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.CopriApi.Exception; using TINK.Services.Geolocation; using TINK.View; namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler { /// Bike is disposable, lock is open and connected to app. /// /// This state can not be occur because /// - app does not allow to return bike/ cancel reservation when lock is not closed /// - as long as app is connected to lock /// - lock can not be opened manually /// - no other device can access lock /// public class DisposableOpen : Base, IRequestHandler { /// Bike is disposable, lock is open and can be reached via bluetooth. /// /// This state should never occur because as long as a ILOCKIT is connected it /// - cannot be closed manually /// - no other device can access lock /// - app itself should never event attempt to open a lock which is not rented. /// /// Provides info about the smart device (phone, tablet, ...) /// View model to be used for progress report and unlocking/ locking view. public DisposableOpen( IBikeInfoMutable selectedBike, Func isConnectedDelegate, Func connectorFactory, IGeolocationService geolocation, ILocksService lockService, Func viewUpdateManager, ISmartDevice smartDevice, IViewService viewService, IBikesViewModel bikesViewModel, IUser activeUser) : base( selectedBike, AppResources.ActionRentBike, // Rent Bike true, // Show button "Rent Bike" isConnectedDelegate, connectorFactory, geolocation, lockService, viewUpdateManager, smartDevice, viewService, bikesViewModel, activeUser) { LockitButtonText = AppResources.ActionCloseLock; // Close Lock IsLockitButtonVisible = true; // Show button "Close Lock" } /// Rents bike by reserving bike and renting bike. /// Next request handler. public async Task HandleRequestOption1() => await RentBike(); /// Closes Lock. /// Next request handler. public async Task HandleRequestOption2() => await CloseLock(); public async Task RentBike() { Log.ForContext().Information("User request to book bike {bikeId}.", SelectedBike.Id); BikesViewModel.IsIdle = false; // Stop polling before requesting bike. BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease; await ViewUpdateManager().StopAsync(); //reserve bike prior to book. BikesViewModel.ActionText = AppResources.ActivityTextReservingBike; IsConnected = IsConnectedDelegate(); try { await ConnectorFactory(IsConnected).Command.DoReserve(SelectedBike); Log.ForContext().Information("User reserved bike {bikeId} successfully.", SelectedBike.Id); } catch (Exception exception) { BikesViewModel.ActionText = string.Empty; Log.ForContext().Information("Request to reserve bike {bikeId} declined.", SelectedBike.Id); if (exception is BookingDeclinedException) { // Too many bikes booked. Log.ForContext().Error("Maximum count of bikes {exception.MaxBikesCount} already requested/ booked.", (exception as BookingDeclinedException).MaxBikesCount); await ViewService.DisplayAlert( AppResources.MessageHintTitle, string.Format(AppResources.ErrorReservingBikeTooManyReservationsRentals, SelectedBike.Id, (exception as BookingDeclinedException).MaxBikesCount), AppResources.MessageAnswerOk); } else if (exception is WebConnectFailureException || exception is RequestNotCachableException) { // Copri server is not reachable. Log.ForContext().Error("Copri server not reachable."); await ViewService.DisplayAlert( AppResources.ErrorNoConnectionTitle, AppResources.ErrorNoWeb, AppResources.MessageAnswerOk); } else { Log.ForContext().Error("{@exception}", exception); await ViewService.DisplayAdvancedAlert( AppResources.ErrorReservingBikeTitle, exception.Message, AppResources.ErrorTryAgain, AppResources.MessageAnswerOk); } // Disconnect lock. BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock; try { SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid); Log.ForContext().Information("Lock from bike {bikeId} disconnected successfully.", SelectedBike.Id); } catch (Exception disconnectException) { Log.ForContext().Information("Lock from bike {bikeId} can not be disconnected. {@exception}", SelectedBike.Id, disconnectException); BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect; } // Restart polling again. BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater; await ViewUpdateManager().StartAsync(); BikesViewModel.ActionText = string.Empty; BikesViewModel.IsIdle = true; return this; } // Book bike BikesViewModel.ActionText = AppResources.ActivityTextRentingBike; IsConnected = IsConnectedDelegate(); try { await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike); Log.ForContext().Information("User booked bike {bikeId} successfully.", SelectedBike.Id); } catch (Exception exception) { BikesViewModel.ActionText = string.Empty; Log.ForContext().Information("Booking of bike {bikeId} failed.", SelectedBike.Id); if (exception is WebConnectFailureException) { // Copri server is not reachable. Log.ForContext().Error("Copri server not reachable."); await ViewService.DisplayAlert( AppResources.ErrorNoConnectionTitle, AppResources.ErrorNoWeb, AppResources.MessageAnswerOk); } else { Log.ForContext().Error("{@exception}", exception); await ViewService.DisplayAlert( AppResources.ErrorRentingBikeTitle, exception.Message, AppResources.MessageAnswerOk); } // Disconnect lock. BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock; try { SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid); Log.ForContext().Error("Lock from bike {bikeId} disconnected successfully.", SelectedBike.Id); } catch (Exception disconnectException) { Log.ForContext().Error("Lock from bike {bikeId} can not be disconnected. {Exception}", SelectedBike.Id, disconnectException); BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect; } 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); } // Get current charging level BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel; ILockService btLock = LockService[SelectedBike.LockInfo.Id]; try { SelectedBike.LockInfo.BatteryPercentage = await btLock.GetBatteryPercentageAsync(); Log.ForContext().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id); } catch (Exception exception) { Log.ForContext().Information("Battery state of lock from {bikeId} can not be read.", SelectedBike.Id); if (exception is OutOfReachException) { Log.ForContext().Debug("Lock is out of reach."); BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach; } else { Log.ForContext().Error("{@exception}", exception); BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral; } } // Get lock infos. 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().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id); } catch (Exception exception) { Log.ForContext().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id); if (exception is WebConnectFailureException) { // No web. Log.ForContext().Debug("Copri server not reachable. No web"); BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate; } else if (exception is ResponseException copriException) { // Copri exception. Log.ForContext().Debug("{response}", copriException.Response); BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate; } else { Log.ForContext().Debug("{@exception}", exception); BikesViewModel.ActionText = AppResources.ActivityTextErrorConnectionUpdateingLockstate; } } 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); } public async Task CloseLock() { Log.ForContext().Information("User request to close lock of bike {bikeId}.", SelectedBike.Id); BikesViewModel.IsIdle = false; // Stop polling before requesting bike. BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease; await ViewUpdateManager().StopAsync(); // Close lock BikesViewModel.ActionText = AppResources.ActivityTextClosingLock; try { SelectedBike.LockInfo.State = (await LockService[SelectedBike.LockInfo.Id].CloseAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected; Log.ForContext().Information("Lock of bike {bikeId} closed successfully.", SelectedBike.Id); } catch (Exception exception) { Log.ForContext().Information("Lock of bike {bikeId} can not be closed.", SelectedBike.Id); BikesViewModel.ActionText = string.Empty; if (exception is OutOfReachException) { Log.ForContext().Debug("Lock is out of reach."); await ViewService.DisplayAlert( AppResources.ErrorCloseLockTitle, AppResources.ErrorLockOutOfReach, AppResources.MessageAnswerOk); } else if (exception is CouldntCloseMovingException) { Log.ForContext().Debug("Lock is moving."); await ViewService.DisplayAlert( AppResources.ErrorCloseLockTitle, AppResources.ErrorLockMoving, AppResources.MessageAnswerOk); } else if (exception is CouldntCloseBoltBlockedException) { Log.ForContext().Debug("Bold is blocked."); await ViewService.DisplayAlert( AppResources.ErrorCloseLockTitle, AppResources.ErrorCloseLockBoltBlocked, AppResources.MessageAnswerOk); } else { Log.ForContext().Debug("{@exception}", exception); await ViewService.DisplayAdvancedAlert( AppResources.ErrorCloseLockTitle, exception.Message, AppResources.ErrorTryAgain, AppResources.MessageAnswerOk); } SelectedBike.LockInfo.State = exception is StateAwareException stateAwareException ? stateAwareException.State : LockingState.UnknownDisconnected; } // get current charging level ILockService btLock = LockService[SelectedBike.LockInfo.Id]; BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel; try { SelectedBike.LockInfo.BatteryPercentage = await btLock.GetBatteryPercentageAsync(); Log.ForContext().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id); } catch (Exception exception) { Log.ForContext().Information("Battery state of lock from {bikeId} can not be read", SelectedBike.Id); if (exception is OutOfReachException) { Log.ForContext().Debug("Lock is out of reach."); BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach; } else { Log.ForContext().Debug("{@exception}", exception); BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral; } } // Get lock infos. 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().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id); } catch (Exception exception) { Log.ForContext().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id); if (exception is WebConnectFailureException) { // No web. Log.ForContext().Debug("Copri server not reachable. No web."); BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate; } else if (exception is ResponseException copriException) { // Copri exception. Log.ForContext().Debug("{response}", copriException.Response); BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate; } else { Log.ForContext().Debug("{@exception}", exception); BikesViewModel.ActionText = AppResources.ActivityTextErrorConnectionUpdateingLockstate; } } // Disconnect lock. BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock; try { SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid); Log.ForContext().Error("Lock of bike {bikeId} disconnected successfully.", SelectedBike.Id); } catch (Exception disconnectException) { Log.ForContext().Error("Lock of bike {bikeId} can not be disconnected. {@exception}", SelectedBike.Id, disconnectException); BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect; } 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); } } }