diff --git a/lib/domain/connections_service.dart b/lib/domain/connections_service.dart index b3b31239..d1f50712 100644 --- a/lib/domain/connections_service.dart +++ b/lib/domain/connections_service.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:collection'; +import 'dart:convert'; import 'dart:io'; import 'package:cbj_integrations_controller/integrations_controller.dart'; @@ -70,13 +71,13 @@ abstract interface class ConnectionsService { Future searchDevices(); - void setEntityState(ActionObject action); + void setEntityState(RequestActionObject action); Future setEtitiesToArea(String areaId, HashSet entities); - Future> get getAllEntities; + Future> get getEntities; - Future> get getAllAreas; + Future> get getAreas; Stream> watchEntities(); @@ -86,13 +87,13 @@ abstract interface class ConnectionsService { Future setNewArea(AreaEntity area); - Future> getScenes(); + Future> get getScenes; Future activateScene(String id); Future addScene(SceneCbjEntity scene); - Future loginVendor(VendorLoginEntity value); + Future loginVendor(VendorLoginEntity value); Future> getVendors(); } diff --git a/lib/domain/device/devices_errors.dart b/lib/domain/device/devices_errors.dart deleted file mode 100644 index 8a3a820d..00000000 --- a/lib/domain/device/devices_errors.dart +++ /dev/null @@ -1,14 +0,0 @@ -import 'package:cybearjinni/domain/device/devices_failures.dart'; - -class DevicesUnexpectedValueError extends Error { - DevicesUnexpectedValueError(this.deviceValueFailure); - - final DevicesFailure deviceValueFailure; - - @override - String toString() { - const explanation = - 'Encountered a ValueFailure at an unrecoverable point. Terminating.'; - return Error.safeToString('$explanation Failure was: $deviceValueFailure'); - } -} diff --git a/lib/domain/device/devices_failures.dart b/lib/domain/device/devices_failures.dart deleted file mode 100644 index 08bf7b7e..00000000 --- a/lib/domain/device/devices_failures.dart +++ /dev/null @@ -1,35 +0,0 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'devices_failures.freezed.dart'; - -@freezed -class DevicesFailure { - const factory DevicesFailure.empty({ - required T failedValue, - }) = _Empty; - - const factory DevicesFailure.actionExcecuter({ - required T failedValue, - }) = _ActionExcecuter; - - const factory DevicesFailure.exceedingLength({ - required T failedValue, - required int max, - }) = _ExceedingLength; - - const factory DevicesFailure.unexpected() = _Unexpected; - - const factory DevicesFailure.insufficientPermission() = - _InsufficientPermission; - - const factory DevicesFailure.unableToUpdate() = _UnableToUpdate; - - const factory DevicesFailure.powerConsumptionIsNotNumber() = - _PowerConsumptionIsNotNumber; - - const factory DevicesFailure.deviceActionDoesNotExist() = - _DeviceActionDoesNotExist; - - const factory DevicesFailure.deviceTypeDoesNotExist() = - _DeviceTypeDoesNotExist; -} diff --git a/lib/domain/device/devices_validators.dart b/lib/domain/device/devices_validators.dart deleted file mode 100644 index 07018491..00000000 --- a/lib/domain/device/devices_validators.dart +++ /dev/null @@ -1,88 +0,0 @@ -import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:cybearjinni/domain/device/devices_failures.dart'; -import 'package:dartz/dartz.dart'; - -Either, String> validateDeviceNotEmpty(String input) { - if (input.isNotEmpty) { - return right(input); - } else { - return left( - DevicesFailure.empty( - failedValue: input, - ), - ); - } -} - -Either, String> validateLastKnownIpNotEmpty( - String input, -) { - if (input.isNotEmpty) { - return right(input); - } else { - return left( - DevicesFailure.empty( - failedValue: input, - ), - ); - } -} - -Either, String> validatePowerConsumptionNotEmpty( - String input, -) { - if (double.tryParse(input) != null) { - return right(input); - } else { - return left(const DevicesFailure.powerConsumptionIsNotNumber()); - } -} - -Either, String> validateAreaNameNotEmpty(String input) { - return right(input); -} - -Either, String> validateMdnsNameNotEmpty(String input) { - return right(input); -} - -Either, String> validateWiFiNameNotEmpty(String input) { - return right(input); -} - -Either, String> validateDeviceMaxNameLength( - String input, - int maxLength, -) { - if (input.length <= maxLength) { - return right(input); - } else { - return left( - DevicesFailure.exceedingLength( - failedValue: input, - max: maxLength, - ), - ); - } -} - -Either, String> validateDeviceStateExist(String input) { - if (EntityUtils.stringToDeviceState(input) != null) { - return right(input); - } - return left(const DevicesFailure.deviceActionDoesNotExist()); -} - -Either, String> validateDeviceActionExist(String input) { - if (EntityUtils.stringToDeviceAction(input) != null) { - return right(input); - } - return left(const DevicesFailure.deviceActionDoesNotExist()); -} - -Either, String> validateDeviceTypeExist(String input) { - if (EntityUtils.stringToDt(input) != null) { - return right(input); - } - return left(const DevicesFailure.deviceTypeDoesNotExist()); -} diff --git a/lib/domain/device/i_device_repository.dart b/lib/domain/device/i_device_repository.dart deleted file mode 100644 index 537a9357..00000000 --- a/lib/domain/device/i_device_repository.dart +++ /dev/null @@ -1,145 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'dart:io'; - -import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:cybearjinni/domain/device/devices_failures.dart'; -import 'package:cybearjinni/infrastructure/core/logger.dart'; -import 'package:cybearjinni/infrastructure/hub_client/hub_requests_routing.dart'; -import 'package:dartz/dartz.dart'; -import 'package:device_info_plus/device_info_plus.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; -import 'package:kt_dart/kt.dart'; -import 'package:multicast_dns/multicast_dns.dart'; -import 'package:network_info_plus/network_info_plus.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:rxdart/rxdart.dart'; - -part 'package:cybearjinni/infrastructure/device_repository.dart'; - -@Deprecated('Old architecture. Replaced by EntitiesService') -abstract interface class IDeviceRepository { - static IDeviceRepository? _instance; - - static IDeviceRepository get instance { - return _instance ??= _DeviceRepository(); - } - - void addOrUpdateDevice(DeviceEntityBase deviceEntity); - - void addOrUpdateDeviceAndStateToWaiting(DeviceEntityBase deviceEntity); - - Future initiateHubConnection(); - - Future>> getAllEntites(); - - Stream>> watchAll(); - - Stream>> watchAllDevices(); - - Stream>> watchLights(); - - Stream>> watchBlinds(); - - Stream>> watchBoilers(); - - Stream>> watchSmartTv(); - - Stream>> watchSwitches(); - - Stream>> watchSmartPlugs(); - - Stream>> - watchSmartComputers(); - - Stream>> watchPrinters(); - - Stream>> watchUncompleted(); - - Future> create( - DeviceEntityBase deviceEntity, - ); - - Future> updateWithDeviceEntity({ - required DeviceEntityBase deviceEntity, - }); - - Future> turnOnDevices({ - required List? devicesId, - }); - - Future> turnOffDevices({ - required List? devicesId, - }); - - Future> changeColorTemperatureDevices({ - required List? devicesId, - required int colorTemperatureToChange, - }); - - Future> changeHsvColorDevices({ - required List? devicesId, - required HSVColor hsvColorToChange, - }); - - Future> changeBrightnessDevices({ - required List? devicesId, - required int brightnessToChange, - }); - - Future> moveUpStateDevices({ - required List? devicesId, - }); - - Future> stopStateDevices({ - required List? devicesId, - }); - - Future> moveDownStateDevices({ - required List? devicesId, - }); - - Future> suspendDevices({ - required List? devicesId, - }); - - Future> shutdownDevices({ - required List? devicesId, - }); - - Future> closeStateDevices({ - required List? devicesId, - }); - - Future> pauseStateDevices({ - required List? devicesId, - }); - - Future> playStateDevices({ - required List? devicesId, - }); - - Future> changeVolumeDevices({ - required List? devicesId, - }); - - Future> queuePrevStateDevices({ - required List? devicesId, - }); - - Future> queueNextStateDevices({ - required List? devicesId, - }); - - BehaviorSubject> allResponseFromTheHubStreamController = - BehaviorSubject>(); - - BehaviorSubject> areasResponseFromTheHubStreamController = - BehaviorSubject>(); - - BehaviorSubject> - devicesResponseFromTheHubStreamController = - BehaviorSubject>(); -} diff --git a/lib/domain/i_hub_connection_repository.dart b/lib/domain/i_hub_connection_repository.dart deleted file mode 100644 index a61938f9..00000000 --- a/lib/domain/i_hub_connection_repository.dart +++ /dev/null @@ -1,46 +0,0 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:cybearjinni/domain/i_local_db_repository.dart'; -import 'package:cybearjinni/infrastructure/core/injection.dart'; -import 'package:cybearjinni/infrastructure/core/logger.dart'; -import 'package:dartz/dartz.dart'; -import 'package:flutter/foundation.dart' show kIsWeb; -import 'package:location/location.dart'; -import 'package:multicast_dns/multicast_dns.dart'; -import 'package:network_info_plus/network_info_plus.dart'; -import 'package:permission_handler/permission_handler.dart' - as permission_handler; -import 'package:wifi_iot/wifi_iot.dart'; - -part 'package:cybearjinni/infrastructure/hub_client/hub_connection_repository.dart'; - -@Deprecated( - 'Old architecture. Replaced with ConnectionsService. Delete after Re adding Hub comunication', -) -abstract class IHubConnectionRepository { - static IHubConnectionRepository? _instance; - - static IHubConnectionRepository get instance { - return _instance ??= _HubConnectionRepository(); - } - - static HubEntity? hubEntity; - - Future connectWithHub({bool demoMod = false}); - - Future> getHubCompInfo( - CompHubInfo appInfoForHub, - ); - - Future closeConnection(); - - Future> searchForHub({ - String? deviceIpOnTheNetwork, - bool? isThatTheIpOfTheHub, - }); - - Future saveHubIP(String hubIP); -} diff --git a/lib/domain/i_local_db_repository.dart b/lib/domain/i_local_db_repository.dart index 92e4c29d..af328350 100644 --- a/lib/domain/i_local_db_repository.dart +++ b/lib/domain/i_local_db_repository.dart @@ -16,7 +16,7 @@ abstract interface class ILocalDbRepository { return _instance ??= _IsarRepository(); } - Future asyncConstructor(); + Future asyncConstructor(); Future> saveHubEntity({ required String hubNetworkBssid, diff --git a/lib/domain/software_info/i_software_info_repository.dart b/lib/domain/software_info/i_software_info_repository.dart index 75792e1a..bbe487ad 100644 --- a/lib/domain/software_info/i_software_info_repository.dart +++ b/lib/domain/software_info/i_software_info_repository.dart @@ -1,7 +1,6 @@ import 'dart:io'; import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:cybearjinni/domain/i_hub_connection_repository.dart'; import 'package:cybearjinni/domain/security_bear/i_security_bear_connection_repository.dart'; import 'package:cybearjinni/domain/security_bear/security_bear_failures.dart'; import 'package:cybearjinni/domain/software_info/software_info_entity.dart'; diff --git a/lib/infrastructure/cbj_app_server_d.dart b/lib/infrastructure/cbj_app_server_d.dart index 32c440b1..4ff328c9 100644 --- a/lib/infrastructure/cbj_app_server_d.dart +++ b/lib/infrastructure/cbj_app_server_d.dart @@ -25,7 +25,7 @@ class _CBJAppServerD extends CyBearJinniAppServiceBase { return Future.value(CompAppInfo()); } -// Future cBJAppGetSmartDeviceInformationAsync( +// Future cBJAppGetSmartDeviceInformationAsync( // SmartDeviceInfo smartDevice) async { // final String smartDeviceIp = smartDevice.smartDeviceIP; // @@ -54,14 +54,14 @@ class CreateTheCBJAppServer { Server? server; /// This function will create the server - Future createServer(StreamController compInfoStream) async { + Future createServer(StreamController compInfoStream) async { await server?.shutdown(); server = Server.create(services: [_CBJAppServerD(compInfoStream)]); await server!.serve(port: 30055); logger.i('App server listening on port ${server!.port}...'); } - Future shutdownServer() async { + Future shutdownServer() async { await server?.shutdown(); return; } diff --git a/lib/infrastructure/connection_service/app_connection_service.dart b/lib/infrastructure/connection_service/app_connection_service.dart index 67e6f712..af0dca37 100644 --- a/lib/infrastructure/connection_service/app_connection_service.dart +++ b/lib/infrastructure/connection_service/app_connection_service.dart @@ -9,11 +9,11 @@ class _AppConnectionService implements ConnectionsService { late SearchDevices searchDevicesInstance; @override - Future> get getAllEntities async => + Future> get getEntities async => IcSynchronizer().getEntities(); @override - Future> get getAllAreas async => + Future> get getAreas async => IcSynchronizer().getAreas(); @override @@ -29,7 +29,7 @@ class _AppConnectionService implements ConnectionsService { IcSynchronizer().areasChangesStream.stream; @override - void setEntityState(ActionObject action) => + void setEntityState(RequestActionObject action) => IcSynchronizer().setEntitiesState(action); @override @@ -45,7 +45,7 @@ class _AppConnectionService implements ConnectionsService { IcSynchronizer().setEtitiesToArea(areaId, entities); @override - Future> getScenes() async => + Future> get getScenes async => IcSynchronizer().getScenes(); @override diff --git a/lib/infrastructure/connection_service/demo_connection_service.dart b/lib/infrastructure/connection_service/demo_connection_service.dart index 72c6522c..1dd06616 100644 --- a/lib/infrastructure/connection_service/demo_connection_service.dart +++ b/lib/infrastructure/connection_service/demo_connection_service.dart @@ -10,17 +10,17 @@ class _DemoConnectionService implements ConnectionsService { } @override - Future> get getAllEntities async => + Future> get getEntities async => DemoConnectionController.getAllEntities(); @override - Future> get getAllAreas async => HashMap(); + Future> get getAreas async => HashMap(); @override Future searchDevices() async {} @override - void setEntityState(ActionObject action) {} + void setEntityState(RequestActionObject action) {} @override Stream> watchEntities() { @@ -48,13 +48,13 @@ class _DemoConnectionService implements ConnectionsService { Future addScene(SceneCbjEntity scene) async {} @override - Future> getScenes() async => HashMap(); + Future> get getScenes async => HashMap(); @override Future activateScene(String id) async {} @override - Future loginVendor(VendorLoginEntity value) async {} + Future loginVendor(VendorLoginEntity value) async {} @override Future> getVendors() async => diff --git a/lib/infrastructure/connection_service/hub_connection_service.dart b/lib/infrastructure/connection_service/hub_connection_service.dart index 78a6d603..6fde9032 100644 --- a/lib/infrastructure/connection_service/hub_connection_service.dart +++ b/lib/infrastructure/connection_service/hub_connection_service.dart @@ -37,18 +37,117 @@ class _HubConnectionService implements ConnectionsService { } @override - Future> get getAllEntities async { - appMessagesToHub.sink - .add(ClientStatusRequests(sendingType: SendingType.firstConnection)); + Future> get getEntities async { + appMessagesToHub.sink.add( + ClientStatusRequests(sendingType: SendingType.allEntities.name), + ); + final HashMap entities = HashMap(); + await for (final RequestsAndStatusFromHub message in hubMessagesToApp.stream) { - logger.i('message from hub is $message'); + final SendingType sendingType = + SendingTypeExtension.fromString(message.sendingType); + if (sendingType != SendingType.allEntities) { + continue; + } + + try { + final Map entitiesMap = Map.from( + jsonDecode(message.allRemoteCommands) as Map, + ); + entities.addEntries( + entitiesMap.entries.map( + (e) => MapEntry( + e.key, + DeviceHelper.convertJsonStringToDomain(e.value), + ), + ), + ); + } catch (e) { + logger.e('Error converting entities\n$e'); + } + break; } - return HashMap(); + + return entities; } @override - Future> get getAllAreas async => HashMap(); + Future> get getAreas async { + appMessagesToHub.sink.add( + ClientStatusRequests(sendingType: SendingType.allAreas.name), + ); + + final HashMap areas = HashMap(); + + await for (final RequestsAndStatusFromHub message + in hubMessagesToApp.stream) { + final SendingType sendingType = + SendingTypeExtension.fromString(message.sendingType); + if (sendingType != SendingType.allAreas) { + continue; + } + + try { + final Map entitiesMap = Map.from( + jsonDecode(message.allRemoteCommands) as Map, + ); + areas.addEntries( + entitiesMap.entries.map( + (e) => MapEntry( + e.key, + AreaEntityDtos.fromJson( + jsonDecode(e.value) as Map, + ).toDomain(), + ), + ), + ); + } catch (e) { + logger.e('Error converting areas\n$e'); + } + break; + } + + return areas; + } + + @override + Future> get getScenes async { + appMessagesToHub.sink.add( + ClientStatusRequests(sendingType: SendingType.allScenes.name), + ); + + final HashMap scenesMap = HashMap(); + + await for (final RequestsAndStatusFromHub message + in hubMessagesToApp.stream) { + final SendingType sendingType = + SendingTypeExtension.fromString(message.sendingType); + if (sendingType != SendingType.allScenes) { + continue; + } + + try { + final Map entities = Map.from( + jsonDecode(message.allRemoteCommands) as Map, + ); + scenesMap.addEntries( + entities.entries.map( + (e) => MapEntry( + e.key, + SceneCbjDtos.fromJson(jsonDecode(e.value) as Map) + .toDomain(), + ), + ), + ); + } catch (e) { + logger.e('Error converting scenes\n$e'); + } + break; + } + + return scenesMap; + } @override Future searchDevices() async { @@ -126,7 +225,14 @@ class _HubConnectionService implements ConnectionsService { } @override - void setEntityState(ActionObject action) {} + void setEntityState(RequestActionObject action) { + appMessagesToHub.sink.add( + ClientStatusRequests( + sendingType: SendingType.setEntitiesAction.name, + allRemoteCommands: action.toInfrastructure().toJsonString(), + ), + ); + } @override Stream> watchEntities() { @@ -153,14 +259,11 @@ class _HubConnectionService implements ConnectionsService { @override Future addScene(SceneCbjEntity scene) async {} - @override - Future> getScenes() async => HashMap(); - @override Future activateScene(String id) async {} @override - Future loginVendor(VendorLoginEntity value) async {} + Future loginVendor(VendorLoginEntity value) async {} @override Future> getVendors() async => @@ -229,7 +332,7 @@ class _HubConnectionService implements ConnectionsService { } /// Connect directly to the Hub if possible - Future connectDirectlyToHub() async { + Future connectDirectlyToHub() async { if (hubIp == null) { return; } diff --git a/lib/infrastructure/connection_service/none_connection_service.dart b/lib/infrastructure/connection_service/none_connection_service.dart index 8e8555db..fb1049d2 100644 --- a/lib/infrastructure/connection_service/none_connection_service.dart +++ b/lib/infrastructure/connection_service/none_connection_service.dart @@ -10,17 +10,16 @@ class _NoneConnectionService implements ConnectionsService { } @override - Future> get getAllEntities async => - HashMap(); + Future> get getEntities async => HashMap(); @override - Future> get getAllAreas async => HashMap(); + Future> get getAreas async => HashMap(); @override Future searchDevices() async {} @override - void setEntityState(ActionObject action) {} + void setEntityState(RequestActionObject action) {} @override Stream> watchEntities() { @@ -45,7 +44,7 @@ class _NoneConnectionService implements ConnectionsService { Future setEtitiesToArea(String areaId, HashSet entities) async {} @override - Future> getScenes() async => HashMap(); + Future> get getScenes async => HashMap(); @override Future addScene(SceneCbjEntity scene) async {} @@ -54,7 +53,7 @@ class _NoneConnectionService implements ConnectionsService { Future activateScene(String id) async {} @override - Future loginVendor(VendorLoginEntity value) async {} + Future loginVendor(VendorLoginEntity value) async {} @override Future> getVendors() async => []; diff --git a/lib/infrastructure/device_repository.dart b/lib/infrastructure/device_repository.dart deleted file mode 100644 index f2da2154..00000000 --- a/lib/infrastructure/device_repository.dart +++ /dev/null @@ -1,1160 +0,0 @@ -part of 'package:cybearjinni/domain/device/i_device_repository.dart'; - -class _DeviceRepository implements IDeviceRepository { - // final DeviceRemoteService _deviceRemoteService; - // final DeviceLocalService _deviceLocalService; - HashMap allDevices = - HashMap(); - - // @override - // void addOrUpdateFromApp(dynamic entity) { - // if (entity is AreaEntity) { - // _addOrUpdateArea(entity); - // } else if (entity is DeviceEntityBase) { - // _addOrUpdateDevice(entity); - // } else { - // logger.w('Entity type to update ${entity.runtimeType} is not supported'); - // } - // allResponseFromTheHubStreamController.sink - // .add(entity); - // } - - @override - void addOrUpdateDevice(DeviceEntityBase deviceEntity) { - allDevices[deviceEntity.cbjDeviceVendor.getOrCrash()] = deviceEntity; - devicesResponseFromTheHubStreamController.sink - .add(allDevices.values.toImmutableList()); - } - - @override - void addOrUpdateDeviceAndStateToWaiting(DeviceEntityBase deviceEntity) { - addOrUpdateDevice( - deviceEntity.copyWithDeviceState( - EntityStateGRPC.waitingInComp, - ), - ); - } - - @override - Future initiateHubConnection() async { - AppRequestsToHub.listenToApp(); - - HubRequestRouting.navigateRequest(); - } - - @override - Future>> - getAllEntites() async { - try { - return right(allDevices.values.toImmutableList()); - } catch (e) { - if (e is PlatformException && e.message!.contains('PERMISSION_DENIED')) { - logger.w('Insufficient permission while getting all devices'); - return left(const DevicesFailure.insufficientPermission()); - } else { - logger.e('Unexpected error while getting all devices'); - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - } - - @override - Stream> watchAll() async* { - yield* allResponseFromTheHubStreamController.map((event) => right(event)); - } - - @override - Stream>> - watchAllDevices() async* { - yield* devicesResponseFromTheHubStreamController.stream - .map((event) => right(event)); - } - - @override - Stream>> - watchLights() async* { - // Using watchAll devices from server function and filtering out only the - // Light device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.light.toString() || - element.entityTypes.getOrCrash() == - EntityTypes.dimmableLight.toString() || - element.entityTypes.getOrCrash() == - EntityTypes.rgbwLights.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchSwitches() async* { - // Using watchAll devices from server function and filtering out only the - // Switches device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.switch_.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchSmartPlugs() async* { - // Using watchAll devices from server function and filtering out only the - // Smart Plugs device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.smartPlug.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchSmartComputers() async* { - // Using watchAll devices from server function and filtering out only the - // Smart Computers device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.smartComputer.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchBlinds() async* { - // Using watchAll devices from server function and filtering out only the - // Blinds device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.blinds.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchBoilers() async* { - // Using watchAll devices from server function and filtering out only the - // Boilers device type - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.boiler.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchSmartTv() async* { - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.smartTV.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> - watchPrinters() async* { - yield* watchAllDevices().map( - (event) => event.fold((l) => left(l), (r) { - return right( - r.toList().asList().where((element) { - return element!.entityTypes.getOrCrash() == - EntityTypes.printer.toString(); - }).toImmutableList(), - ); - }), - ); - } - - @override - Stream>> watchUncompleted() { - // TODO: implement watchUncompleted - throw UnimplementedError(); - } - - @override - Future> create( - DeviceEntityBase deviceEntity, - ) async { - try { - String deviceModelString = 'No Model found'; - final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); - if (Platform.isAndroid) { - final AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; - logger.i(androidInfo.model); - deviceModelString = androidInfo.model; - } else if (Platform.isIOS) { - final IosDeviceInfo iosInfo = await deviceInfo.iosInfo; - logger.i(iosInfo.utsname.machine); - deviceModelString = iosInfo.model; - } - - const String currentUserId = 'user id'; - - deviceEntity - .copyWithStateMassage('Setting up device') - .copyWithSenderDeviceOs(Platform.operatingSystem) - .copyWithDeviceSenderDeviceModel(deviceModelString) - .copyWithSenderId(currentUserId); - - DeviceEntityDtoBase.fromDomain(); - - return right(unit); - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - } - - @override - Future> updateWithDeviceEntity({ - required DeviceEntityBase deviceEntity, - }) async { - return left(const DevicesFailure.unexpected()); - } - - @override - Future> turnOnDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericLightDE) { - deviceEntity.lightSwitchState = - GenericLightSwitchState(EntityActions.on.toString()); - } else if (deviceEntity is GenericDimmableLightDE) { - deviceEntity.lightSwitchState = - GenericDimmableLightSwitchState(EntityActions.on.toString()); - } else if (deviceEntity is GenericRgbwLightDE) { - deviceEntity.lightSwitchState = - GenericRgbwLightSwitchState(EntityActions.on.toString()); - } else if (deviceEntity is GenericSwitchDE) { - deviceEntity.switchState = - GenericSwitchSwitchState(EntityActions.on.toString()); - } else if (deviceEntity is GenericBoilerDE) { - deviceEntity.boilerSwitchState = - GenericBoilerSwitchState(EntityActions.on.toString()); - } else if (deviceEntity is GenericSmartPlugDE) { - deviceEntity.smartPlugState = - GenericSmartPlugState(EntityActions.on.toString()); - } else { - logger.w( - 'On action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> turnOffDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericLightDE) { - deviceEntity.lightSwitchState = - GenericLightSwitchState(EntityActions.off.toString()); - } else if (deviceEntity is GenericDimmableLightDE) { - deviceEntity.lightSwitchState = - GenericDimmableLightSwitchState(EntityActions.off.toString()); - } else if (deviceEntity is GenericRgbwLightDE) { - deviceEntity.lightSwitchState = - GenericRgbwLightSwitchState(EntityActions.off.toString()); - } else if (deviceEntity is GenericSwitchDE) { - deviceEntity.switchState = - GenericSwitchSwitchState(EntityActions.off.toString()); - } else if (deviceEntity is GenericBoilerDE) { - deviceEntity.boilerSwitchState = - GenericBoilerSwitchState(EntityActions.off.toString()); - } else if (deviceEntity is GenericSmartPlugDE) { - deviceEntity.smartPlugState = - GenericSmartPlugState(EntityActions.off.toString()); - } else { - logger.w( - 'Off action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> changeColorTemperatureDevices({ - required List? devicesId, - required int colorTemperatureToChange, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericRgbwLightDE) { - deviceEntity.lightColorTemperature = GenericRgbwLightColorTemperature( - colorTemperatureToChange.toString(), - ); - } else { - logger.w( - 'Off action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - try { - if (!deviceEntity.doesWaitingToSendTemperatureColorRequest) { - deviceEntity.doesWaitingToSendTemperatureColorRequest = true; - - final Future> updateEntityResponse = - updateWithDeviceEntity(deviceEntity: deviceEntity); - - await Future.delayed( - Duration( - milliseconds: - deviceEntity.sendNewTemperatureColorEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendTemperatureColorRequest = false; - - return updateEntityResponse; - } - } catch (e) { - await Future.delayed( - Duration( - milliseconds: - deviceEntity.sendNewTemperatureColorEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendTemperatureColorRequest = false; - return left(const DevicesFailure.unexpected()); - } - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> changeHsvColorDevices({ - required List? devicesId, - required HSVColor hsvColorToChange, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericRgbwLightDE) { - deviceEntity - ..lightColorAlpha = - GenericRgbwLightColorAlpha(hsvColorToChange.alpha.toString()) - ..lightColorHue = - GenericRgbwLightColorHue(hsvColorToChange.hue.toString()) - ..lightColorSaturation = GenericRgbwLightColorSaturation( - hsvColorToChange.saturation.toString(), - ) - ..lightColorValue = - GenericRgbwLightColorValue(hsvColorToChange.value.toString()); - } else { - logger.w( - 'Off action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - try { - if (!deviceEntity.doesWaitingToSendHsvColorRequest) { - deviceEntity.doesWaitingToSendHsvColorRequest = true; - - final Future> updateEntityResponse = - updateWithDeviceEntity(deviceEntity: deviceEntity); - - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewHsvColorEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendHsvColorRequest = false; - - return updateEntityResponse; - } - } catch (e) { - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewHsvColorEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendHsvColorRequest = false; - return left(const DevicesFailure.unexpected()); - } - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> changeBrightnessDevices({ - required List? devicesId, - required int brightnessToChange, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - Either totalActionResult = right(unit); - - try { - Either actionResult; - - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } else if (deviceEntity is GenericDimmableLightDE) { - deviceEntity.lightBrightness = - GenericDimmableLightBrightness(brightnessToChange.toString()); - actionResult = await dimDimmableLight(deviceEntity); - } else if (deviceEntity is GenericRgbwLightDE) { - deviceEntity.lightBrightness = - GenericRgbwLightBrightness(brightnessToChange.toString()); - actionResult = await dimRgbwLight(deviceEntity); - } else { - logger.w( - 'Brightness action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - if (actionResult.isLeft()) { - totalActionResult = actionResult; - } - } - return totalActionResult; - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - } - - Future> dimDimmableLight( - GenericDimmableLightDE deviceEntity, - ) async { - try { - if (!deviceEntity.doesWaitingToSendBrightnessRequest) { - deviceEntity.doesWaitingToSendBrightnessRequest = true; - - final Future> updateEntityResponse = - updateWithDeviceEntity(deviceEntity: deviceEntity); - - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewBrightnessEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendBrightnessRequest = false; - return updateEntityResponse; - } - } catch (e) { - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewBrightnessEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendBrightnessRequest = false; - return left(const DevicesFailure.unexpected()); - } - return right(unit); - } - - Future> dimRgbwLight( - GenericRgbwLightDE deviceEntity, - ) async { - try { - if (!deviceEntity.doesWaitingToSendBrightnessRequest) { - deviceEntity.doesWaitingToSendBrightnessRequest = true; - - final Future> updateEntityResponse = - updateWithDeviceEntity(deviceEntity: deviceEntity); - - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewBrightnessEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendBrightnessRequest = false; - return updateEntityResponse; - } - } catch (e) { - await Future.delayed( - Duration( - milliseconds: deviceEntity.sendNewBrightnessEachMilliseconds, - ), - ); - deviceEntity.doesWaitingToSendBrightnessRequest = false; - return left(const DevicesFailure.unexpected()); - } - return right(unit); - } - - @override - Future> moveUpStateDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericBlindsDE) { - deviceEntity.blindsSwitchState = - GenericBlindsSwitchState(EntityActions.moveUp.toString()); - } else { - logger.w( - 'Off action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> stopStateDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericBlindsDE) { - deviceEntity.blindsSwitchState = - GenericBlindsSwitchState(EntityActions.stop.toString()); - } else if (deviceEntity is GenericSmartTvDE) { - deviceEntity.pausePlayState = GenericSmartTvPausePlayState( - EntityActions.stop.toString(), - ); - } else { - logger.w( - 'Stop action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> moveDownStateDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericBlindsDE) { - deviceEntity.blindsSwitchState = - GenericBlindsSwitchState(EntityActions.moveDown.toString()); - } else { - logger.w( - 'Move down action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> suspendDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartComputerDE) { - deviceEntity.smartComputerSuspendState = - GenericSmartComputerSuspendState( - EntityActions.suspend.toString(), - ); - } else { - logger.w( - 'Suspend action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> shutdownDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartComputerDE) { - deviceEntity.smartComputerShutDownState = - GenericSmartComputerShutdownState( - EntityActions.shutdown.toString(), - ); - } else { - logger.w( - 'Shutdown action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> changeVolumeDevices({ - required List? devicesId, - }) async { - // TODO: implement changeVolumeDevices - throw UnimplementedError(); - } - - @override - Future> closeStateDevices({ - List? devicesId, - String? forceUpdateLocation, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericBlindsDE) { - deviceEntity.blindsSwitchState = - GenericBlindsSwitchState(EntityActions.close.toString()); - } else { - logger.w( - 'Close action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> pauseStateDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartTvDE) { - deviceEntity.pausePlayState = GenericSmartTvPausePlayState( - EntityActions.pause.toString(), - ); - } else { - logger.w( - 'Pause action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> playStateDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartTvDE) { - deviceEntity.pausePlayState = GenericSmartTvPausePlayState( - EntityActions.play.toString(), - ); - } else { - logger.w( - 'Play action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> queuePrevStateDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartTvDE) { - deviceEntity.pausePlayState = GenericSmartTvPausePlayState( - EntityActions.skipPreviousVid.toString(), - ); - } else { - logger.w( - 'Skip prev vid action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - @override - Future> queueNextStateDevices({ - required List? devicesId, - }) async { - final List deviceEntityListToUpdate = - await getDeviceEntityListFromId(devicesId!); - - try { - for (final DeviceEntityBase? deviceEntity in deviceEntityListToUpdate) { - if (deviceEntity == null) { - continue; - } - if (deviceEntity is GenericSmartTvDE) { - deviceEntity.pausePlayState = GenericSmartTvPausePlayState( - EntityActions.skipNextVid.toString(), - ); - } else { - logger.w( - 'Skip next vid action not supported for' - ' ${deviceEntity.entityTypes.getOrCrash()} type', - ); - continue; - } - - updateWithDeviceEntity(deviceEntity: deviceEntity); - } - } on PlatformException catch (e) { - if (e.message!.contains('PERMISSION_DENIED')) { - return left(const DevicesFailure.insufficientPermission()); - } else if (e.message!.contains('NOT_FOUND')) { - return left(const DevicesFailure.unableToUpdate()); - } else { - // log.error(e.toString()); - return left(const DevicesFailure.unexpected()); - } - } - return right(unit); - } - - Future> updateComputer( - DeviceEntityBase deviceEntity, - ) async { - try { - addOrUpdateDeviceAndStateToWaiting(deviceEntity); - - try { - deviceEntity.copyWithDeviceState(EntityStateGRPC.waitingInCloud); - - final String deviceDtoAsString = - DeviceHelper.convertDomainToJsonString(deviceEntity); - final ClientStatusRequests clientStatusRequests = ClientStatusRequests( - allRemoteCommands: deviceDtoAsString, - sendingType: SendingType.entityType, - ); - AppRequestsToHub.appRequestsToHubStreamController - .add(clientStatusRequests); - } catch (e) { - logger.e('This is the error\n$e'); - - // final DocumentReference homeDoc = - // await _firestore.currentHomeDocument(); - // final CollectionReference devicesCollection = - // homeDoc.devicesCollecttion; - // final DocumentReference deviceDocumentReference = - // devicesCollection.doc(deviceEntity.id!.getOrCrash()); - // updateDatabase(documentPath: deviceDocumentReference, fieldsToUpdate: { - // 'lastKnownIp': lastKnownIp, - // }); - } - - return right(unit); - } catch (e) { - logger.w('Probably ip of device was not inserted into the device object'); - return left(const DevicesFailure.unexpected()); - } - } - - Future> getDeviceEntityListFromId( - List deviceIdList, - ) async { - final List deviceEntityList = []; - - if (allDevices.isEmpty) { - return []; - } - - for (final deviceId in deviceIdList) { - final DeviceEntityBase? device = allDevices[deviceId]; - if (device == null) { - continue; - } - deviceEntityList.add(device); - } - return deviceEntityList; - } - - /// Search device IP by computer Avahi (mdns) name - Future getDeviceIpByDeviceAvahiName(String mDnsName) async { - String deviceIp = ''; - final String fullMdnsName = '$mDnsName.local'; - - final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool? reuseAddress, - bool? reusePort, - int? ttl, - }) { - return RawDatagramSocket.bind(host, port, ttl: ttl!); - }, - ); - // Start the client with default options. - - await client.start(); - await for (final IPAddressResourceRecord record - in client.lookup( - ResourceRecordQuery.addressIPv4(fullMdnsName), - )) { - deviceIp = record.address.address; - logger.t('Found address (${record.address}).'); - } - - // await for (final IPAddressResourceRecord record - // in client.lookup( - // ResourceRecordQuery.addressIPv6(fullMdnsName))) { - // logger.t('Found address (${record.address}).'); - // } - - client.stop(); - - logger.t('Done.'); - - return deviceIp; - } - - /// How to send the data, in the local network or the remote server/cloud - Future whereToUpdateDevicesData( - String? forceUpdateLocation, - String? deviceSecondWifiName, - ) async { - String updateLocation; - - try { - if (forceUpdateLocation == null) { - final status = await Permission.location.status; - if (status.isDenied) { - Permission.location.request(); - } - - final String? wifiName = await NetworkInfo().getWifiName(); - - if (deviceSecondWifiName != null && - deviceSecondWifiName.isNotEmpty && - deviceSecondWifiName == wifiName) { - updateLocation = 'L'; // L for local network - } else { - updateLocation = 'R'; // R for remote - } - } else { - updateLocation = forceUpdateLocation; - } - } catch (exception) { - updateLocation = 'L'; - } - - return updateLocation; - } - - /// Stream controller of the app request for the hub - @override - BehaviorSubject allResponseFromTheHubStreamController = - BehaviorSubject(); - - @override - BehaviorSubject> - devicesResponseFromTheHubStreamController = - BehaviorSubject>(); - - @override - BehaviorSubject> areasResponseFromTheHubStreamController = - BehaviorSubject>(); -} diff --git a/lib/infrastructure/hub_client/hub_connection_repository.dart b/lib/infrastructure/hub_client/hub_connection_repository.dart deleted file mode 100644 index 629ca963..00000000 --- a/lib/infrastructure/hub_client/hub_connection_repository.dart +++ /dev/null @@ -1,582 +0,0 @@ -part of 'package:cybearjinni/domain/i_hub_connection_repository.dart'; - -@Deprecated( - 'Old architecture. Replaced with ConnectionsService. Delete after Re adding Hub comunication', -) -class _HubConnectionRepository implements IHubConnectionRepository { - _HubConnectionRepository() { - if (currentEnvApp == EnvApp.prod) { - hubPort = 50055; - } else { - hubPort = 60055; - } - } - - /// Port to connect to the cbj hub, will change according to the current - /// running environment - late int hubPort; - - int tryAgainConnectToTheHubOnceMore = 0; - - bool cancelConnectionWithHub = false; - - bool appInDemoMod = false; - - @override - Future connectWithHub({bool demoMod = false}) async { - if (cancelConnectionWithHub && !demoMod) { - return; - } - appInDemoMod = demoMod; - - if (appInDemoMod) { - cancelConnectionWithHub = true; - return streamFromDemoMode(); - } - - /// Load network information from local db - if (IHubConnectionRepository.hubEntity == null) { - await loadNetworkInformationFromDb(); - } - - ConnectivityResult? connectivityResult; - try { - connectivityResult = await Connectivity().checkConnectivity(); - } catch (e) { - logger.w('Cant check connectivity this is probably PC, error\n$e'); - } - - // Last Number of bssid can change fix?, need to check if more numbers - // can do that - final String? savedWifiBssid = - IHubConnectionRepository.hubEntity?.hubNetworkBssid.getOrCrash(); - final String? savedWifiBssidWithoutLastNumber = - savedWifiBssid?.substring(0, savedWifiBssid.lastIndexOf(':')); - String? wifiBSSID; - String? wifiBSSIDWithoutLastNumber; - try { - wifiBSSID = await NetworkInfo().getWifiBSSID(); - wifiBSSIDWithoutLastNumber = - wifiBSSID?.substring(0, wifiBSSID.lastIndexOf(':')); - } catch (e) { - logger.w("Can't get WiFi BSSID"); - } - final Either remotePipesInformation = - await ILocalDbRepository.instance.getRemotePipesDnsName(); - - // Check if you are connected to the home local network for direct - // communication with the Hub. - // This block can be false also if user does not approve some permissions - // or #256 if the app run on the computer and connected with ethernet cable - // (not effecting connection with WiFi) - if (remotePipesInformation.isLeft() || - (connectivityResult != null && - connectivityResult == ConnectivityResult.wifi && - savedWifiBssidWithoutLastNumber != null && - wifiBSSIDWithoutLastNumber != null && - savedWifiBssidWithoutLastNumber == wifiBSSIDWithoutLastNumber) || - (connectivityResult != null && - connectivityResult == ConnectivityResult.ethernet && - savedWifiBssidWithoutLastNumber == 'no:Network:Bssid') || - (kIsWeb && savedWifiBssidWithoutLastNumber == 'no:Network:Bssid')) { - (await openAndroidWifiSettingIfPossible()).fold( - (l) { - logger - .w('No way to establish connection with the Hub, WiFi or location' - ' permission is closed for here'); - return; - }, - (r) async {}, - ); - logger.i('Connect using direct connection to Hub'); - - await connectDirectlyToHub(); - return; - } else { - await connectionUsingRemotePipes(); - } - } - - @override - Future> getHubCompInfo( - CompHubInfo appInfoForHub, - ) async { - if (IHubConnectionRepository.hubEntity == null) { - try { - String? hubNetworkBssid; - (await ILocalDbRepository.instance.getHubEntityNetworkBssid()).fold( - (l) => throw 'Error getting Hub network Bssid', - (r) => hubNetworkBssid = r, - ); - - String? hubNetworkName; - (await ILocalDbRepository.instance.getHubEntityNetworkName()).fold( - (l) => throw 'Error getting Hub network name', - (r) => hubNetworkName = r, - ); - - String? hubNetworkIp; - (await ILocalDbRepository.instance.getHubEntityLastKnownIp()).fold( - (l) => throw 'Error getting Hub network IP', - (r) => hubNetworkIp = r, - ); - IHubConnectionRepository.hubEntity = HubDtos( - hubNetworkBssid: hubNetworkBssid!, - lastKnownIp: hubNetworkIp!, - networkName: hubNetworkName!, - ).toDomain(); - } catch (e) { - logger.e('Crashed while setting Hub info from local db\n$e'); - } - } - - ConnectivityResult? connectivityResult; - try { - connectivityResult = await Connectivity().checkConnectivity(); - } catch (e) { - logger.w('Cant check connectivity this is probably PC, error\n$e'); - } - - // Last Number of bssid can change fix?, need to check if more numbers - // can do that - final String? savedWifiBssid = - IHubConnectionRepository.hubEntity?.hubNetworkBssid.getOrCrash(); - final String? savedWifiBssidWithoutLastNumber = - savedWifiBssid?.substring(0, savedWifiBssid.lastIndexOf(':')); - - final String? wifiBSSID = await NetworkInfo().getWifiBSSID(); - final String? wifiBSSIDWithoutLastNumber = - wifiBSSID?.substring(0, wifiBSSID.lastIndexOf(':')); - - // Check if you are connected to the home local network for direct - // communication with the Hub. - // This block can be false also if user does not improve some permissions - // or #256 if the app run on the computer and connected with ethernet cable - // (not effecting connection with WiFi) - if (connectivityResult != null && - connectivityResult == ConnectivityResult.wifi && - savedWifiBssidWithoutLastNumber != null && - wifiBSSIDWithoutLastNumber != null && - savedWifiBssidWithoutLastNumber == wifiBSSIDWithoutLastNumber) { - logger.i('Connect using direct connection to Hub'); - - if (IHubConnectionRepository.hubEntity?.lastKnownIp.getOrCrash() != - null) { - Socket? testHubConnection; - try { - testHubConnection = await Socket.connect( - IHubConnectionRepository.hubEntity!.lastKnownIp.getOrCrash(), - hubPort, - timeout: const Duration(milliseconds: 500), - ); - testHubConnection.destroy(); - } catch (e) { - testHubConnection?.destroy(); - - await searchForHub(); - } - } else { - await searchForHub(); - } - - try { - final CompHubInfo? compHubInfo = await HubClient.getHubCompInfo( - IHubConnectionRepository.hubEntity!.lastKnownIp.getOrCrash(), - hubPort, - appInfoForHub, - ); - - if (compHubInfo == null) { - return left(const HubFailures.unexpected()); - } - return right(compHubInfo); - } catch (e) { - logger.e('Error getting hubInfo\n$e'); - return left(const HubFailures.unexpected()); - } - - // return; - } else { - logger.i('Connect using Remote Pipes'); - return (await ILocalDbRepository.instance.getRemotePipesDnsName()).fold( - (l) { - logger.e('Cant find local Remote Pipes Dns name'); - return left(const HubFailures.unexpected()); - }, (r) async { - try { - final CompHubInfo? compHubInfo = - await HubClient.getHubCompInfo(r, 50056, appInfoForHub); - - if (compHubInfo == null) { - return left(const HubFailures.unexpected()); - } - return right(compHubInfo); - } catch (e) { - logger.e('Error getting hubInfo\n$e'); - return left(const HubFailures.unexpected()); - } - }); - // Here for easy find and local testing - // HubClient.createStreamWithHub('127.0.0.1', 50056); - } - } - - @override - Future closeConnection() async { - cancelConnectionWithHub = true; - } - - /// Search device IP by computer Avahi (mdns) name - Future getDeviceIpByDeviceAvahiName(String mDnsName) async { - String deviceIp = ''; - // final String fullMdnsName = '$mDnsName.local'; - - final MDnsClient client = MDnsClient( - rawDatagramSocketFactory: ( - dynamic host, - int port, { - bool? reuseAddress, - bool? reusePort, - int? ttl, - }) { - return RawDatagramSocket.bind(host, port, ttl: ttl!); - }, - ); - - // Start the client with default options. - await client.start(); - await for (final IPAddressResourceRecord record - in client.lookup( - ResourceRecordQuery.addressIPv4(mDnsName), - )) { - deviceIp = record.address.address; - logger.i('Found address (${record.address}).'); - } - - // await for (final IPAddressResourceRecord record - // in client.lookup( - // ResourceRecordQuery.addressIPv6(fullMdnsName))) { - // logger.t('Found address (${record.address}).'); - // } - - client.stop(); - - logger.t('Done.'); - - return deviceIp; - } - - @override - Future> searchForHub({ - String? deviceIpOnTheNetwork, - bool? isThatTheIpOfTheHub, - }) async { - try { - final Either locationRequest = - await askLocationPermissionAndLocationOn(); - - if (locationRequest.isLeft()) { - return locationRequest; - } - - logger.i('searchForHub'); - - String? currentDeviceIP; - String? networkBSSID; - String? networkName; - if (await Connectivity().checkConnectivity() == ConnectivityResult.wifi && - !kIsWeb) { - final NetworkInfo networkInfo = NetworkInfo(); - networkName = await networkInfo.getWifiName(); - currentDeviceIP = await networkInfo.getWifiIP(); - networkBSSID = await networkInfo.getWifiBSSID(); - } else { - if (deviceIpOnTheNetwork == null) { - // Issue https://github.com/CyBear-Jinni/cbj_app/issues/256 - return left( - const HubFailures - .findingHubWhenConnectedToEthernetCableIsNotSupported(), - ); - } - - currentDeviceIP = deviceIpOnTheNetwork; - networkBSSID = 'no:Network:Bssid:Found'; - networkName = 'noNetworkNameFound'; - if (isThatTheIpOfTheHub != null && isThatTheIpOfTheHub) { - return insertHubInfo( - networkIp: currentDeviceIP, - networkBSSID: networkBSSID, - networkName: networkName, - ); - } - } - - final String subnet = - currentDeviceIP!.substring(0, currentDeviceIP.lastIndexOf('.')); - - logger.i('Hub Search subnet IP $subnet'); - - // TODO: Search for hub - // final Stream devicesWithPort = - // HostScanner.scanDevicesForSinglePort( - // subnet, - // hubPort, - - // /// TODO: return this settings when can use with the await for loop - // // resultsInIpAscendingOrder: false, - // timeout: const Duration(milliseconds: 600), - // ); - - // await for (final ActiveHost activeHost in devicesWithPort) { - // logger.i('Found Cbj Hub device: ${activeHost.address}'); - // if (networkBSSID != null && networkName != null) { - // return insertHubInfo( - // networkIp: activeHost.address, - // networkBSSID: networkBSSID, - // networkName: networkName, - // ); - // } - // } - } catch (e) { - logger.w('Exception searchForHub\n$e'); - } - await Future.delayed(const Duration(seconds: 5)); - return left(const HubFailures.cantFindHubInNetwork()); - } - - @override - Future saveHubIP(String hubIP) async { - logger.w('saveHubIP'); - } - - Future> askLocationPermissionAndLocationOn() async { - final Location location = Location(); - - bool serviceEnabled; - PermissionStatus permissionGranted; - - int permissionCounter = 0; - int disabledCounter = 0; - - // Get location permission is not supported on Linux - if (Platform.isLinux || Platform.isWindows) { - return right(unit); - } - - while (true) { - permissionGranted = await location.hasPermission(); - if (permissionGranted == PermissionStatus.denied) { - permissionGranted = await location.requestPermission(); - if (permissionGranted != PermissionStatus.granted) { - logger.e('Permission to use location is denied'); - await Future.delayed(const Duration(seconds: 10)); - - permissionCounter++; - if (permissionCounter > 5) { - permission_handler.openAppSettings(); - } else if (permissionCounter > 7) { - return const Left(HubFailures.unexpected()); - } - continue; - } - } - - serviceEnabled = await location.serviceEnabled(); - if (!serviceEnabled) { - serviceEnabled = await location.requestService(); - if (!serviceEnabled) { - disabledCounter++; - if (disabledCounter > 2) { - return const Left(HubFailures.unexpected()); - } - logger.w('Location is disabled'); - await Future.delayed(const Duration(seconds: 5)); - continue; - } - } - break; - } - return right(unit); - } - - /// Will save hub info both on ram and to the local database - Future> insertHubInfo({ - required String networkIp, - required String networkName, - required String networkBSSID, - }) async { - IHubConnectionRepository.hubEntity = HubEntity( - hubNetworkBssid: HubNetworkBssid(networkBSSID), - networkName: HubNetworkName(networkName), - lastKnownIp: HubNetworkIp(networkIp), - ); - - final HubDtos hubDtos = - IHubConnectionRepository.hubEntity!.toInfrastructure(); - - (await ILocalDbRepository.instance.saveHubEntity( - hubNetworkBssid: hubDtos.hubNetworkBssid, - networkName: hubDtos.networkName, - lastKnownIp: hubDtos.lastKnownIp, - )) - .fold( - (l) => logger.e('Cant find local Remote Pipes Dns name'), - (r) => logger.i('Found CyBear Jinni Hub'), - ); - return right(unit); - } - - Future streamFromDemoMode() async { - await HubClientDemo.createStreamWithHub(); - } - - /// Load saved Hub network information and load it to - /// IHubConnectionRepository.hubEntity - Future loadNetworkInformationFromDb() async { - try { - String? hubNetworkBssid; - (await ILocalDbRepository.instance.getHubEntityNetworkBssid()).fold( - (l) => throw 'Error getting Hub network Bssid', - (r) => hubNetworkBssid = r, - ); - - String? hubNetworkName; - (await ILocalDbRepository.instance.getHubEntityNetworkName()).fold( - (l) => throw 'Error getting Hub network name', - (r) => hubNetworkName = r, - ); - - String? hubNetworkIp; - (await ILocalDbRepository.instance.getHubEntityLastKnownIp()).fold( - (l) => throw 'Error getting Hub network IP', - (r) => hubNetworkIp = r, - ); - IHubConnectionRepository.hubEntity = HubDtos( - hubNetworkBssid: hubNetworkBssid!, - lastKnownIp: hubNetworkIp!, - networkName: hubNetworkName!, - ).toDomain(); - } catch (e) { - logger.e('Crashed while setting Hub info from local db\n$e'); - } - } - - /// Connect directly to the Hub if possible - Future connectDirectlyToHub() async { - Socket? testHubConnection; - try { - testHubConnection = await Socket.connect( - IHubConnectionRepository.hubEntity!.lastKnownIp.getOrCrash(), - hubPort, - timeout: const Duration(milliseconds: 500), - ); - await testHubConnection.close(); - testHubConnection.destroy(); - testHubConnection = null; - } catch (e) { - await testHubConnection?.close(); - testHubConnection?.destroy(); - - Either foundAHub = await searchForHub(); - // If can't find hub in local network - if (foundAHub.isLeft()) { - // Connect using Remote pipes if connection information exists - if ((await ILocalDbRepository.instance.getRemotePipesDnsName()) - .isRight()) { - await connectionUsingRemotePipes(); - return; - } - while (true) { - foundAHub = await searchForHub(); - if (foundAHub.isRight()) { - break; - } - } - } - } - - tryAgainConnectToTheHubOnceMore = 0; - await HubClient.createStreamWithHub( - IHubConnectionRepository.hubEntity!.lastKnownIp.getOrCrash(), - hubPort, - ); - } - - /// Connect to the Hub using the Remote Pipes - Future connectionUsingRemotePipes() async { - (await ILocalDbRepository.instance.getRemotePipesDnsName()).fold( - (l) async { - (await openAndroidWifiSettingIfPossible()).fold( - (l) { - logger.w( - 'No way to establish connection with the Hub, WiFi or location' - ' permission is closed'); - }, - (r) async { - await connectWithHub(); - }, - ); - }, - (r) { - logger.i('Connect using Remote Pipes'); - HubClient.createStreamWithHub(r, 50056); - tryAgainConnectToTheHubOnceMore = 0; - }, - ); - } - - Future> openAndroidWifiSettingIfPossible() async { - final bool wifiEnabled = await WiFiForIoTPlugin.isEnabled(); - final Location location = Location(); - - if (wifiEnabled && await location.serviceEnabled()) { - final bool wifiEnabled = await WiFiForIoTPlugin.isConnected(); - if (wifiEnabled) { - return right(unit); - } - // while (true) { - // if (wifiEnabled) { - // if (tryAgainConnectToTheHubOnceMore <= 10) { - // // Even if WiFi got enabled it still takes time for the - // // device to complete the automatic connection to previous - // // WiFi network, so we give it a little time before stop trying - // tryAgainConnectToTheHubOnceMore += 1; - // await Future.delayed(const Duration(seconds: 5)); - // } else { - // logger.w( - // "User cannot connect to home as he is A. Not in his home B. Didn't set Remote Pipes", - // ); - // } - // } else { - // logger.t('User not connected to any WiFi, Will try again.'); - // tryAgainConnectToTheHubOnceMore = 0; - // await Future.delayed(const Duration(milliseconds: 500)); - // - // return right(unit); - // } - // } - } else { - logger.w( - 'Will ask the user to open WiFi and gps to try local connection', - ); - final bool wifiEnabled = await WiFiForIoTPlugin.isEnabled(); - if (!wifiEnabled) { - WiFiForIoTPlugin.setEnabled(true, shouldOpenSettings: true); - tryAgainConnectToTheHubOnceMore = 0; - await Future.delayed(const Duration(milliseconds: 500)); - return right(unit); - } - - (await askLocationPermissionAndLocationOn()).fold((l) { - logger.e( - 'User does not allow opening location and does not have remote pipes info', - ); - }, (r) async { - // Try to connect again because there is a chance user without - // remote pipes info but is in his home - return right(unit); - }); - } - return const Left(HubFailures.unexpected()); - } -} diff --git a/lib/infrastructure/hub_client/hub_requests_routing.dart b/lib/infrastructure/hub_client/hub_requests_routing.dart deleted file mode 100644 index 32cd3113..00000000 --- a/lib/infrastructure/hub_client/hub_requests_routing.dart +++ /dev/null @@ -1,221 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:cybearjinni/domain/device/i_device_repository.dart'; -import 'package:cybearjinni/domain/i_hub_connection_repository.dart'; -import 'package:cybearjinni/infrastructure/core/injection.dart'; -import 'package:cybearjinni/infrastructure/core/logger.dart'; -import 'package:grpc/grpc.dart'; - -@Deprecated( - 'Old architecture. Replaced with ConnectionsService. Delete after Re adding Hub comunication', -) -class HubRequestRouting { - static StreamSubscription? requestsFromHubSubscription; - - static Stream? connectivityChangedStream; - - static bool areWeRunning = false; - - // static int numberOfCrashes = 0; - static int numberOfConnectivityChange = 0; - - static Future navigateRequest() async { - if (areWeRunning) { - return; - } - - await Future.delayed(const Duration(milliseconds: 100)); - - if (areWeRunning) { - return; - } - areWeRunning = true; - - // await requestsFromHubSubscription?.cancel(); - // requestsFromHubSubscription = null; - connectivityChangedStream = null; - - requestsFromHubSubscription = HubRequestsToApp.streamRequestsToApp.stream - .listen((dynamic requestsAndStatusFromHub) { - if (requestsAndStatusFromHub is! RequestsAndStatusFromHub) { - return; - } - if (requestsAndStatusFromHub.sendingType == SendingType.entityType) { - navigateDeviceRequest(requestsAndStatusFromHub.allRemoteCommands); - } else if (requestsAndStatusFromHub.sendingType == SendingType.areaType) { - navigateAreaRequest(requestsAndStatusFromHub.allRemoteCommands); - } else if (requestsAndStatusFromHub.sendingType == - SendingType.sceneType) { - navigateSceneRequest(requestsAndStatusFromHub.allRemoteCommands); - } else { - logger.i( - 'Got from Hub unsupported massage type: ' - '${requestsAndStatusFromHub.sendingType}', - ); - } - }); - requestsFromHubSubscription?.onError((error) async { - if (error is GrpcError && error.code == 1) { - logger.t('Hub have been disconnected'); - } - // else if (error is GrpcError && error.code == 2) { - // logger.t('Hub have been terminated'); - // } - else { - logger.e('Hub stream error: $error'); - if (error.toString().contains('errorCode: 10')) { - areWeRunning = false; - - navigateRequest(); - } - } - }); - - connectivityChangedStream = Connectivity().onConnectivityChanged; - connectivityChangedStream?.listen((ConnectivityResult event) async { - numberOfConnectivityChange++; - logger.i('Connectivity changed ${event.name} And $event'); - if (event == ConnectivityResult.none || numberOfConnectivityChange <= 1) { - return; - } - areWeRunning = false; - navigateRequest(); - }); - - await IHubConnectionRepository.instance.connectWithHub(); - } - - static Future navigateAreaRequest( - String allRemoteCommands, - ) async { - // final Map requestAsJson = - // jsonDecode(allRemoteCommands) as Map; - - // final AreaEntityDtos areaEntityDtos = AreaEntityDtos( - // uniqueId: requestAsJson['uniqueId'] as String, - // cbjEntityName: requestAsJson['cbjEntityName'] as String, - // background: requestAsJson['background'] as String, - // areaTypes: Set.from(requestAsJson['areaTypes'] as Set), - // areaDevicesId: - // Set.from(requestAsJson['areaDevicesId'] as Set), - // areaScenesId: - // Set.from(requestAsJson['areaScenesId'] as Set), - // areaRoutinesId: - // Set.from(requestAsJson['areaRoutinesId'] as Set), - // areaBindingsId: - // Set.from(requestAsJson['areaBindingsId'] as Set), - // areaMostUsedBy: - // Set.from(requestAsJson['areaMostUsedBy'] as Set), - // areaPermissions: - // Set.from(requestAsJson['areaPermissions'] as Set), - // ); - - // final AreaEntity areaEntity = areaEntityDtos.toDomain(); - - // IAreaRepository.instance.addOrUpdateArea(areaEntity); - } - - static Future navigateDeviceRequest( - String allRemoteCommands, - ) async { - final Map requestAsJson = - jsonDecode(allRemoteCommands) as Map; - final String? deviceTypeAsString = requestAsJson['entityTypes'] as String?; - - final String? deviceStateAsString = - requestAsJson['entityStateGRPC'] as String?; - if (deviceTypeAsString == null || deviceStateAsString == null) { - return; - } - - ///TODO: add request type login support - - final EntityTypes? deviceType = EntityUtils.stringToDt(deviceTypeAsString); - - final EntityStateGRPC? entityStateGRPC = - EntityUtils.stringToDeviceState(deviceStateAsString); - - if (deviceType == null || entityStateGRPC == null) { - return; - } - - late DeviceEntityBase deviceEntity; - - switch (deviceType) { - case EntityTypes.light: - deviceEntity = - GenericLightDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Light device type'); - case EntityTypes.dimmableLight: - deviceEntity = - GenericDimmableLightDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Dimmable Light device type'); - case EntityTypes.rgbwLights: - deviceEntity = - GenericRgbwLightDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding rgbW light device type'); - case EntityTypes.blinds: - deviceEntity = - GenericBlindsDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Blinds device type'); - case EntityTypes.boiler: - deviceEntity = - GenericBoilerDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Boiler device type'); - case EntityTypes.smartTV: - deviceEntity = - GenericSmartTvDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Smart TV device type'); - case EntityTypes.switch_: - deviceEntity = - GenericSwitchDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Addin' - 'g Switch device type'); - case EntityTypes.smartPlug: - deviceEntity = - GenericSmartPlugDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Smart Plug device type'); - case EntityTypes.smartComputer: - deviceEntity = - GenericSmartComputerDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Smart Plug device type'); - case EntityTypes.printer: - deviceEntity = - GenericPrinterDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Smart printer device type'); - case EntityTypes.securityCamera: - deviceEntity = - GenericSecurityCameraDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.i('Adding Smart camera device type'); - default: - if (entityStateGRPC == EntityStateGRPC.pingNow) { - deviceEntity = - GenericPingDeviceDtos.fromJson(requestAsJson).toDomain(); - logger.t('Got Ping request'); - return; - } else { - logger.w( - 'Entity type is $deviceType is not supported $entityStateGRPC ', - ); - deviceEntity = - GenericUnsupportedDeviceDtos.fromJson(requestAsJson).toDomain(); - } - break; - } - IDeviceRepository.instance.addOrUpdateDevice(deviceEntity); - } - - static Future navigateSceneRequest( - String allRemoteCommands, - ) async { - final Map requestAsJson = - jsonDecode(allRemoteCommands) as Map; - final SceneCbjDtos sceneCbjDtos = SceneCbjDtos.fromJson(requestAsJson); - - getIt() - .addOrUpdateNewSceneInApp(sceneCbjDtos.toDomain()); - } -} diff --git a/lib/infrastructure/isar_local_db/isar_repository.dart b/lib/infrastructure/isar_local_db/isar_repository.dart index ad3e9678..127a9175 100644 --- a/lib/infrastructure/isar_local_db/isar_repository.dart +++ b/lib/infrastructure/isar_local_db/isar_repository.dart @@ -3,7 +3,7 @@ part of 'package:cybearjinni/domain/i_local_db_repository.dart'; class _IsarRepository implements ILocalDbRepository { late Isar isar; @override - Future asyncConstructor() async { + Future asyncConstructor() async { final dir = await getApplicationDocumentsDirectory(); isar = await Isar.open( [ diff --git a/lib/infrastructure/mqtt.dart b/lib/infrastructure/mqtt.dart index 281bc2bb..27a67a14 100644 --- a/lib/infrastructure/mqtt.dart +++ b/lib/infrastructure/mqtt.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'package:cbj_integrations_controller/integrations_controller.dart'; import 'package:cybearjinni/infrastructure/core/logger.dart'; import 'package:mqtt_client/mqtt_client.dart'; @@ -13,10 +11,10 @@ class MqttServerRepository extends IMqttServerRepository { } @override - Future allHubDevicesSubscriptions() async {} + Future allHubDevicesSubscriptions() async {} @override - Future asyncConstructor() async {} + Future asyncConstructor() async {} @override Future connect() async { @@ -45,25 +43,25 @@ class MqttServerRepository extends IMqttServerRepository { String getScenesTopicTypeName() => ''; @override - Future postSmartDeviceToAppMqtt({ + Future postSmartDeviceToAppMqtt({ required DeviceEntityBase entityFromTheHub, }) async { - HubRequestsToApp.streamRequestsToApp.sink.add( - RequestsAndStatusFromHub( - sendingType: SendingType.entityType, - allRemoteCommands: - DeviceHelper.convertDomainToJsonString(entityFromTheHub), - ), - ); + // HubRequestsToApp.streamRequestsToApp.sink.add( + // RequestsAndStatusFromHub( + // sendingType: SendingType.entityType.name, + // allRemoteCommands: + // DeviceHelper.convertDomainToJsonString(entityFromTheHub), + // ), + // ); } @override - Future postToAppMqtt({ + Future postToAppMqtt({ required DeviceEntityBase entityFromTheHub, }) async {} @override - Future postToHubMqtt({ + Future postToHubMqtt({ required dynamic entityFromTheApp, bool? gotFromApp, }) async { @@ -87,24 +85,24 @@ class MqttServerRepository extends IMqttServerRepository { // ISavedAreasRepo.instance.addOrUpdateArea(entityFromTheApp.toDomain()); /// Sends directly to device connector conjecture - HubRequestsToApp.streamRequestsToApp.add( - RequestsAndStatusFromHub( - sendingType: SendingType.areaType, - allRemoteCommands: jsonEncode(entityFromTheApp.toJson()), - ), - ); + // HubRequestsToApp.streamRequestsToApp.add( + // RequestsAndStatusFromHub( + // sendingType: SendingType.areaType.name, + // allRemoteCommands: jsonEncode(entityFromTheApp.toJson()), + // ), + // ); return; } logger.i('Type interaction support is missing $entityFromTheApp'); } @override - Future publishDeviceEntity( + Future publishDeviceEntity( DeviceEntityBase deviceEntityDtoAbstract, ) async {} @override - Future publishMessage(String topic, String message) async {} + Future publishMessage(String topic, String message) async {} @override Future?> readingFromMqttOnce(String topic) async { @@ -112,7 +110,7 @@ class MqttServerRepository extends IMqttServerRepository { } @override - Future sendToApp() async {} + Future sendToApp() async {} @override Stream>> @@ -150,5 +148,5 @@ class MqttServerRepository extends IMqttServerRepository { } @override - Future subscribeToTopic(String topic) async {} + Future subscribeToTopic(String topic) async {} } diff --git a/lib/infrastructure/security_bear_client/security_bear_connection_repository.dart b/lib/infrastructure/security_bear_client/security_bear_connection_repository.dart index ad290f5d..67904fa2 100644 --- a/lib/infrastructure/security_bear_client/security_bear_connection_repository.dart +++ b/lib/infrastructure/security_bear_client/security_bear_connection_repository.dart @@ -16,7 +16,7 @@ class _SecurityBearConnectionRepository static SecurityBearEntity? securityBearEntity; - // Future connectWithSecurityBear() async { + // Future connectWithSecurityBear() async { // if (securityBearEntity == null) { // try { // String? securityBearNetworkBssid; diff --git a/lib/infrastructure/software_info/software_info_repository.dart b/lib/infrastructure/software_info/software_info_repository.dart index 9f528ee2..b18f06ae 100644 --- a/lib/infrastructure/software_info/software_info_repository.dart +++ b/lib/infrastructure/software_info/software_info_repository.dart @@ -44,19 +44,19 @@ class _SoftwareInfoRepository implements ISoftwareInfoRepository { appInfoForHub ??= CompHubInfo(); - final Either hubResponse = - await IHubConnectionRepository.instance.getHubCompInfo(appInfoForHub); - - return hubResponse.fold( - (l) => left(const SoftwareInfoFailures.unexpected()), - (r) { - return right(SoftwareInfoEntity.compHubInfo(r)); - }, - ); + // final Either hubResponse = + // await IHubConnectionRepository.instance.getHubCompInfo(appInfoForHub); + + // return hubResponse.fold( + // (l) => left(const SoftwareInfoFailures.unexpected()), + // (r) { + // return right(SoftwareInfoEntity.compHubInfo(r)); + // }, + // ); } catch (e) { logger.e('Software info from hub error\n$e'); - return left(const SoftwareInfoFailures.unexpected()); } + return left(const SoftwareInfoFailures.unexpected()); } @override diff --git a/lib/presentation/atoms/scene_atom.dart b/lib/presentation/atoms/scene_atom.dart index 8f6d8a49..658d228e 100644 --- a/lib/presentation/atoms/scene_atom.dart +++ b/lib/presentation/atoms/scene_atom.dart @@ -17,7 +17,7 @@ class SceneAtom extends StatefulWidget { class _SceneAtomState extends State { late SceneCbjEntity sceneCbj; - Future _activateScene() async => ConnectionsService.instance + Future _activateScene() async => ConnectionsService.instance .activateScene(widget.currentScene.uniqueId.getOrCrash()); @override diff --git a/lib/presentation/molecules/devices/ac_molecule.dart b/lib/presentation/molecules/devices/ac_molecule.dart index 53d4c71c..903e0600 100644 --- a/lib/presentation/molecules/devices/ac_molecule.dart +++ b/lib/presentation/molecules/devices/ac_molecule.dart @@ -18,7 +18,7 @@ class AcMolecule extends StatefulWidget { } class _AcMoleculeState extends State { - Future _turnOnAllAcs() async { + Future _turnOnAllAcs() async { FlushbarHelper.createLoading( message: 'Turning_On_ac'.tr(), linearProgressIndicator: const LinearProgressIndicator(), @@ -47,7 +47,7 @@ class _AcMoleculeState extends State { ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.acSwitchState, actionType: action, @@ -55,7 +55,7 @@ class _AcMoleculeState extends State { ); } - Future _turnOffAllAcs() async { + Future _turnOffAllAcs() async { FlushbarHelper.createLoading( message: 'Turning_Off_ac'.tr(), linearProgressIndicator: const LinearProgressIndicator(), diff --git a/lib/presentation/molecules/devices/blind_molecule.dart b/lib/presentation/molecules/devices/blind_molecule.dart index 4795a196..a95eb30f 100644 --- a/lib/presentation/molecules/devices/blind_molecule.dart +++ b/lib/presentation/molecules/devices/blind_molecule.dart @@ -21,7 +21,7 @@ class BlindMolecule extends StatefulWidget { } class _BlindMoleculeState extends State { - Future _moveUpAllBlinds() async { + Future _moveUpAllBlinds() async { FlushbarHelper.createLoading( message: 'Pulling_Up_all_blinds'.tr(), linearProgressIndicator: const LinearProgressIndicator(), @@ -50,7 +50,7 @@ class _BlindMoleculeState extends State { ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.blindsSwitchState, actionType: action, @@ -58,7 +58,7 @@ class _BlindMoleculeState extends State { ); } - Future _stopAllBlinds(List blindsIdToStop) async { + Future _stopAllBlinds(List blindsIdToStop) async { FlushbarHelper.createLoading( message: 'Stopping_all_blinds'.tr(), linearProgressIndicator: const LinearProgressIndicator(), @@ -67,7 +67,7 @@ class _BlindMoleculeState extends State { setEntityState(EntityActions.stop); } - Future _moveDownAllBlinds(List blindsIdToTurnDown) async { + Future _moveDownAllBlinds(List blindsIdToTurnDown) async { FlushbarHelper.createLoading( message: 'Pulling_down_all_blinds'.tr(), linearProgressIndicator: const LinearProgressIndicator(), diff --git a/lib/presentation/molecules/devices/boiler_molecule.dart b/lib/presentation/molecules/devices/boiler_molecule.dart index 2987f8cd..c881dd98 100644 --- a/lib/presentation/molecules/devices/boiler_molecule.dart +++ b/lib/presentation/molecules/devices/boiler_molecule.dart @@ -18,7 +18,7 @@ class BoilerMolecule extends StatefulWidget { } class _BoilerMoleculeState extends State { - Future _turnOnAllBoilers() async { + Future _turnOnAllBoilers() async { FlushbarHelper.createLoading( message: 'Turning_On_boiler'.tr(), linearProgressIndicator: const LinearProgressIndicator(), @@ -47,7 +47,7 @@ class _BoilerMoleculeState extends State { ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.boilerSwitchState, actionType: action, @@ -55,7 +55,7 @@ class _BoilerMoleculeState extends State { ); } - Future _turnOffAllBoilers() async { + Future _turnOffAllBoilers() async { FlushbarHelper.createLoading( message: 'Turning_Off_boiler'.tr(), linearProgressIndicator: const LinearProgressIndicator(), diff --git a/lib/presentation/molecules/devices/dimmable_light_molecule.dart b/lib/presentation/molecules/devices/dimmable_light_molecule.dart index e7a5e3da..5128c3f9 100644 --- a/lib/presentation/molecules/devices/dimmable_light_molecule.dart +++ b/lib/presentation/molecules/devices/dimmable_light_molecule.dart @@ -27,7 +27,7 @@ class _DimmableLightMoleculeState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { final GenericDimmableLightDE rgbwLightDe = widget.entity; double lightBrightness = @@ -42,7 +42,7 @@ class _DimmableLightMoleculeState extends State { }); } - Future _changeBrightness(double value) async { + Future _changeBrightness(double value) async { setState(() { brightness = value; }); @@ -90,7 +90,7 @@ class _DimmableLightMoleculeState extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: property, actionType: action, diff --git a/lib/presentation/molecules/devices/light_card_molecule.dart b/lib/presentation/molecules/devices/light_card_molecule.dart index eb6d16c2..bf5cb74f 100644 --- a/lib/presentation/molecules/devices/light_card_molecule.dart +++ b/lib/presentation/molecules/devices/light_card_molecule.dart @@ -1,5 +1,4 @@ import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:cybearjinni/domain/device/i_device_repository.dart'; import 'package:cybearjinni/presentation/atoms/atoms.dart'; import 'package:flutter/material.dart'; @@ -8,19 +7,19 @@ class LightCardMolecule extends StatelessWidget { final GenericLightDE? entity; - Future _onChange(bool value) async { - final GenericLightDE tempDeviceEntity = entity! - ..entityStateGRPC = EntityState.state(EntityStateGRPC.waitingInCloud) - ..lightSwitchState = GenericLightSwitchState(value.toString()); + Future _onChange(bool value) async { + // final GenericLightDE tempDeviceEntity = entity! + // ..entityStateGRPC = EntityState.state(EntityStateGRPC.waitingInCloud) + // ..lightSwitchState = GenericLightSwitchState(value.toString()); if (value) { - await IDeviceRepository.instance.turnOnDevices( - devicesId: [tempDeviceEntity.deviceCbjUniqueId.getOrCrash()], - ); + // await IDeviceRepository.instance.turnOnDevices( + // devicesId: [tempDeviceEntity.deviceCbjUniqueId.getOrCrash()], + // ); } else { - await IDeviceRepository.instance.turnOffDevices( - devicesId: [tempDeviceEntity.deviceCbjUniqueId.getOrCrash()], - ); + // await IDeviceRepository.instance.turnOffDevices( + // devicesId: [tempDeviceEntity.deviceCbjUniqueId.getOrCrash()], + // ); } } diff --git a/lib/presentation/molecules/devices/light_molecule.dart b/lib/presentation/molecules/devices/light_molecule.dart index 62539a5e..70d820b3 100644 --- a/lib/presentation/molecules/devices/light_molecule.dart +++ b/lib/presentation/molecules/devices/light_molecule.dart @@ -35,7 +35,7 @@ class LightMolecule extends StatelessWidget { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.lightSwitchState, actionType: action, diff --git a/lib/presentation/molecules/devices/printer_molecule.dart b/lib/presentation/molecules/devices/printer_molecule.dart index 49637125..e0e3cfec 100644 --- a/lib/presentation/molecules/devices/printer_molecule.dart +++ b/lib/presentation/molecules/devices/printer_molecule.dart @@ -18,7 +18,7 @@ class PrinterMolecule extends StatefulWidget { } class _PrinterMoleculeState extends State { - Future _openPrintersWebPage() async { + Future _openPrintersWebPage() async { FlushbarHelper.createLoading( message: 'Opening printers Web Page', linearProgressIndicator: const LinearProgressIndicator(), diff --git a/lib/presentation/molecules/devices/rgb_light_molecule.dart b/lib/presentation/molecules/devices/rgb_light_molecule.dart index bff49486..687b51b3 100644 --- a/lib/presentation/molecules/devices/rgb_light_molecule.dart +++ b/lib/presentation/molecules/devices/rgb_light_molecule.dart @@ -30,7 +30,7 @@ class _RgbwLightMoleculeState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { final GenericRgbwLightDE rgbwLightDe = widget.entity; int lightColorTemperature = @@ -83,7 +83,7 @@ class _RgbwLightMoleculeState extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: entityProperties, actionType: action, @@ -92,7 +92,7 @@ class _RgbwLightMoleculeState extends State { ); } - Future _changeBrightness(double value) async { + Future _changeBrightness(double value) async { setState(() { brightness = value; }); @@ -184,7 +184,7 @@ class _LightColorMods extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { final GenericRgbwLightDE rgbwLightDe = widget.entity; int lightColorTemperature = @@ -230,7 +230,7 @@ class _LightColorMods extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: entityProperties, actionType: action, @@ -239,7 +239,7 @@ class _LightColorMods extends State { ); } - Future _changeColorTemperature(int newColorTemperature) async { + Future _changeColorTemperature(int newColorTemperature) async { setState(() { colorTemperature = newColorTemperature; }); @@ -250,7 +250,7 @@ class _LightColorMods extends State { ); } - Future _changeHsvColor(HSVColor newHsvColor) async { + Future _changeHsvColor(HSVColor newHsvColor) async { setState(() { hsvColor = newHsvColor; }); @@ -309,14 +309,14 @@ class _LightColorMods extends State { ); } - Future _showWhiteMode() async { + Future _showWhiteMode() async { setState(() { colorModFocus = 0; colorModeWidget = getWhiteModeWidget(); }); } - Future _showColorMode() async { + Future _showColorMode() async { setState(() { colorModFocus = 1; colorModeWidget = getHsvColorModeWidget(); diff --git a/lib/presentation/molecules/devices/security_camera_molecule.dart b/lib/presentation/molecules/devices/security_camera_molecule.dart index f530314a..ec964cae 100644 --- a/lib/presentation/molecules/devices/security_camera_molecule.dart +++ b/lib/presentation/molecules/devices/security_camera_molecule.dart @@ -19,7 +19,7 @@ class SecurityCameraMolecule extends StatefulWidget { } class _SecurityCameraMoleculeState extends State { - Future _openCameraPage() async { + Future _openCameraPage() async { FlushbarHelper.createLoading( message: 'Opening Camera', linearProgressIndicator: const LinearProgressIndicator(), diff --git a/lib/presentation/molecules/devices/smart_computer_molecule.dart b/lib/presentation/molecules/devices/smart_computer_molecule.dart index f30f7c3a..7328aeca 100644 --- a/lib/presentation/molecules/devices/smart_computer_molecule.dart +++ b/lib/presentation/molecules/devices/smart_computer_molecule.dart @@ -1,6 +1,5 @@ import 'package:another_flushbar/flushbar_helper.dart'; import 'package:cbj_integrations_controller/integrations_controller.dart'; -import 'package:cybearjinni/domain/device/i_device_repository.dart'; import 'package:cybearjinni/presentation/atoms/atoms.dart'; import 'package:cybearjinni/presentation/molecules/molecules.dart'; import 'package:flutter/material.dart'; @@ -18,22 +17,22 @@ class SmartComputerMolecule extends StatefulWidget { } class _SmartComputerMoleculeState extends State { - Future _suspendAllSmartComputers(List smartComputersId) async { + Future _suspendAllSmartComputers(List smartComputersId) async { FlushbarHelper.createLoading( message: 'Suspending all Smart Computers', linearProgressIndicator: const LinearProgressIndicator(), ).show(context); - IDeviceRepository.instance.suspendDevices(devicesId: smartComputersId); + // IDeviceRepository.instance.suspendDevices(deviDscesId: smartComputersId); } - Future _shutdownAllSmartComputers(List smartComputersId) async { + Future _shutdownAllSmartComputers(List smartComputersId) async { FlushbarHelper.createLoading( message: 'Suspending all Smart Computers', linearProgressIndicator: const LinearProgressIndicator(), ).show(context); - IDeviceRepository.instance.shutdownDevices(devicesId: smartComputersId); + // IDeviceRepository.instance.shutdownDevices(devicesId: smartComputersId); } void suspendComputer(BuildContext context) { diff --git a/lib/presentation/molecules/devices/smart_plug_molecule.dart b/lib/presentation/molecules/devices/smart_plug_molecule.dart index a215944c..19a3cfc6 100644 --- a/lib/presentation/molecules/devices/smart_plug_molecule.dart +++ b/lib/presentation/molecules/devices/smart_plug_molecule.dart @@ -23,7 +23,7 @@ class _SmartPlugsMoleculeState extends State { Timer? timeFromLastColorChange; HSVColor? lastColoredPicked; - Future _changeAction(bool value) async { + Future _changeAction(bool value) async { setEntityState(value ? EntityActions.on : EntityActions.off); } @@ -45,7 +45,7 @@ class _SmartPlugsMoleculeState extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.lightSwitchState, actionType: action, diff --git a/lib/presentation/molecules/devices/smart_tv_molecule.dart b/lib/presentation/molecules/devices/smart_tv_molecule.dart index 750c5d80..8a6739c2 100644 --- a/lib/presentation/molecules/devices/smart_tv_molecule.dart +++ b/lib/presentation/molecules/devices/smart_tv_molecule.dart @@ -94,7 +94,7 @@ class _SmartTvMoleculeState extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: property, actionType: action, diff --git a/lib/presentation/molecules/devices/switch_molecule.dart b/lib/presentation/molecules/devices/switch_molecule.dart index af5f09ed..0594b522 100644 --- a/lib/presentation/molecules/devices/switch_molecule.dart +++ b/lib/presentation/molecules/devices/switch_molecule.dart @@ -23,7 +23,7 @@ class _SwitchMoleculeState extends State { Timer? timeFromLastColorChange; HSVColor? lastColoredPicked; - Future _changeAction(bool value) async { + Future _changeAction(bool value) async { setEntityState(value ? EntityActions.on : EntityActions.off); } @@ -45,7 +45,7 @@ class _SwitchMoleculeState extends State { ], ); ConnectionsService.instance.setEntityState( - ActionObject( + RequestActionObject( uniqueIdByVendor: uniqueIdByVendor, property: EntityProperties.lightSwitchState, actionType: action, diff --git a/lib/presentation/pages/add_action_page.dart b/lib/presentation/pages/add_action_page.dart index 61b19e62..c405ad66 100644 --- a/lib/presentation/pages/add_action_page.dart +++ b/lib/presentation/pages/add_action_page.dart @@ -28,13 +28,13 @@ class _AddActionPageState extends State { }); } - Future onActionSelected(String value) async { + Future onActionSelected(String value) async { setState(() { selectedAction = EntityActions.values.elementAt(int.parse(value)); }); } - Future _onPropertySelected(String property) async { + Future _onPropertySelected(String property) async { setState(() { selectedProperty = EntityProperties.values.elementAt(int.parse(property)); }); diff --git a/lib/presentation/pages/add_bindings/add_binding_page.dart b/lib/presentation/pages/add_bindings/add_binding_page.dart index a216165d..ef654864 100644 --- a/lib/presentation/pages/add_bindings/add_binding_page.dart +++ b/lib/presentation/pages/add_bindings/add_binding_page.dart @@ -42,16 +42,16 @@ class _AddBindingPageState extends State { bool showErrorMessages = false; bool isSubmitting = false; - Future initialzeEntities() async { + Future initialzeEntities() async { final HashMap entitiesTemp = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; setState(() { entities = entitiesTemp; }); } - Future _sendBindingToHub() async { + Future _sendBindingToHub() async { // IBindingCbjRepository.instance // .addOrUpdateNewBindingInHubFromDevicesPropertyActionList( // bindingName, @@ -59,7 +59,7 @@ class _AddBindingPageState extends State { // ); } - Future _addFullAction(EntityActionObject value) async { + Future _addFullAction(EntityActionObject value) async { setState(() { allDevicesWithNewAction.add(value); }); @@ -142,7 +142,8 @@ class _AddBindingPageState extends State { ), onPressed: (_) async { final EntityActionObject? actionList = - await context.router.push( + await context.router + .push( AddActionRoute(entities: entities!), ); if (actionList != null) { diff --git a/lib/presentation/pages/add_new_area_page.dart b/lib/presentation/pages/add_new_area_page.dart index 8b6331dc..f9d8b4c5 100644 --- a/lib/presentation/pages/add_new_area_page.dart +++ b/lib/presentation/pages/add_new_area_page.dart @@ -44,7 +44,7 @@ class _AddNewAreaFormState extends State { bool showErrorMessages = false; bool isSubmitting = false; - // Future _initialized() async { + // Future _initialized() async { // IAreaRepository.instance.getAllAreas().fold((l) => null, (r) { // _allAreas = Set.from(r.iter); // }); @@ -60,7 +60,7 @@ class _AddNewAreaFormState extends State { // }); // } - Future _createArea() async { + Future _createArea() async { final AreaEntity areaEntity = AreaEntity( uniqueId: AreaUniqueId.fromUniqueString(areaUniqueId.getOrCrash()), cbjEntityName: AreaDefaultName(cbjEntityName.getOrCrash()), @@ -77,13 +77,13 @@ class _AddNewAreaFormState extends State { ConnectionsService.instance.setNewArea(areaEntity); } - Future _defaultNameChanged(String value) async { + Future _defaultNameChanged(String value) async { setState(() { cbjEntityName = AreaDefaultName(value); }); } - Future _areaTypesChanged(Set value) async { + Future _areaTypesChanged(Set value) async { setState(() { areaTypes = AreaTypes(value); }); @@ -148,14 +148,14 @@ class _AddNewAreaFormState extends State { } return MultiSelectItem( - areaPurposeType.value, + areaPurposeType.name, areaNameEdited, ); }).toList(), listType: MultiSelectListType.CHIP, - onConfirm: (List values) { + onConfirm: (List values) { _areaTypesChanged( - values.map((e) => e.toString()).toSet(), + values.map((e) => e).toSet(), ); }, ), diff --git a/lib/presentation/pages/add_new_devices_process/choose_device_vendor_to_add/widgets/vendors_list.dart b/lib/presentation/pages/add_new_devices_process/choose_device_vendor_to_add/widgets/vendors_list.dart index 000a7f61..ffcc0553 100644 --- a/lib/presentation/pages/add_new_devices_process/choose_device_vendor_to_add/widgets/vendors_list.dart +++ b/lib/presentation/pages/add_new_devices_process/choose_device_vendor_to_add/widgets/vendors_list.dart @@ -18,7 +18,7 @@ class _VendorsListState extends State { initializeVendors(); } - Future initializeVendors() async { + Future initializeVendors() async { final List temp = await ConnectionsService.instance.getVendors(); temp.removeWhere( diff --git a/lib/presentation/pages/add_new_devices_process/computer_connection_check/widgets/computer_connection_check_widget.dart b/lib/presentation/pages/add_new_devices_process/computer_connection_check/widgets/computer_connection_check_widget.dart index 8e734e0f..6131c0e5 100644 --- a/lib/presentation/pages/add_new_devices_process/computer_connection_check/widgets/computer_connection_check_widget.dart +++ b/lib/presentation/pages/add_new_devices_process/computer_connection_check/widgets/computer_connection_check_widget.dart @@ -52,7 +52,7 @@ class _ComputerConnectionCheckWidgetState ).show(context); } - Future _checkConnectedToWiFiNetwork() async { + Future _checkConnectedToWiFiNetwork() async { if ((await WiFiScan.instance.canStartScan()) == CanStartScan.yes) { await WiFiScan.instance.startScan(); if ((await WiFiScan.instance.canGetScannedResults()) == @@ -79,7 +79,7 @@ class _ComputerConnectionCheckWidgetState _searchIfHubOnTheSameWifiNetwork(); } - Future _searchIfHubOnTheSameWifiNetwork() async { + Future _searchIfHubOnTheSameWifiNetwork() async { int connectionTimeout = 0; while (true) { diff --git a/lib/presentation/pages/add_new_devices_process/configure_new_cbj_comp/widgets/configure_new_cbj_comp_widget.dart b/lib/presentation/pages/add_new_devices_process/configure_new_cbj_comp/widgets/configure_new_cbj_comp_widget.dart index ee1affc7..982fb7d2 100644 --- a/lib/presentation/pages/add_new_devices_process/configure_new_cbj_comp/widgets/configure_new_cbj_comp_widget.dart +++ b/lib/presentation/pages/add_new_devices_process/configure_new_cbj_comp/widgets/configure_new_cbj_comp_widget.dart @@ -48,7 +48,7 @@ class _ConfigureNewCbjCompWidgetsState _sendHotSpotInformation(widget.cbjCompEntity); } - Future _sendHotSpotInformation(CbjCompEntity cBJCompEntity) async { + Future _sendHotSpotInformation(CbjCompEntity cBJCompEntity) async { progressPercentage += 0.3; setState(() { state = ConfigureNewCbjCompState.actionInProgress; diff --git a/lib/presentation/pages/add_new_devices_process/connect_to_home_wifi/widgets/connect_to_home_wifi_widget.dart b/lib/presentation/pages/add_new_devices_process/connect_to_home_wifi/widgets/connect_to_home_wifi_widget.dart index 7e8d4cc8..b3c16849 100644 --- a/lib/presentation/pages/add_new_devices_process/connect_to_home_wifi/widgets/connect_to_home_wifi_widget.dart +++ b/lib/presentation/pages/add_new_devices_process/connect_to_home_wifi/widgets/connect_to_home_wifi_widget.dart @@ -25,7 +25,7 @@ class _ConnectToHomeWiFiWidgetState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { final dartz.Either doesWiFiEnabled = await IManageNetworkRepository.instance.doesWiFiEnabled(); @@ -41,7 +41,7 @@ class _ConnectToHomeWiFiWidgetState extends State { }); } - Future _connectToWiFi() async { + Future _connectToWiFi() async { final ManageNetworkEntity manageWiFiEntity = ManageNetworkEntity( name: wifiName, pass: wifiPassword, diff --git a/lib/presentation/pages/add_new_devices_process/open_access_point/widgets/open_access_point_widget.dart b/lib/presentation/pages/add_new_devices_process/open_access_point/widgets/open_access_point_widget.dart index f6f293fd..6e742a21 100644 --- a/lib/presentation/pages/add_new_devices_process/open_access_point/widgets/open_access_point_widget.dart +++ b/lib/presentation/pages/add_new_devices_process/open_access_point/widgets/open_access_point_widget.dart @@ -29,7 +29,7 @@ class _OpenAccessPointWidgetState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { OpenAccessPointState stateTemp; if (Platform.isAndroid) { final ManageNetworkEntity manageNetworkEntity = ManageNetworkEntity( @@ -52,7 +52,7 @@ class _OpenAccessPointWidgetState extends State { }); } - Future _doesAccessPointOpen() async { + Future _doesAccessPointOpen() async { OpenAccessPointState stateTemp; if (Platform.isAndroid) { diff --git a/lib/presentation/pages/add_new_devices_process/scan_for_new_cbj_comps/widgets/scan_for_new_cbj_comps_widget.dart b/lib/presentation/pages/add_new_devices_process/scan_for_new_cbj_comps/widgets/scan_for_new_cbj_comps_widget.dart index 9e1bd7d8..682c1998 100644 --- a/lib/presentation/pages/add_new_devices_process/scan_for_new_cbj_comps/widgets/scan_for_new_cbj_comps_widget.dart +++ b/lib/presentation/pages/add_new_devices_process/scan_for_new_cbj_comps/widgets/scan_for_new_cbj_comps_widget.dart @@ -28,7 +28,8 @@ class _ScanForNewCBJCompsWidgetState extends State { _watchAllStarted(); } - Future _watchAllStarted() async { + Future + _watchAllStarted() async { await _cbjCompStreamSubscription?.cancel(); _cbjCompStreamSubscription = ICbjCompRepository.instance .getConnectedComputersIP() @@ -45,7 +46,7 @@ class _ScanForNewCBJCompsWidgetState extends State { }); } - Future _compDevicesReceived( + Future _compDevicesReceived( dartz.Either failureOrCBJCompList, ) async { final dynamic failureOrCompListDynamic = failureOrCBJCompList.fold( @@ -71,7 +72,8 @@ class _ScanForNewCBJCompsWidgetState extends State { } @override - Future dispose() async { + Future + dispose() async { await _cbjCompStreamSubscription?.cancel(); await ICbjCompRepository.instance.shutdownServer(); return super.dispose(); diff --git a/lib/presentation/pages/add_routine/add_routine_page.dart b/lib/presentation/pages/add_routine/add_routine_page.dart index 36aba05f..ab701e9f 100644 --- a/lib/presentation/pages/add_routine/add_routine_page.dart +++ b/lib/presentation/pages/add_routine/add_routine_page.dart @@ -52,16 +52,17 @@ class _AddRoutinePageState extends State { bool isSubmitting = false; HashMap? entities; - Future initialzeEntities() async { + Future initialzeEntities() async { final HashMap entitiesTemp = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; setState(() { entities = entitiesTemp; }); } - Future _sendRoutineToHub() async { + Future + _sendRoutineToHub() async { if (daysToRepeat == null || hourToRepeat == null || minutesToRepeat == null || @@ -78,11 +79,11 @@ class _AddRoutinePageState extends State { // ); } - Future _routineNameChange(String value) async { + Future _routineNameChange(String value) async { routineName = value; } - Future _addFullAction(EntityActionObject value) async { + Future _addFullAction(EntityActionObject value) async { setState(() { allDevicesWithNewAction.add(value); }); diff --git a/lib/presentation/pages/add_scene/add_scene_page.dart b/lib/presentation/pages/add_scene/add_scene_page.dart index cce9e4f8..425d0a8c 100644 --- a/lib/presentation/pages/add_scene/add_scene_page.dart +++ b/lib/presentation/pages/add_scene/add_scene_page.dart @@ -33,9 +33,9 @@ class _AddScenePageState extends State { /// List of devices with entities, will be treated as actions HashSet entitiesWithActions = HashSet(); - Future initialzeEntities() async { + Future initialzeEntities() async { final HashMap entitiesTemp = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; setState(() { entities = entitiesTemp; @@ -54,7 +54,7 @@ class _AddScenePageState extends State { ) .toList(); - Future _sendSceneToHub() async { + Future _sendSceneToHub() async { final List actions = entitiesWithActionsToActionsByVendor(); @@ -81,11 +81,7 @@ class _AddScenePageState extends State { ConnectionsService.instance.addScene(scene); } - void _sceneNameChange(String value) { - sceneName = value; - } - - Future _addFullAction(EntityActionObject value) async { + Future _addFullAction(EntityActionObject value) async { setState(() { entitiesWithActions.add(value); }); @@ -123,7 +119,7 @@ class _AddScenePageState extends State { labelText: 'Scene Name', ), style: const TextStyle(color: Colors.black), - onChanged: _sceneNameChange, + onChanged: (value) => sceneName = value, ), SizedBox( height: 300, diff --git a/lib/presentation/pages/change_area_for_devices_page.dart b/lib/presentation/pages/change_area_for_devices_page.dart index ea615a1e..9956c163 100644 --- a/lib/presentation/pages/change_area_for_devices_page.dart +++ b/lib/presentation/pages/change_area_for_devices_page.dart @@ -52,14 +52,14 @@ class _ChangeAreaForDevicesWidgetState _initialized(); } - Future _initialized() async { + Future _initialized() async { getAreas(); getEntities(); } Future getAreas() async { final HashMap areasTemp = - await ConnectionsService.instance.getAllAreas; + await ConnectionsService.instance.getAreas; setState(() { areas = areasTemp; }); @@ -67,7 +67,7 @@ class _ChangeAreaForDevicesWidgetState Future getEntities() async { final HashMap entitiesTemp = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; setState(() { entities = entitiesTemp; }); diff --git a/lib/presentation/pages/connect_to_hub/connect_to_hub_page.dart b/lib/presentation/pages/connect_to_hub/connect_to_hub_page.dart index 8380df08..feed20bd 100644 --- a/lib/presentation/pages/connect_to_hub/connect_to_hub_page.dart +++ b/lib/presentation/pages/connect_to_hub/connect_to_hub_page.dart @@ -1,5 +1,4 @@ import 'package:auto_route/auto_route.dart'; -import 'package:cybearjinni/domain/i_hub_connection_repository.dart'; import 'package:cybearjinni/presentation/atoms/atoms.dart'; import 'package:cybearjinni/presentation/core/routes/app_router.gr.dart'; import 'package:cybearjinni/presentation/pages/connect_to_hub/widgets/cbj_hub_in_network_widget.dart'; @@ -160,7 +159,7 @@ class ConnectToHubPage extends StatelessWidget { GestureDetector( onTap: () { context.router.push(const SmartCameraContainerRoute()); - IHubConnectionRepository.instance.closeConnection(); + // IHubConnectionRepository.instance.closeConnection(); }, child: Container( margin: const EdgeInsets.symmetric(horizontal: 30), diff --git a/lib/presentation/pages/connect_to_hub/widgets/cbj_hub_in_network_widget.dart b/lib/presentation/pages/connect_to_hub/widgets/cbj_hub_in_network_widget.dart index 967edd8a..26a4054f 100644 --- a/lib/presentation/pages/connect_to_hub/widgets/cbj_hub_in_network_widget.dart +++ b/lib/presentation/pages/connect_to_hub/widgets/cbj_hub_in_network_widget.dart @@ -42,7 +42,7 @@ class _CbjHubInNetworkWidgetState extends State { }); final HashMap entities = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; if (entities.isNotEmpty) { if (!mounted || foundEntity) { diff --git a/lib/presentation/pages/connect_to_hub_more_page.dart b/lib/presentation/pages/connect_to_hub_more_page.dart index 7d89f66d..42e1e0fe 100644 --- a/lib/presentation/pages/connect_to_hub_more_page.dart +++ b/lib/presentation/pages/connect_to_hub_more_page.dart @@ -1,16 +1,12 @@ import 'dart:async'; import 'package:auto_route/auto_route.dart'; -import 'package:cbj_integrations_controller/integrations_controller.dart'; import 'package:cybearjinni/domain/connections_service.dart'; -import 'package:cybearjinni/domain/device/devices_failures.dart'; import 'package:cybearjinni/presentation/atoms/atoms.dart'; import 'package:cybearjinni/presentation/core/routes/app_router.gr.dart'; -import 'package:dartz/dartz.dart' as dartz; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:hexcolor/hexcolor.dart'; -import 'package:kt_dart/kt.dart'; @RoutePage() class ConnectToHubMorePage extends StatelessWidget { @@ -88,23 +84,13 @@ class ConnectToHubMoreWidget extends StatefulWidget { } class _ConnectToHubMoreWidgetState extends State { - StreamSubscription>>? - _deviceStreamSubscription; - bool isLoading = false; - Future _connectInDemoMode() async { + Future _connectInDemoMode() async { ConnectionsService.setCurrentConnectionType(ConnectionType.demo); context.router.replace(const HomeRoute()); } - @override - void dispose() { - _deviceStreamSubscription?.cancel(); - - super.dispose(); - } - @override Widget build(BuildContext context) { if (isLoading) { diff --git a/lib/presentation/pages/entities_in_area_page.dart b/lib/presentation/pages/entities_in_area_page.dart index 8d9208e4..315fd83b 100644 --- a/lib/presentation/pages/entities_in_area_page.dart +++ b/lib/presentation/pages/entities_in_area_page.dart @@ -33,7 +33,7 @@ class _EntitiesInAreaPageState extends State { Future initialzeDevices() async { final Map entitiesMap = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; final Set entityIdsInArea = widget.areaEntity.entitiesId.getOrCrash(); final Set entityTypes = widget.entityTypes; diff --git a/lib/presentation/pages/entities_in_network_page.dart b/lib/presentation/pages/entities_in_network_page.dart index 2c0e13cb..f2c60885 100644 --- a/lib/presentation/pages/entities_in_network_page.dart +++ b/lib/presentation/pages/entities_in_network_page.dart @@ -23,7 +23,7 @@ class _EntitiesInNetworkPageState extends State { Future initializeAllEntities() async { final Map entities = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; setState(() { allEntities = entities.values.toList(); }); diff --git a/lib/presentation/pages/home_page/home_page.dart b/lib/presentation/pages/home_page/home_page.dart index 13b50c09..11419604 100644 --- a/lib/presentation/pages/home_page/home_page.dart +++ b/lib/presentation/pages/home_page/home_page.dart @@ -45,9 +45,9 @@ class _HomePageState extends State { HashMap? areas; HashMap? entities; - Future initializedScenes() async { + Future initializedScenes() async { final HashMap scenecsTemp = - await ConnectionsService.instance.getScenes(); + await ConnectionsService.instance.getScenes; setState(() { scenes = scenecsTemp; @@ -72,7 +72,7 @@ class _HomePageState extends State { Future _initialzeAreas() async { final HashMap areasTemp = - await ConnectionsService.instance.getAllAreas; + await ConnectionsService.instance.getAreas; setState(() { areas ??= HashMap(); @@ -101,7 +101,7 @@ class _HomePageState extends State { Future _initialzeEntities() async { final HashMap entitiesTemp = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; entitiesTemp.removeWhere( (key, value) => value.entityTypes.type == EntityTypes.smartTypeNotSupported || diff --git a/lib/presentation/pages/introduction_screen/introduction_screen_body.dart b/lib/presentation/pages/introduction_screen/introduction_screen_body.dart index d4312805..6fe7822e 100644 --- a/lib/presentation/pages/introduction_screen/introduction_screen_body.dart +++ b/lib/presentation/pages/introduction_screen/introduction_screen_body.dart @@ -116,7 +116,7 @@ class _IntroductionScreenBodyState extends State { ), onDone: () async { final HashMap entities = - await ConnectionsService.instance.getAllEntities; + await ConnectionsService.instance.getEntities; if (!mounted) { return; } diff --git a/lib/presentation/pages/plus_button.dart b/lib/presentation/pages/plus_button.dart index 0d8d0369..7d2a9c26 100644 --- a/lib/presentation/pages/plus_button.dart +++ b/lib/presentation/pages/plus_button.dart @@ -10,7 +10,7 @@ import 'package:iconify_flutter/icons/simple_icons.dart'; @RoutePage() class PlusButtonPage extends StatelessWidget { - Future _logout(BuildContext context) async { + Future _logout(BuildContext context) async { context.router.replace(const ConnectToHubRoute()); ConnectionsService.setCurrentConnectionType(null); } diff --git a/lib/presentation/pages/remote_pipes_page.dart b/lib/presentation/pages/remote_pipes_page.dart index 1662f52b..f4bdc236 100644 --- a/lib/presentation/pages/remote_pipes_page.dart +++ b/lib/presentation/pages/remote_pipes_page.dart @@ -61,13 +61,13 @@ class RemotePipesWidget extends StatefulWidget { class _RemotePipesWidgetState extends State { String? remotePipesDomainName; - Future _remotePipesDomainChanged(String value) async { + Future _remotePipesDomainChanged(String value) async { setState(() { remotePipesDomainName = value; }); } - Future _addRemotePipeUrl() async { + Future _addRemotePipeUrl() async { if (remotePipesDomainName == null || remotePipesDomainName!.isEmpty) { return; } diff --git a/lib/presentation/pages/scenes/scenes_page.dart b/lib/presentation/pages/scenes/scenes_page.dart index 6e77c17a..74b221b4 100644 --- a/lib/presentation/pages/scenes/scenes_page.dart +++ b/lib/presentation/pages/scenes/scenes_page.dart @@ -29,9 +29,9 @@ class _ScenesPageState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { final HashMap scenecsTemp = - await ConnectionsService.instance.getScenes(); + await ConnectionsService.instance.getScenes; final HashMap scenesInArea = HashMap.fromEntries( widget.area.areaScenesId.getOrCrash().map((e) { diff --git a/lib/presentation/pages/software_info_page.dart b/lib/presentation/pages/software_info_page.dart index fb1f0bb5..98a68610 100644 --- a/lib/presentation/pages/software_info_page.dart +++ b/lib/presentation/pages/software_info_page.dart @@ -67,7 +67,7 @@ class _SoftwareInfoWidgetState extends State { _initialized(); } - Future _initialized() async { + Future _initialized() async { SoftwareInfoEntity? appInfoEntity; (await ISoftwareInfoRepository.instance.getAppSoftwareInfo()).fold( (l) => l,