sharee.bike-App/TINKLib/ViewModel/Bikes/Bike/BluetoothLock/RequestHandler/ReservedDisconnected.cs
2023-11-06 12:23:09 +01:00

544 lines
21 KiB
C#

using System;
using System.Threading.Tasks;
using Serilog;
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock;
using TINK.Model.Connector;
using TINK.Model.Device;
using TINK.Model.User;
using TINK.MultilingualResources;
using TINK.Repository.Exception;
using TINK.Services.BluetoothLock;
using TINK.Services.BluetoothLock.Exception;
using TINK.Services.BluetoothLock.Tdo;
using TINK.Services.CopriApi.Exception;
using TINK.Services.Geolocation;
using TINK.View;
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
public class ReservedDisconnected : Base, IRequestHandler
{
/// <param name="smartDevice">Provides info about the smart device (phone, tablet, ...)</param>
/// <param name="bikesViewModel">View model to be used for progress report and unlocking/ locking view.</param>
public ReservedDisconnected(
IBikeInfoMutable selectedBike,
Func<bool> isConnectedDelegate,
Func<bool, IConnector> connectorFactory,
IGeolocationService geolocation,
ILocksService lockService,
Func<IPollingUpdateTaskManager> viewUpdateManager,
ISmartDevice smartDevice,
IViewService viewService,
IBikesViewModel bikesViewModel,
IUser activeUser) : base(
selectedBike,
AppResources.ActionCancelReservation,
true, // Show button "Cancel Reservation".
isConnectedDelegate,
connectorFactory,
geolocation,
lockService,
viewUpdateManager,
smartDevice,
viewService,
bikesViewModel,
activeUser)
{
LockitButtonText = AppResources.ActionSearchLock;
IsLockitButtonVisible = true; // Show button "Search Lock"
}
/// <summary> Cancel reservation. </summary>
public async Task<IRequestHandler> HandleRequestOption1() => await CancelReservation();
/// <summary> Connect to reserved bike ask whether to rent bike or not and if yes open lock. </summary>
/// <returns></returns>
public async Task<IRequestHandler> HandleRequestOption2() => await ConnectLockAndRentBike();
/// <summary> Cancel reservation. </summary>
public async Task<IRequestHandler> CancelReservation()
{
Log.ForContext<ReservedDisconnected>().Information("User request to cancel reservation of bike {bikeId}", SelectedBike.Id);
BikesViewModel.IsIdle = false; // Lock list to avoid multiple taps while copri action is pending.
var alertResult = await ViewService.DisplayAlert(
string.Empty,
string.Format(AppResources.QuestionCancelReservation, SelectedBike.GetFullDisplayName()),
AppResources.MessageAnswerYes,
AppResources.MessageAnswerNo);
if (alertResult == false)
{
// User aborted cancel process
Log.ForContext<ReservedDisconnected>().Information("User canceled request to cancel reservation of bike {bikeId}.", SelectedBike.Id);
BikesViewModel.IsIdle = true;
return this;
}
// Stop polling before cancel request.
BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease;
await ViewUpdateManager().StopAsync();
BikesViewModel.ActionText = AppResources.ActivityTextCancelingReservation;
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.DoCancelReservation(SelectedBike);
Log.ForContext<ReservedDisconnected>().Information("User canceled reservation of bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedDisconnected>().Information("User selected reserved bike {bikeId} but cancel reservation failed.", SelectedBike.Id);
BikesViewModel.ActionText = string.Empty;
if (exception is InvalidAuthorizationResponseException)
{
// Copri response is invalid.
Log.ForContext<ReservedDisconnected>().Error("Invalid auth. response.");
await ViewService.DisplayAlert(
AppResources.ErrorCancelReservationTitle,
AppResources.ErrorAccountInvalidAuthorization,
AppResources.MessageAnswerOk);
}
else if (exception is WebConnectFailureException
|| exception is RequestNotCachableException)
{
// Copri server is not reachable.
Log.ForContext<ReservedDisconnected>().Error("Copri server not reachable.");
await ViewService.DisplayAlert(
AppResources.ErrorCancelReservationTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedDisconnected>().Error("{@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorCancelReservationTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
/// <summary> Connect to reserved bike ask whether to rent bike or not and if yes open lock. </summary>
/// <returns></returns>
public async Task<IRequestHandler> ConnectLockAndRentBike()
{
BikesViewModel.IsIdle = false;
Log.ForContext<ReservedDisconnected>().Information("User request to connect to lock of bike {bikeId}.", SelectedBike.Id);
// Stop polling before getting new auth-values.
BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease;
await ViewUpdateManager().StopAsync();
BikesViewModel.ActionText = AppResources.ActivityTextQuerryServer;
IsConnected = IsConnectedDelegate();
try
{
// Repeat reservation to get a new seed/ k_user value.
await ConnectorFactory(IsConnected).Command.CalculateAuthKeys(SelectedBike);
Log.ForContext<ReservedDisconnected>().Information("Calculation of AuthKeys successfully.");
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
if (exception is WebConnectFailureException
|| exception is RequestNotCachableException)
{
// Copri server is not reachable.
Log.ForContext<ReservedDisconnected>().Information("Calculation of AuthKeys failed (Copri server not reachable).");
await ViewService.DisplayAlert(
AppResources.ErrorNoConnectionTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedDisconnected>().Error("Calculation of AuthKeys failed. {@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorConnectLockTitle,
exception.Message,
AppResources.ErrorConnectLock,
AppResources.MessageAnswerOk);
}
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync();
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true;
return this;
}
// Connect to lock.
LockInfoTdo result = null;
var continueConnect = true;
var retryCount = 1;
while (continueConnect && result == null)
{
BikesViewModel.ActionText = AppResources.ActivityTextSearchingLock;
try
{
result = await LockService.ConnectAsync(
new LockInfoAuthTdo.Builder
{
Id = SelectedBike.LockInfo.Id,
Guid = SelectedBike.LockInfo.Guid,
K_seed = SelectedBike.LockInfo.Seed,
K_u = SelectedBike.LockInfo.UserKey
}.Build(),
LockService.TimeOut.GetSingleConnect(retryCount));
Log.ForContext<ReservedDisconnected>().Information("Connected to lock of bike {bikeId} successfully. Value is {lockState}.", SelectedBike.Id, SelectedBike.LockInfo.State);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
if (exception is ConnectBluetoothNotOnException)
{
continueConnect = false;
await ViewService.DisplayAlert(
AppResources.ErrorConnectLockTitle,
AppResources.ErrorLockBluetoothNotOn,
AppResources.MessageAnswerOk);
Log.ForContext<ReservedDisconnected>().Debug("Connection to lock of bike {bikeId} failed, bluetooth is off.", SelectedBike.Id);
}
else if (exception is ConnectLocationPermissionMissingException)
{
continueConnect = false;
await ViewService.DisplayAlert(
AppResources.ErrorConnectLockTitle,
AppResources.ErrorNoLocationPermission,
AppResources.MessageAnswerOk);
Log.ForContext<ReservedDisconnected>().Debug("Connection to lock of bike {bikeId} failed, location permissions are missing.", SelectedBike.Id);
}
else if (exception is ConnectLocationOffException)
{
continueConnect = false;
await ViewService.DisplayAlert(
AppResources.ErrorConnectLockTitle,
AppResources.ErrorLockLocationOff,
AppResources.MessageAnswerOk);
Log.ForContext<ReservedDisconnected>().Debug("Connection to lock of bike {bikeId} failed, location services are off.", SelectedBike.Id);
}
else if (exception is OutOfReachException)
{
continueConnect = false;
await ViewService.DisplayAlert(
AppResources.ErrorConnectLockTitle,
AppResources.ErrorLockOutOfReach,
AppResources.MessageAnswerOk);
Log.ForContext<ReservedDisconnected>().Debug("Connection to lock of bike {bikeId} failed, lock is out of reach.", SelectedBike.Id);
}
else
{
Log.ForContext<ReservedDisconnected>().Error("Lock of bike {bikeId} can not be found. {Exception}", SelectedBike.Id, exception);
string message;
if (retryCount < 2)
{
message = AppResources.ErrorConnectLock;
}
else
{
message = AppResources.ErrorConnectLockEscalationLevel1;
}
Log.ForContext<ReservedDisconnected>().Error("Lock state can not be retrieved. {Exception}", exception);
continueConnect = await ViewService.DisplayAdvancedAlert(
AppResources.ErrorConnectLockTitle,
message,
"", // Might show detailed info in future versions. Property used earlier: IsReportLevelVerbose. Maybe use ActiveUser.DebugLevel.HasFlag(Permissions.ReportLevel) instead.
AppResources.MessageAnswerRetry,
AppResources.MessageAnswerCancel);
}
if (continueConnect)
{
retryCount++;
continue;
}
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync();
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true;
return this;
}
}
if (!(result?.State is LockitLockingState lockingState))
{
Log.ForContext<ReservedDisconnected>().Information("Lock for bike {bikeId} not found.", SelectedBike.Id);
BikesViewModel.ActionText = string.Empty;
await ViewService.DisplayAlert(
AppResources.ErrorConnectLockTitle,
AppResources.ErrorLockNoStatus,
AppResources.MessageAnswerOk);
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync();
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true;
return this;
}
// get current locking state
var state = lockingState.GetLockingState();
SelectedBike.LockInfo.State = state;
SelectedBike.LockInfo.Guid = result?.Guid ?? new Guid();
// Ask whether to really book bike?
var alertResult
= SelectedBike.LockInfo.State != LockingState.Open
? await ViewService.DisplayAlert(
string.Empty,
string.Format(AppResources.QuestionOpenLockAndBookBike, SelectedBike.GetFullDisplayName()),
AppResources.MessageAnswerYes,
AppResources.MessageAnswerNo)
: await ViewService.DisplayAlert(
string.Empty,
string.Format(AppResources.QuestionBookBike, SelectedBike.GetFullDisplayName()),
AppResources.MessageAnswerYes,
AppResources.MessageAnswerNo);
if (alertResult == false)
{
// User aborted booking process
Log.ForContext<ReservedDisconnected>().Information("User denied to book reserved bike {bikeId}.", SelectedBike.Id);
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
Log.ForContext<ReservedDisconnected>().Information("Lock of bike {bikeId} disconnected successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedDisconnected>().Error("Lock of bike {bikeId} can not be disconnected. {Exception}", SelectedBike.Id, exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync();
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true;
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
// Book bike prior to opening lock.
Log.ForContext<ReservedDisconnected>().Information("User request to book reserved bike {bikeId}.", SelectedBike.Id);
BikesViewModel.ActionText = AppResources.ActivityTextRentingBike;
IsConnected = IsConnectedDelegate();
try
{
if (SelectedBike.LockInfo.State != LockingState.Open)
{
await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike, LockingAction.Open);
}
else
{
await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike);
}
Log.ForContext<ReservedDisconnected>().Information("User booked bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
if (exception is WebConnectFailureException)
{
// Copri server is not reachable.
Log.ForContext<ReservedDisconnected>().Information("Booking of bike {bikeId} failed (Copri server not reachable).", SelectedBike.Id);
await ViewService.DisplayAlert(
AppResources.ErrorRentingBikeTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedDisconnected>().Error("Booking of bike {bikeId} failed. {@exception}", SelectedBike.Id, exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorRentingBikeTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
}
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync(); // Restart polling again.
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
// Unlock bike.
ILockService btLock = LockService[SelectedBike.LockInfo.Id];
if (SelectedBike.LockInfo.State != LockingState.Open)
{
BikesViewModel.ActionText = AppResources.ActivityTextOpeningLock;
try
{
SelectedBike.LockInfo.State = (await btLock.OpenAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected;
Log.ForContext<ReservedDisconnected>().Debug("Lock from {bikeId} opened successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
if (exception is OutOfReachException)
{
Log.ForContext<ReservedDisconnected>().Debug("Lock from {bikeId} can not be opened. {Exception}", SelectedBike.Id, exception);
await ViewService.DisplayAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorLockOutOfReach,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenBoldIsBlockedException)
{
Log.ForContext<ReservedDisconnected>().Debug("Lock from {bikeId} can not be opened. Bold is blocked. {Exception}", SelectedBike.Id, exception);
await ViewService.DisplayAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockBoldBlocked,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenBoldStatusIsUnknownException)
{
Log.ForContext<ReservedDisconnected>().Debug("Lock from {bikeId} can not be opened. Bold status is unknown. {Exception}", SelectedBike.Id, exception);
await ViewService.DisplayAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockStatusUnknown,
AppResources.MessageAnswerOk);
}
else if (exception is CouldntOpenInconsistentStateExecption inconsistentState
&& inconsistentState.State == LockingState.Closed)
{
Log.ForContext<ReservedDisconnected>().Debug("Lock from {bikeId} can not be opened. lock reports state closed. {Exception}", SelectedBike.Id, exception);
await ViewService.DisplayAlert(
AppResources.ErrorOpenLockTitle,
AppResources.ErrorOpenLockStillClosed,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<ReservedDisconnected>().Error("Lock from {bikeId} can not be opened. {Exception}", SelectedBike.Id, exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorOpenLockTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
}
SelectedBike.LockInfo.State = exception is StateAwareException stateAwareException
? stateAwareException.State
: LockingState.UnknownDisconnected;
}
}
// get current charging level
BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel;
try
{
SelectedBike.LockInfo.BatteryPercentage = await btLock.GetBatteryPercentageAsync();
Log.ForContext<ReservedDisconnected>().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
if (exception is OutOfReachException)
{
Log.ForContext<ReservedDisconnected>().Debug("Battery state of lock from {bikeId} can not be read, bike out of range. {Exception}", SelectedBike.Id, exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach;
}
else
{
Log.ForContext<ReservedDisconnected>().Error("Battery state of lock from {bikeId} can not be read. {Exception}", SelectedBike.Id, exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral;
}
}
// Lock list to avoid multiple taps while copri action is pending.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdatingLockingState;
var versionTdo = btLock.VersionInfo;
if (versionTdo != null)
{
SelectedBike.LockInfo.VersionInfo = new VersionInfo.Builder
{
FirmwareVersion = versionTdo.FirmwareVersion,
HardwareVersion = versionTdo.HardwareVersion,
LockVersion = versionTdo.LockVersion,
}.Build();
}
// update backend
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.UpdateLockingStateAsync(SelectedBike);
Log.ForContext<ReservedDisconnected>().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedDisconnected>().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// No web.
Log.ForContext<ReservedDisconnected>().Debug("Copri server not reachable. No web.");
BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate;
}
else if (exception is ResponseException copriException)
{
// Copri exception.
Log.ForContext<ReservedDisconnected>().Debug("{response}.", copriException.Response);
BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate;
}
else
{
Log.ForContext<ReservedDisconnected>().Debug("{@exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorConnectionUpdateingLockstate;
}
}
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
await ViewUpdateManager().StartAsync();
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true; // Unlock GUI
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
}
}
}