sharee.bike-App/TINKLib/ViewModel/Bikes/Bike/BluetoothLock/RequestHandler/DisposableOpen.cs

420 lines
16 KiB
C#
Raw Normal View History

2023-04-19 12:14:14 +02:00
using System;
2021-05-13 20:03:07 +02:00
using System.Threading.Tasks;
2022-08-30 15:42:25 +02:00
using Serilog;
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock;
2021-05-13 20:03:07 +02:00
using TINK.Model.Connector;
2022-08-30 15:42:25 +02:00
using TINK.Model.Device;
using TINK.Model.User;
using TINK.MultilingualResources;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Exception;
2021-05-13 20:03:07 +02:00
using TINK.Services.BluetoothLock;
using TINK.Services.BluetoothLock.Exception;
2023-11-06 12:23:09 +01:00
using TINK.Services.CopriApi.Exception;
2022-08-30 15:42:25 +02:00
using TINK.Services.Geolocation;
using TINK.View;
2021-05-13 20:03:07 +02:00
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
2022-09-06 16:08:19 +02:00
/// <summary> Bike is disposable, lock is open and connected to app. </summary>
/// <remarks>
/// 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
/// </remarks>
public class DisposableOpen : Base, IRequestHandler
{
/// <summary> Bike is disposable, lock is open and can be reached via bluetooth. </summary>
/// <remarks>
2023-04-19 12:14:14 +02:00
/// This state should never occur because as long as a ILOCKIT is connected it
2022-09-06 16:08:19 +02:00
/// - cannot be closed manually
/// - no other device can access lock
/// - app itself should never event attempt to open a lock which is not rented.
/// </remarks>
/// <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 DisposableOpen(
IBikeInfoMutable selectedBike,
Func<bool> isConnectedDelegate,
Func<bool, IConnector> connectorFactory,
2023-04-05 15:02:10 +02:00
IGeolocationService geolocation,
2022-09-06 16:08:19 +02:00
ILocksService lockService,
Func<IPollingUpdateTaskManager> viewUpdateManager,
ISmartDevice smartDevice,
IViewService viewService,
IBikesViewModel bikesViewModel,
IUser activeUser) : base(
selectedBike,
2023-11-06 12:23:09 +01:00
AppResources.ActionRentBike, // Rent Bike
true, // Show button "Rent Bike"
2022-09-06 16:08:19 +02:00
isConnectedDelegate,
connectorFactory,
geolocation,
lockService,
viewUpdateManager,
smartDevice,
viewService,
bikesViewModel,
activeUser)
{
2023-11-06 12:23:09 +01:00
LockitButtonText = AppResources.ActionCloseLock; // Close Lock
IsLockitButtonVisible = true; // Show button "Close Lock"
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
/// <summary>Rents bike by reserving bike and renting bike.</summary>
2022-09-06 16:08:19 +02:00
/// <returns>Next request handler.</returns>
2023-11-06 12:23:09 +01:00
public async Task<IRequestHandler> HandleRequestOption1() => await RentBike();
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
/// <summary>Closes Lock.</summary>
2022-09-06 16:08:19 +02:00
/// <returns>Next request handler.</returns>
2023-11-06 12:23:09 +01:00
public async Task<IRequestHandler> HandleRequestOption2() => await CloseLock();
public async Task<IRequestHandler> RentBike()
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Information("User request to book bike {bikeId}.", SelectedBike.Id);
BikesViewModel.IsIdle = false;
2022-09-06 16:08:19 +02:00
// Stop polling before requesting bike.
BikesViewModel.ActionText = AppResources.ActivityTextOneMomentPlease;
2023-08-31 12:20:06 +02:00
await ViewUpdateManager().StopAsync();
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
//reserve bike prior to book.
BikesViewModel.ActionText = AppResources.ActivityTextReservingBike;
IsConnected = IsConnectedDelegate();
try
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
await ConnectorFactory(IsConnected).Command.DoReserve(SelectedBike);
Log.ForContext<DisposableOpen>().Information("User reserved bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
Log.ForContext<DisposableOpen>().Information("Request to reserve bike {bikeId} declined.", SelectedBike.Id);
if (exception is BookingDeclinedException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
// Too many bikes booked.
Log.ForContext<DisposableOpen>().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);
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
else if (exception is WebConnectFailureException
|| exception is RequestNotCachableException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
// Copri server is not reachable.
Log.ForContext<DisposableOpen>().Error("Copri server not reachable.");
await ViewService.DisplayAlert(
AppResources.ErrorNoConnectionTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<DisposableOpen>().Error("{@exception}", exception);
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorReservingBikeTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
2022-09-06 16:08:19 +02:00
}
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Information("Lock from bike {bikeId} disconnected successfully.", SelectedBike.Id);
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
catch (Exception disconnectException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Information("Lock from bike {bikeId} can not be disconnected. {@exception}", SelectedBike.Id, disconnectException);
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
2023-11-06 12:23:09 +01:00
// Restart polling again.
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
2023-08-31 12:20:06 +02:00
await ViewUpdateManager().StartAsync();
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = string.Empty;
BikesViewModel.IsIdle = true;
2023-11-06 12:23:09 +01:00
return this;
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
// Book bike
BikesViewModel.ActionText = AppResources.ActivityTextRentingBike;
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike);
Log.ForContext<DisposableOpen>().Information("User booked bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
Log.ForContext<DisposableOpen>().Information("Booking of bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// Copri server is not reachable.
Log.ForContext<DisposableOpen>().Error("Copri server not reachable.");
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
await ViewService.DisplayAlert(
AppResources.ErrorNoConnectionTitle,
AppResources.ErrorNoWeb,
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<DisposableOpen>().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<DisposableOpen>().Error("Lock from bike {bikeId} disconnected successfully.", SelectedBike.Id);
}
catch (Exception disconnectException)
{
Log.ForContext<DisposableOpen>().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
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel;
2023-11-06 12:23:09 +01:00
ILockService btLock = LockService[SelectedBike.LockInfo.Id];
2022-09-06 16:08:19 +02:00
try
{
2023-11-06 12:23:09 +01:00
SelectedBike.LockInfo.BatteryPercentage = await btLock.GetBatteryPercentageAsync();
Log.ForContext<DisposableOpen>().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id);
2022-09-06 16:08:19 +02:00
}
catch (Exception exception)
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Information("Battery state of lock from {bikeId} can not be read.", SelectedBike.Id);
2022-09-06 16:08:19 +02:00
if (exception is OutOfReachException)
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Debug("Lock is out of reach.");
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach;
}
else
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Error("{@exception}", exception);
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral;
}
}
2023-11-06 12:23:09 +01:00
// 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
2022-09-06 16:08:19 +02:00
IsConnected = IsConnectedDelegate();
try
{
2023-11-06 12:23:09 +01:00
await ConnectorFactory(IsConnected).Command.UpdateLockingStateAsync(SelectedBike);
Log.ForContext<DisposableOpen>().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id);
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
catch (Exception exception)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// No web.
Log.ForContext<DisposableOpen>().Debug("Copri server not reachable. No web");
BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate;
}
else if (exception is ResponseException copriException)
{
// Copri exception.
Log.ForContext<DisposableOpen>().Debug("{response}", copriException.Response);
BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate;
}
else
{
Log.ForContext<DisposableOpen>().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<IRequestHandler> CloseLock()
{
Log.ForContext<DisposableOpen>().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();
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
// Close lock
BikesViewModel.ActionText = AppResources.ActivityTextClosingLock;
try
{
SelectedBike.LockInfo.State = (await LockService[SelectedBike.LockInfo.Id].CloseAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected;
Log.ForContext<DisposableOpen>().Information("Lock of bike {bikeId} closed successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<DisposableOpen>().Information("Lock of bike {bikeId} can not be closed.", SelectedBike.Id);
BikesViewModel.ActionText = string.Empty;
if (exception is OutOfReachException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Debug("Lock is out of reach.");
2022-09-06 16:08:19 +02:00
await ViewService.DisplayAlert(
2023-11-06 12:23:09 +01:00
AppResources.ErrorCloseLockTitle,
AppResources.ErrorLockOutOfReach,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
2023-11-06 12:23:09 +01:00
else if (exception is CouldntCloseMovingException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Debug("Lock is moving.");
2022-09-06 16:08:19 +02:00
await ViewService.DisplayAlert(
2023-11-06 12:23:09 +01:00
AppResources.ErrorCloseLockTitle,
AppResources.ErrorLockMoving,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
2023-11-06 12:23:09 +01:00
else if (exception is CouldntCloseBoltBlockedException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Debug("Bold is blocked.");
await ViewService.DisplayAlert(
AppResources.ErrorCloseLockTitle,
AppResources.ErrorCloseLockBoltBlocked,
AppResources.MessageAnswerOk);
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
else
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<DisposableOpen>().Debug("{@exception}", exception);
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
await ViewService.DisplayAdvancedAlert(
AppResources.ErrorCloseLockTitle,
exception.Message,
AppResources.ErrorTryAgain,
AppResources.MessageAnswerOk);
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
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<ReservedOpen>().Information("Battery state of lock from {bikeId} read successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedOpen>().Information("Battery state of lock from {bikeId} can not be read", SelectedBike.Id);
if (exception is OutOfReachException)
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<ReservedOpen>().Debug("Lock is out of reach.");
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach;
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
else
2022-09-06 16:08:19 +02:00
{
2023-11-06 12:23:09 +01:00
Log.ForContext<ReservedOpen>().Debug("{@exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral;
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
}
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
// 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();
}
2022-09-06 16:08:19 +02:00
2023-11-06 12:23:09 +01:00
// update backend
IsConnected = IsConnectedDelegate();
try
{
await ConnectorFactory(IsConnected).Command.UpdateLockingStateAsync(SelectedBike);
Log.ForContext<ReservedOpen>().Information("Backend updated for bike {bikeId} successfully.", SelectedBike.Id);
}
catch (Exception exception)
{
Log.ForContext<ReservedOpen>().Information("Updating backend for bike {bikeId} failed.", SelectedBike.Id);
if (exception is WebConnectFailureException)
{
// No web.
Log.ForContext<ReservedOpen>().Debug("Copri server not reachable. No web.");
BikesViewModel.ActionText = AppResources.ActivityTextErrorNoWebUpdateingLockstate;
}
else if (exception is ResponseException copriException)
{
// Copri exception.
Log.ForContext<ReservedOpen>().Debug("{response}", copriException.Response);
BikesViewModel.ActionText = AppResources.ActivityTextErrorStatusUpdateingLockstate;
}
else
{
Log.ForContext<ReservedOpen>().Debug("{@exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorConnectionUpdateingLockstate;
}
2022-09-06 16:08:19 +02:00
}
2023-11-06 12:23:09 +01:00
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
Log.ForContext<DisposableOpen>().Error("Lock of bike {bikeId} disconnected successfully.", SelectedBike.Id);
}
catch (Exception disconnectException)
{
Log.ForContext<DisposableOpen>().Error("Lock of bike {bikeId} can not be disconnected. {@exception}", SelectedBike.Id, disconnectException);
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
2023-08-31 12:20:06 +02:00
await ViewUpdateManager().StartAsync();
2023-11-06 12:23:09 +01:00
BikesViewModel.ActionText = string.Empty;
2022-09-06 16:08:19 +02:00
BikesViewModel.IsIdle = true;
2023-04-05 15:02:10 +02:00
return RequestHandlerFactory.Create(SelectedBike, IsConnectedDelegate, ConnectorFactory, GeolocationService, LockService, ViewUpdateManager, SmartDevice, ViewService, BikesViewModel, ActiveUser);
2022-09-06 16:08:19 +02:00
}
}
2021-05-13 20:03:07 +02:00
}