2021-05-13 20:03:07 +02:00
using Serilog ;
using System ;
using System.Threading.Tasks ;
using TINK.Model.Bike.BluetoothLock ;
using TINK.Model.Connector ;
using TINK.Model.State ;
using TINK.View ;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Exception ;
2021-05-13 20:03:07 +02:00
using TINK.Model.Services.Geolocation ;
using TINK.Services.BluetoothLock ;
using TINK.Services.BluetoothLock.Exception ;
using TINK.MultilingualResources ;
using TINK.Model.Bikes.Bike.BluetoothLock ;
using TINK.Model.User ;
using Xamarin.Essentials ;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Request ;
using TINK.Model.Device ;
2021-08-28 10:04:10 +02:00
using System.Threading ;
using System.Collections.Generic ;
2021-05-13 20:03:07 +02:00
namespace TINK.ViewModel.Bikes.Bike.BluetoothLock.RequestHandler
{
public class BookedUnknown : Base , IRequestHandler
{
2021-06-26 20:57:55 +02:00
/// <param name="smartDevice">Provides info about the smart device (phone, tablet, ...).</param>
2021-05-13 20:03:07 +02:00
/// <param name="bikesViewModel">View model to be used for progress report and unlocking/ locking view.</param>
public BookedUnknown (
IBikeInfoMutable selectedBike ,
Func < bool > isConnectedDelegate ,
Func < bool , IConnector > connectorFactory ,
IGeolocation geolocation ,
ILocksService lockService ,
Func < IPollingUpdateTaskManager > viewUpdateManager ,
2021-06-26 20:57:55 +02:00
ISmartDevice smartDevice ,
2021-05-13 20:03:07 +02:00
IViewService viewService ,
IBikesViewModel bikesViewModel ,
IUser activeUser ) : base (
selectedBike ,
AppResources . ActionOpenAndPause , // Schloss öffnen und Miete fortsetzen.
true , // Show button to enabled returning of bike.
isConnectedDelegate ,
connectorFactory ,
geolocation ,
lockService ,
viewUpdateManager ,
2021-06-26 20:57:55 +02:00
smartDevice ,
2021-05-13 20:03:07 +02:00
viewService ,
bikesViewModel ,
activeUser )
{
LockitButtonText = AppResources . ActionClose ; // BT button text "Schließen".;
IsLockitButtonVisible = true ; // Show button to enable opening lock in case user took a pause and does not want to return the bike.
}
/// <summary> Gets the bike state. </summary>
public override InUseStateEnum State = > InUseStateEnum . Booked ;
/// <summary> Open bike and update COPRI lock state. </summary>
2021-06-26 20:57:55 +02:00
public async Task < IRequestHandler > HandleRequestOption1 ( ) = > await OpenLock ( ) ;
/// <summary> Close lock in order to pause ride and update COPRI lock state.</summary>
public async Task < IRequestHandler > HandleRequestOption2 ( ) = > await CloseLock ( ) ;
/// <summary> Open bike and update COPRI lock state. </summary>
public async Task < IRequestHandler > OpenLock ( )
2021-05-13 20:03:07 +02:00
{
// Unlock bike.
Log . ForContext < BookedUnknown > ( ) . Information ( "User request to unlock bike {bike}." , SelectedBike ) ;
// Stop polling before returning bike.
BikesViewModel . IsIdle = false ;
BikesViewModel . ActionText = AppResources . ActivityTextOneMomentPlease ;
await ViewUpdateManager ( ) . StopUpdatePeridically ( ) ;
BikesViewModel . ActionText = AppResources . ActivityTextOpeningLock ;
try
{
SelectedBike . LockInfo . State = ( await LockService [ SelectedBike . LockInfo . Id ] . OpenAsync ( ) ) ? . GetLockingState ( ) ? ? LockingState . Disconnected ;
}
catch ( Exception exception )
{
BikesViewModel . ActionText = string . Empty ;
if ( exception is OutOfReachException )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockOutOfReadMessage ,
"OK" ) ;
}
2021-06-26 20:57:55 +02:00
else if ( exception is CouldntOpenBoldIsBlockedException )
2021-05-13 20:03:07 +02:00
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be opened. Bold is blocked. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
2021-06-26 20:57:55 +02:00
AppResources . ErrorOpenLockBoldBlockedMessage ,
"OK" ) ;
}
else if ( exception is CouldntOpenBoldWasBlockedException )
{
2021-08-28 10:04:10 +02:00
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be opened. Bold was or is blocked. {Exception}" , exception ) ;
2021-06-26 20:57:55 +02:00
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockStillOpenTitle ,
AppResources . ErrorOpenLockBoldWasBlockedMessage ,
2021-05-13 20:03:07 +02:00
"OK" ) ;
}
else if ( exception is CouldntOpenInconsistentStateExecption inconsistentState
& & inconsistentState . State = = LockingState . Closed )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be opened. lock reports state closed. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
AppResources . ErrorOpenLockStillClosedMessage ,
"OK" ) ;
}
else
{
Log . ForContext < BookedUnknown > ( ) . Error ( "Lock can not be opened. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorOpenLockTitle ,
exception . Message ,
"OK" ) ;
}
// When bold is blocked lock is still closed even if exception occurres.
// In all other cases state is supposed to be unknown. Example: Lock is out of reach and no more bluetooth connected.
SelectedBike . LockInfo . State = exception is StateAwareException stateAwareException
? stateAwareException . State
: LockingState . Disconnected ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
BikesViewModel . ActionText = AppResources . ActivityTextReadingChargingLevel ;
try
{
2021-06-26 20:57:55 +02:00
SelectedBike . LockInfo . BatteryPercentage = await LockService [ SelectedBike . LockInfo . Id ] . GetBatteryPercentageAsync ( ) ;
2021-05-13 20:03:07 +02:00
}
catch ( Exception exception )
{
if ( exception is OutOfReachException )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Akkustate can not be read, bike out of range. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelOutOfReach ;
}
else
{
Log . ForContext < BookedUnknown > ( ) . Error ( "Akkustate can not be read. {Exception}" , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorReadingChargingLevelGeneral ;
}
}
// Lock list to avoid multiple taps while copri action is pending.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdatingLockingState ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . UpdateLockingStateAsync ( SelectedBike ) ;
}
catch ( Exception exception )
{
if ( exception is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < BookedUnknown > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed (Copri server not reachable)." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorNoWebUpdateingLockstate ;
}
else if ( exception is ResponseException copriException )
{
// Copri server is not reachable.
Log . ForContext < BookedUnknown > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed. {response}." , SelectedBike , copriException . Response ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorStatusUpdateingLockstate ;
}
else
{
Log . ForContext < BookedUnknown > ( ) . Error ( "User locked bike {bike} in order to pause ride but updating failed . {@l_oException}" , SelectedBike . Id , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorConnectionUpdateingLockstate ;
}
}
Log . ForContext < BookedUnknown > ( ) . Information ( "User paused ride using {bike} successfully." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
/// <summary> Close lock in order to pause ride and update COPRI lock state.</summary>
2021-06-26 20:57:55 +02:00
public async Task < IRequestHandler > CloseLock ( )
2021-05-13 20:03:07 +02:00
{
// Unlock bike.
BikesViewModel . IsIdle = false ;
2021-08-28 10:04:10 +02:00
2021-05-13 20:03:07 +02:00
Log . ForContext < BookedUnknown > ( ) . Information ( "User request to lock bike {bike} in order to pause ride." , SelectedBike ) ;
2021-08-28 10:04:10 +02:00
// Start getting geolocation.
BikesViewModel . ActionText = AppResources . ActivityTextQueryLocationStart ;
var ctsLocation = new CancellationTokenSource ( ) ;
Task < Location > currentLocationTask = null ;
var timeStamp = DateTime . Now ;
try
{
currentLocationTask = Geolocation . GetAsync ( ctsLocation . Token , timeStamp ) ;
}
catch ( Exception ex )
{
// No location information available.
Log . ForContext < BookedUnknown > ( ) . Information ( "Returning bike {Bike} is not possible. Start query location failed. {Exception}" , SelectedBike , ex ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorQueryLocationQuery ;
}
2021-05-13 20:03:07 +02:00
// Stop polling before returning bike.
BikesViewModel . ActionText = AppResources . ActivityTextOneMomentPlease ;
await ViewUpdateManager ( ) . StopUpdatePeridically ( ) ;
2021-08-28 10:04:10 +02:00
// Close lock
2021-05-13 20:03:07 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextClosingLock ;
try
{
SelectedBike . LockInfo . State = ( await L ockService [ SelectedBike . LockInfo . Id ] . CloseAsync ( ) ) ? . GetLockingState ( ) ? ? LockingState . Disconnected ;
}
catch ( Exception exception )
{
BikesViewModel . ActionText = string . Empty ;
2021-08-28 10:04:10 +02:00
// Signal cts to cancel getting geolocation.
ctsLocation . Cancel ( ) ;
2021-05-13 20:03:07 +02:00
if ( exception is OutOfReachException )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be closed. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorCloseLockTitle ,
AppResources . ErrorCloseLockOutOfReachMessage ,
"OK" ) ;
}
else if ( exception is CounldntCloseMovingException )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be closed. Lock is out of reach. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorCloseLockTitle ,
AppResources . ErrorCloseLockMovingMessage ,
"OK" ) ;
}
else if ( exception is CouldntCloseBoldBlockedException )
{
Log . ForContext < BookedUnknown > ( ) . Debug ( "Lock can not be closed. Lock is out of reach. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorCloseLockTitle ,
AppResources . ErrorCloseLockBoldBlockedMessage ,
"OK" ) ;
}
else
{
Log . ForContext < BookedUnknown > ( ) . Error ( "Lock can not be closed. {Exception}" , exception ) ;
await ViewService . DisplayAlert (
AppResources . ErrorCloseLockTitle ,
exception . Message ,
"OK" ) ;
}
SelectedBike . LockInfo . State = exception is StateAwareException stateAwareException
? stateAwareException . State
: LockingState . Disconnected ;
2021-08-28 10:04:10 +02:00
// Wait until cancel getting geolocation has completed.
BikesViewModel . ActionText = AppResources . ActivityTextQueryLocationCancelWait ;
try
{
await Task . WhenAny ( new List < Task > { currentLocationTask ? ? Task . CompletedTask } ) ;
}
catch ( Exception ex )
{
// No location information available.
Log . ForContext < BookedUnknown > ( ) . Information ( "Canceling query location failed on unexpected lock state failed. {Exception}" , SelectedBike , ex ) ;
}
2021-05-13 20:03:07 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
2021-08-28 10:04:10 +02:00
2021-05-13 20:03:07 +02:00
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
// Get geoposition.
2021-08-28 10:04:10 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextQueryLocation ;
2021-05-13 20:03:07 +02:00
Location currentLocation = null ;
try
{
2021-08-28 10:04:10 +02:00
await Task . WhenAny ( new List < Task > { currentLocationTask ? ? Task . CompletedTask } ) ;
currentLocation = currentLocationTask ? . Result ? ? null ;
2021-05-13 20:03:07 +02:00
}
catch ( Exception ex )
{
// No location information available.
2021-08-28 10:04:10 +02:00
Log . ForContext < BookedUnknown > ( ) . Information ( "Get geolocation failed when closing lock of bike {Bike} with unknown state. {Exception}" , SelectedBike , ex ) ;
2021-05-13 20:03:07 +02:00
2021-08-28 10:04:10 +02:00
BikesViewModel . ActionText = AppResources . ActivityTextErrorQueryLocationWhenAny ;
2021-05-13 20:03:07 +02:00
}
// Lock list to avoid multiple taps while copri action is pending.
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdatingLockingState ;
IsConnected = IsConnectedDelegate ( ) ;
try
{
await ConnectorFactory ( IsConnected ) . Command . UpdateLockingStateAsync (
SelectedBike ,
currentLocation ! = null
? new LocationDto . Builder
{
Latitude = currentLocation . Latitude ,
Longitude = currentLocation . Longitude ,
Accuracy = currentLocation . Accuracy ? ? double . NaN ,
Age = timeStamp . Subtract ( currentLocation . Timestamp . DateTime ) ,
} . Build ( )
: null ) ;
}
catch ( Exception exception )
{
if ( exception is WebConnectFailureException )
{
// Copri server is not reachable.
Log . ForContext < BookedUnknown > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed (Copri server not reachable)." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorNoWebUpdateingLockstate ;
}
else if ( exception is ResponseException copriException )
{
// Copri server is not reachable.
Log . ForContext < BookedUnknown > ( ) . Information ( "User locked bike {bike} in order to pause ride but updating failed. Message: {Message} Details: {Details}" , SelectedBike , copriException . Message , copriException . Response ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorStatusUpdateingLockstate ;
}
else
{
Log . ForContext < BookedUnknown > ( ) . Error ( "User locked bike {bike} in order to pause ride but updating failed. {@l_oException}" , SelectedBike . Id , exception ) ;
BikesViewModel . ActionText = AppResources . ActivityTextErrorConnectionUpdateingLockstate ;
}
}
Log . ForContext < BookedUnknown > ( ) . Information ( "User paused ride using {bike} successfully." , SelectedBike ) ;
BikesViewModel . ActionText = AppResources . ActivityTextStartingUpdater ;
await ViewUpdateManager ( ) . StartUpdateAyncPeridically ( ) ;
BikesViewModel . ActionText = string . Empty ;
BikesViewModel . IsIdle = true ;
2021-06-26 20:57:55 +02:00
return RequestHandlerFactory . Create ( SelectedBike , IsConnectedDelegate , ConnectorFactory , Geolocation , LockService , ViewUpdateManager , SmartDevice , ViewService , BikesViewModel , ActiveUser ) ;
2021-05-13 20:03:07 +02:00
}
}
}