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

283 lines
11 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;
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-08-31 12:20:06 +02:00
AppResources.ActionCloseOrBook,
2022-09-06 16:08:19 +02:00
true, // Show copri button to enable reserving
isConnectedDelegate,
connectorFactory,
geolocation,
lockService,
viewUpdateManager,
smartDevice,
viewService,
bikesViewModel,
activeUser)
{
LockitButtonText = GetType().Name;
IsLockitButtonVisible = false;
}
/// <summary>Books bike by reserving bike, opening lock and booking bike.</summary>
/// <returns>Next request handler.</returns>
2023-07-19 10:10:36 +02:00
public async Task<IRequestHandler> HandleRequestOption1() => await CloseLockOrDoBook();
2022-09-06 16:08:19 +02:00
public async Task<IRequestHandler> HandleRequestOption2() => await UnsupportedRequest();
/// <summary>Books bike by reserving bike, opening lock and booking bike.</summary>
/// <returns>Next request handler.</returns>
2023-07-19 10:10:36 +02:00
public async Task<IRequestHandler> CloseLockOrDoBook()
2022-09-06 16:08:19 +02:00
{
BikesViewModel.IsIdle = false; // Lock list to avoid multiple taps while copri action is pending.
// 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
// Ask whether to really book bike or close lock?
var l_oResult = await ViewService.DisplayAlert(
string.Empty,
2023-08-31 12:20:06 +02:00
String.Format(AppResources.QuestionCloseOrBook, SelectedBike.GetFullDisplayName()),
AppResources.ActionBook,
AppResources.ActionClose);
2022-09-06 16:08:19 +02:00
if (l_oResult == false)
{
// Close lock
Log.ForContext<DisposableOpen>().Information("User selected disposable bike {bike} in order to close lock.", SelectedBike);
BikesViewModel.ActionText = AppResources.ActivityTextClosingLock;
try
{
SelectedBike.LockInfo.State = (await LockService[SelectedBike.LockInfo.Id].CloseAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected;
}
catch (Exception exception)
{
BikesViewModel.ActionText = string.Empty;
if (exception is OutOfReachException)
{
Log.ForContext<DisposableOpen>().Debug("Lock can not be closed. {Exception}", exception);
await ViewService.DisplayAlert(
AppResources.ErrorCloseLockTitle,
2023-08-31 12:20:06 +02:00
AppResources.ErrorLockOutOfReach,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
else if (exception is CouldntCloseMovingException)
{
Log.ForContext<DisposableOpen>().Debug("Lock can not be closed. Lock is out of reach. {Exception}", exception);
await ViewService.DisplayAlert(
AppResources.ErrorCloseLockTitle,
2023-08-31 12:20:06 +02:00
AppResources.ErrorLockMoving,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
2023-08-31 12:20:06 +02:00
else if (exception is CouldntCloseBoltBlockedException)
2022-09-06 16:08:19 +02:00
{
Log.ForContext<DisposableOpen>().Debug("Lock can not be closed. Lock is out of reach. {Exception}", exception);
await ViewService.DisplayAlert(
AppResources.ErrorCloseLockTitle,
2023-08-31 12:20:06 +02:00
AppResources.ErrorCloseLockBoltBlocked,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<DisposableOpen>().Error("Lock can not be closed. {Exception}", exception);
2023-08-31 12:20:06 +02:00
await ViewService.DisplayAdvancedAlert(
2022-09-06 16:08:19 +02:00
AppResources.ErrorCloseLockTitle,
exception.Message,
2023-08-31 12:20:06 +02:00
AppResources.ErrorTryAgain,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
SelectedBike.LockInfo.State = exception is StateAwareException stateAwareException
? stateAwareException.State
: LockingState.UnknownDisconnected;
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-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
}
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
}
catch (Exception exception)
{
Log.ForContext<DisposableOpen>().Error("Lock can not be disconnected. {Exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
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-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
}
// Lock list to avoid multiple taps while copri action is pending.
Log.ForContext<DisposableOpen>().Information("Request to book bike {bike}.", SelectedBike);
BikesViewModel.ActionText = AppResources.ActivityTextReadingChargingLevel;
try
{
SelectedBike.LockInfo.BatteryPercentage = await LockService[SelectedBike.LockInfo.Id].GetBatteryPercentageAsync();
}
catch (Exception exception)
{
if (exception is OutOfReachException)
{
2023-04-19 12:14:14 +02:00
Log.ForContext<DisposableOpen>().Debug("Battery state can not be read, bike out of range. {Exception}", exception);
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelOutOfReach;
}
else
{
2023-04-19 12:14:14 +02:00
Log.ForContext<DisposableOpen>().Error("Battery state can not be read. {Exception}", exception);
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextErrorReadingChargingLevelGeneral;
}
}
2023-04-19 12:14:14 +02:00
// Notify copri about unlock action in order to start booking.
2022-09-06 16:08:19 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextRentingBike;
IsConnected = IsConnectedDelegate();
try
{
2022-12-27 21:08:09 +01:00
await ConnectorFactory(IsConnected).Command.DoBookAsync(SelectedBike);
2022-09-06 16:08:19 +02:00
}
catch (Exception l_oException)
{
BikesViewModel.ActionText = string.Empty;
if (l_oException is WebConnectFailureException)
{
// Copri server is not reachable.
Log.ForContext<DisposableOpen>().Information("User selected requested bike {l_oId} but reserving failed (Copri server not reachable).", SelectedBike.Id);
await ViewService.DisplayAlert(
2023-08-31 12:20:06 +02:00
AppResources.ErrorRentingBikeTitle,
AppResources.ErrorNoWeb,
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
else
{
Log.ForContext<DisposableOpen>().Error("User selected requested bike {l_oId} but reserving failed. {@l_oException}", SelectedBike.Id, l_oException);
await ViewService.DisplayAlert(
2023-08-31 12:20:06 +02:00
AppResources.ErrorRentingBikeTitle,
string.Format(l_oException.Message, AppResources.ErrorTryAgain),
2022-09-06 16:08:19 +02:00
AppResources.MessageAnswerOk);
}
// If booking failed lock bike again because bike is only reserved.
2023-08-31 12:20:06 +02:00
BikesViewModel.ActionText = AppResources.ActivityTextClosingLock;
2022-09-06 16:08:19 +02:00
try
{
SelectedBike.LockInfo.State = (await LockService[SelectedBike.LockInfo.Id].CloseAsync())?.GetLockingState() ?? LockingState.UnknownDisconnected;
}
catch (Exception exception)
{
Log.ForContext<DisposableOpen>().Error("Locking bike after booking failure failed. {Exception}", exception);
SelectedBike.LockInfo.State = exception is StateAwareException stateAwareException
? stateAwareException.State
: LockingState.UnknownDisconnected;
}
// Disconnect lock.
BikesViewModel.ActionText = AppResources.ActivityTextDisconnectingLock;
try
{
SelectedBike.LockInfo.State = await LockService.DisconnectAsync(SelectedBike.LockInfo.Id, SelectedBike.LockInfo.Guid);
}
catch (Exception exception)
{
Log.ForContext<DisposableOpen>().Error("Lock can not be disconnected. {Exception}", exception);
BikesViewModel.ActionText = AppResources.ActivityTextErrorDisconnect;
}
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
2023-08-31 12:20:06 +02:00
await ViewUpdateManager().StartAsync();
2022-09-06 16:08:19 +02:00
// Update status text and unlock list of bikes because no more action is pending.
BikesViewModel.ActionText = string.Empty; // Todo: Move this statement in front of finally block because in catch block BikesViewModel.ActionText is already set to empty.
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
}
Log.ForContext<DisposableOpen>().Information("User reserved bike {bike} successfully.", SelectedBike);
// Restart polling again.
BikesViewModel.ActionText = AppResources.ActivityTextStartingUpdater;
2023-08-31 12:20:06 +02:00
await ViewUpdateManager().StartAsync();
2022-09-06 16:08:19 +02:00
// Update status text and unlock list of bikes because no more action is pending.
BikesViewModel.ActionText = string.Empty; // Todo: Move this statement in front of finally block because in catch block BikesViewModel.ActionText is already set to empty.
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
}
2023-04-19 12:14:14 +02:00
/// <summary> Request is not supported, button should be disabled. </summary>
2022-09-06 16:08:19 +02:00
/// <returns></returns>
public async Task<IRequestHandler> UnsupportedRequest()
{
Log.ForContext<DisposableOpen>().Error("Click of unsupported button click detected.");
return await Task.FromResult<IRequestHandler>(this);
}
}
2021-05-13 20:03:07 +02:00
}