diff --git a/lib/features/devices/bloc/acs_bloc/acs_bloc.dart b/lib/features/devices/bloc/acs_bloc/acs_bloc.dart index d5c21c0..7b47fce 100644 --- a/lib/features/devices/bloc/acs_bloc/acs_bloc.dart +++ b/lib/features/devices/bloc/acs_bloc/acs_bloc.dart @@ -81,13 +81,16 @@ class ACsBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$acId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { + _streamSubscription = stream.listen((DatabaseEvent event) { Map usersMap = event.snapshot.value as Map; List statusList = []; @@ -96,14 +99,21 @@ class ACsBloc extends Bloc { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = AcStatusModel.fromJson(usersMap['productUuid'], statusList); + add(AcUpdated()); }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + _onAcUpdated(AcUpdated event, Emitter emit) { emit(GetAcStatusState(acStatusModel: deviceStatus)); } diff --git a/lib/features/devices/bloc/ceiling_bloc/ceiling_sensor_bloc.dart b/lib/features/devices/bloc/ceiling_bloc/ceiling_sensor_bloc.dart index 39ac044..895fb67 100644 --- a/lib/features/devices/bloc/ceiling_bloc/ceiling_sensor_bloc.dart +++ b/lib/features/devices/bloc/ceiling_bloc/ceiling_sensor_bloc.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; @@ -42,28 +43,64 @@ class CeilingSensorBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + Timer? _timer; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { + _streamSubscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = CeilingSensorModel.fromJson(statusList); - add(CeilingSensorUpdated()); + if (!isClosed) { + add(CeilingSensorUpdated()); + } }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$deviceId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) { + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = CeilingSensorModel.fromJson(statusList); + // add(CeilingSensorUpdated()); + // }); + // } catch (_) {} + // } + _onCeilingSensorUpdated( CeilingSensorUpdated event, Emitter emit) { emit(UpdateState(ceilingSensorModel: deviceStatus)); diff --git a/lib/features/devices/bloc/curtain_bloc/curtain_bloc.dart b/lib/features/devices/bloc/curtain_bloc/curtain_bloc.dart index a5c5f49..dc56b4e 100644 --- a/lib/features/devices/bloc/curtain_bloc/curtain_bloc.dart +++ b/lib/features/devices/bloc/curtain_bloc/curtain_bloc.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:firebase_database/firebase_database.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart'; @@ -182,28 +184,61 @@ class CurtainBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + Timer? _timer; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$curtainId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { + _streamSubscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = CurtainModel.fromJson(statusList); - // add(CeilingSensorUpdated()); + if (!isClosed) {} }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$curtainId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) { + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = CurtainModel.fromJson(statusList); + // }); + // } catch (_) {} + // } + List groupList = []; bool allSwitchesOn = true; List devicesList = []; diff --git a/lib/features/devices/bloc/devices_cubit.dart b/lib/features/devices/bloc/devices_cubit.dart index 6006e1a..f8726ab 100644 --- a/lib/features/devices/bloc/devices_cubit.dart +++ b/lib/features/devices/bloc/devices_cubit.dart @@ -1,6 +1,9 @@ // ignore_for_file: constant_identifier_names, unused_import +import 'dart:async'; + import 'package:dio/dio.dart'; +import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart'; @@ -48,7 +51,6 @@ class DevicesCubit extends Cubit { return _instance ??= DevicesCubit._(); } - @override Future close() { _instance = null; @@ -62,6 +64,43 @@ class DevicesCubit extends Cubit { } } + Timer? _timer; + + final Map> _deviceSubscriptions = + {}; + + void _listenToChanges(deviceId) { + try { + if (_deviceSubscriptions.containsKey(deviceId)) { + _deviceSubscriptions[deviceId]?.cancel(); + _deviceSubscriptions.remove(deviceId); + } + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); + Stream stream = ref.onValue; + final subscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } + Map usersMap = + event.snapshot.value as Map; + print('object-----${usersMap['status']}'); + List statusList = []; + usersMap['status'].forEach((element) { + statusList + .add(StatusModel(code: element['code'], value: element['value'])); + }); + emitSafe(GetDevicesLoading()); + final deviceIndex = allDevices.indexWhere((d) => d.uuid == deviceId); + if (deviceIndex != -1) { + allDevices[deviceIndex].status = statusList; + } + emitSafe(GetDevicesSuccess(allDevices)); + }); + _deviceSubscriptions[deviceId] = subscription; + } catch (_) {} + } + static DevicesCubit get(context) => BlocProvider.of(context); List? allCategories; @@ -416,6 +455,10 @@ class DevicesCubit extends Cubit { spaceUuid: unit.id, ); allDevices = devices; + for (var deviceId in allDevices) { + + _listenToChanges(deviceId.uuid); + } emitSafe(GetDevicesSuccess(allDevices)); } catch (e) { emitSafe(GetDevicesError(e.toString())); diff --git a/lib/features/devices/bloc/door_sensor_bloc/door_sensor_bloc.dart b/lib/features/devices/bloc/door_sensor_bloc/door_sensor_bloc.dart index b88d477..f0ad998 100644 --- a/lib/features/devices/bloc/door_sensor_bloc/door_sensor_bloc.dart +++ b/lib/features/devices/bloc/door_sensor_bloc/door_sensor_bloc.dart @@ -25,9 +25,11 @@ class DoorSensorBloc extends Bloc { bool lowBattery = false; bool closingReminder = false; bool doorAlarm = false; - DoorSensorModel deviceStatus = DoorSensorModel(doorContactState: false, batteryPercentage: 0); + DoorSensorModel deviceStatus = + DoorSensorModel(doorContactState: false, batteryPercentage: 0); - void _fetchStatus(DoorSensorInitial event, Emitter emit) async { + void _fetchStatus( + DoorSensorInitial event, Emitter emit) async { emit(DoorSensorLoadingState()); try { var response = await DevicesAPI.getDeviceStatus(DSId); @@ -40,7 +42,7 @@ class DoorSensorBloc extends Bloc { ); emit(UpdateState(doorSensor: deviceStatus)); Future.delayed(const Duration(milliseconds: 500)); - _listenToChanges(); + _listenToChanges(); } catch (e) { emit(DoorSensorFailedState(errorMessage: e.toString())); return; @@ -48,7 +50,8 @@ class DoorSensorBloc extends Bloc { } // Toggle functions for each switch - void _toggleLowBattery(ToggleLowBatteryEvent event, Emitter emit) async { + void _toggleLowBattery( + ToggleLowBatteryEvent event, Emitter emit) async { emit(LoadingNewSate(doorSensor: deviceStatus)); try { lowBattery = event.isLowBatteryEnabled; @@ -89,7 +92,8 @@ class DoorSensorBloc extends Bloc { } } - void _toggleDoorAlarm(ToggleDoorAlarmEvent event, Emitter emit) async { + void _toggleDoorAlarm( + ToggleDoorAlarmEvent event, Emitter emit) async { emit(LoadingNewSate(doorSensor: deviceStatus)); try { doorAlarm = event.isDoorAlarmEnabled; @@ -108,9 +112,11 @@ class DoorSensorBloc extends Bloc { } } - DeviceReport recordGroups = DeviceReport(startTime: '0', endTime: '0', data: []); + DeviceReport recordGroups = + DeviceReport(startTime: '0', endTime: '0', data: []); - Future fetchLogsForLastMonth(ReportLogsInitial event, Emitter emit) async { + Future fetchLogsForLastMonth( + ReportLogsInitial event, Emitter emit) async { DateTime now = DateTime.now(); DateTime lastMonth = DateTime(now.year, now.month - 1, now.day); @@ -133,22 +139,52 @@ class DoorSensorBloc extends Bloc { } } - _listenToChanges() { + // _listenToChanges() { + // try { + // DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$DSId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: true)); + // }); + + // deviceStatus = DoorSensorModel.fromJson(statusList); + // if (!isClosed) { + // add( + // DoorSensorSwitch(switchD: deviceStatus.doorContactState), + // ); + // } + // }); + // } catch (_) {} + // } + + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$DSId'); + _streamSubscription?.cancel(); + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$DSId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } - Map usersMap = event.snapshot.value as Map; + Map usersMap = + event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: true)); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = DoorSensorModel.fromJson(statusList); if (!isClosed) { add( @@ -158,4 +194,11 @@ class DoorSensorBloc extends Bloc { }); } catch (_) {} } + + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } } diff --git a/lib/features/devices/bloc/garage_door_bloc/garage_door_bloc.dart b/lib/features/devices/bloc/garage_door_bloc/garage_door_bloc.dart index 3db0b7e..f6f6332 100644 --- a/lib/features/devices/bloc/garage_door_bloc/garage_door_bloc.dart +++ b/lib/features/devices/bloc/garage_door_bloc/garage_door_bloc.dart @@ -180,13 +180,16 @@ class GarageDoorBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$GDId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } @@ -194,19 +197,50 @@ class GarageDoorBloc extends Bloc { event.snapshot.value as Map; List statusList = []; usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: true)); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = GarageDoorModel.fromJson(statusList); - if (!isClosed) { - // add( - // DoorSensorSwitch(switchD: deviceStatus.doorContactState), - // ); - } + // if (!isClosed) { + // add(ToggleSelectedEvent()); + // } }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$GDId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: true)); + // }); + + // deviceStatus = GarageDoorModel.fromJson(statusList); + // if (!isClosed) { + // // add( + // // DoorSensorSwitch(switchD: deviceStatus.doorContactState), + // // ); + // } + // }); + // } catch (_) {} + // } + List> days = [ {"day": "Sun", "key": "Sun"}, {"day": "Mon", "key": "Mon"}, diff --git a/lib/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart b/lib/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart index 6a90042..50745cd 100644 --- a/lib/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart +++ b/lib/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart @@ -26,7 +26,8 @@ class OneGangBloc extends Bloc { bool oneGangGroup = false; List devicesList = []; - OneGangBloc({required this.oneGangId, required this.switchCode}) : super(InitialState()) { + OneGangBloc({required this.oneGangId, required this.switchCode}) + : super(InitialState()) { on(_fetchOneGangStatus); on(_oneGangUpdated); on(_changeFirstSwitch); @@ -49,7 +50,8 @@ class OneGangBloc extends Bloc { on(_groupAllOff); } - void _fetchOneGangStatus(InitialEvent event, Emitter emit) async { + void _fetchOneGangStatus( + InitialEvent event, Emitter emit) async { emit(LoadingInitialState()); try { var response = await DevicesAPI.getDeviceStatus(oneGangId); @@ -66,22 +68,51 @@ class OneGangBloc extends Bloc { } } - _listenToChanges() { + // _listenToChanges() { + // try { + // DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneGangId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = OneGangModel.fromJson(statusList); + // if (!isClosed) { + // add(OneGangUpdated()); + // } + // }); + // } catch (_) {} + // } + + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneGangId'); + _streamSubscription?.cancel(); + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$oneGangId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } - Map usersMap = event.snapshot.value as Map; + Map usersMap = + event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: element['value'])); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - + print('=========${usersMap['status']}'); deviceStatus = OneGangModel.fromJson(statusList); if (!isClosed) { add(OneGangUpdated()); @@ -90,11 +121,19 @@ class OneGangBloc extends Bloc { } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + _oneGangUpdated(OneGangUpdated event, Emitter emit) { emit(UpdateState(oneGangModel: deviceStatus)); } - void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter emit) async { + void _changeFirstSwitch( + ChangeFirstSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(oneGangModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.value; @@ -119,17 +158,20 @@ class OneGangBloc extends Bloc { } } - void _changeSliding(ChangeSlidingSegment event, Emitter emit) async { + void _changeSliding( + ChangeSlidingSegment event, Emitter emit) async { emit(ChangeSlidingSegmentState(value: event.value)); } - void _setCounterValue(SetCounterValue event, Emitter emit) async { + void _setCounterValue( + SetCounterValue event, Emitter emit) async { emit(LoadingNewSate(oneGangModel: deviceStatus)); int seconds = 0; try { seconds = event.duration.inSeconds; final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: oneGangId, code: event.deviceCode, value: seconds), + DeviceControlModel( + deviceId: oneGangId, code: event.deviceCode, value: seconds), oneGangId); if (response['success'] ?? false) { @@ -152,7 +194,8 @@ class OneGangBloc extends Bloc { } } - void _getCounterValue(GetCounterEvent event, Emitter emit) async { + void _getCounterValue( + GetCounterEvent event, Emitter emit) async { emit(LoadingInitialState()); try { var response = await DevicesAPI.getDeviceStatus(oneGangId); @@ -241,7 +284,8 @@ class OneGangBloc extends Bloc { deviceId: oneGangId, ); List jsonData = response; - listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList(); + listSchedule = + jsonData.map((item) => ScheduleModel.fromJson(item)).toList(); emit(InitialState()); } on DioException catch (e) { final errorData = e.response!.data; @@ -252,12 +296,13 @@ class OneGangBloc extends Bloc { int? getTimeStampWithoutSeconds(DateTime? dateTime) { if (dateTime == null) return null; - DateTime dateTimeWithoutSeconds = - DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute); + DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, + dateTime.day, dateTime.hour, dateTime.minute); return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; } - Future toggleChange(ToggleScheduleEvent event, Emitter emit) async { + Future toggleChange( + ToggleScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.changeSchedule( @@ -276,7 +321,8 @@ class OneGangBloc extends Bloc { } } - Future deleteSchedule(DeleteScheduleEvent event, Emitter emit) async { + Future deleteSchedule( + DeleteScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.deleteSchedule( @@ -296,7 +342,8 @@ class OneGangBloc extends Bloc { } } - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { + void toggleCreateSchedule( + ToggleCreateScheduleEvent event, Emitter emit) { emit(LoadingInitialState()); createSchedule = !createSchedule; selectedDays.clear(); @@ -325,7 +372,8 @@ class OneGangBloc extends Bloc { int selectedTabIndex = 0; - void toggleSelectedIndex(ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex( + ToggleSelectedEvent event, Emitter emit) { emit(LoadingInitialState()); selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); @@ -334,7 +382,8 @@ class OneGangBloc extends Bloc { List groupOneGangList = []; bool allSwitchesOn = true; - void _fetchOneGangWizardStatus(InitialWizardEvent event, Emitter emit) async { + void _fetchOneGangWizardStatus( + InitialWizardEvent event, Emitter emit) async { emit(LoadingInitialState()); try { devicesList = []; @@ -344,7 +393,8 @@ class OneGangBloc extends Bloc { HomeCubit.getInstance().selectedSpace?.id ?? '', '1G'); for (int i = 0; i < devicesList.length; i++) { - var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); + var response = + await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); List statusModelList = []; for (var status in response['status']) { statusModelList.add(StatusModel.fromJson(status)); @@ -365,15 +415,16 @@ class OneGangBloc extends Bloc { return true; }); } - emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: allSwitchesOn)); + emit(UpdateGroupState( + oneGangList: groupOneGangList, allSwitches: allSwitchesOn)); } catch (e) { emit(FailedState(error: e.toString())); return; } } - void _changeFirstWizardSwitch( - ChangeFirstWizardSwitchStatusEvent event, Emitter emit) async { + void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, + Emitter emit) async { emit(LoadingNewSate(oneGangModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -386,7 +437,8 @@ class OneGangBloc extends Bloc { } }); - emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: allSwitchesValue)); + emit(UpdateGroupState( + oneGangList: groupOneGangList, allSwitches: allSwitchesValue)); final response = await DevicesAPI.deviceBatchController( code: 'switch_1', @@ -414,7 +466,8 @@ class OneGangBloc extends Bloc { emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: true)); // Get a list of all device IDs - List allDeviceIds = groupOneGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupOneGangList.map((device) => device.deviceId).toList(); // First call for switch_1 final response = await DevicesAPI.deviceBatchController( @@ -446,7 +499,8 @@ class OneGangBloc extends Bloc { emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: false)); // Get a list of all device IDs - List allDeviceIds = groupOneGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupOneGangList.map((device) => device.deviceId).toList(); // First call for switch_1 final response = await DevicesAPI.deviceBatchController( diff --git a/lib/features/devices/bloc/smart_door_bloc/smart_door_bloc.dart b/lib/features/devices/bloc/smart_door_bloc/smart_door_bloc.dart index ffd8760..cc4a1d9 100644 --- a/lib/features/devices/bloc/smart_door_bloc/smart_door_bloc.dart +++ b/lib/features/devices/bloc/smart_door_bloc/smart_door_bloc.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:math'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; @@ -37,7 +38,8 @@ class SmartDoorBloc extends Bloc { on(selectTimeOfLinePassword); on(selectTimeOnlinePassword); on(deletePassword); - on(generateAndSavePasswordTimeLimited); + on( + generateAndSavePasswordTimeLimited); on(generateAndSavePasswordOneTime); on(toggleDaySelection); on(_renamePassword); @@ -59,7 +61,8 @@ class SmartDoorBloc extends Bloc { List? oneTimePasswords = []; List? timeLimitPasswords = []; - Future generate7DigitNumber(GeneratePasswordEvent event, Emitter emit) async { + Future generate7DigitNumber( + GeneratePasswordEvent event, Emitter emit) async { emit(LoadingInitialState()); passwordController.clear(); Random random = Random(); @@ -71,7 +74,8 @@ class SmartDoorBloc extends Bloc { } Future generateAndSavePasswordOneTime( - GenerateAndSavePasswordOneTimeEvent event, Emitter emit) async { + GenerateAndSavePasswordOneTimeEvent event, + Emitter emit) async { try { if (isSavingPassword) return; isSavingPassword = true; @@ -92,7 +96,8 @@ class SmartDoorBloc extends Bloc { } } - void _fetchSmartDoorStatus(InitialEvent event, Emitter emit) async { + void _fetchSmartDoorStatus( + InitialEvent event, Emitter emit) async { try { emit(LoadingInitialState()); var response = await DevicesAPI.getDeviceStatus(deviceId); @@ -102,42 +107,80 @@ class SmartDoorBloc extends Bloc { } deviceStatus = SmartDoorModel.fromJson(statusModelList); emit(UpdateState(smartDoorModel: deviceStatus)); - _listenToChanges(); + _listenToChanges(); } catch (e) { emit(FailedState(errorMessage: e.toString())); return; } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + Timer? _timer; + + void _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + _streamSubscription?.cancel(); + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$deviceId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { - Map usersMap = event.snapshot.value as Map; + _streamSubscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } + Map usersMap = + event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: element['value'])); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = SmartDoorModel.fromJson(statusList); - add(DoorLockUpdated()); + if (!isClosed) { + add(DoorLockUpdated()); + } }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + // _listenToChanges() { + // try { + // DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) { + // Map usersMap = event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = SmartDoorModel.fromJson(statusList); + // add(DoorLockUpdated()); + // }); + // } catch (_) {} + // } + _doorLockUpdated(DoorLockUpdated event, Emitter emit) { unlockRequest = deviceStatus.unlockRequest; emit(UpdateState(smartDoorModel: deviceStatus)); } - void _renamePassword(RenamePasswordEvent event, Emitter emit) async { + void _renamePassword( + RenamePasswordEvent event, Emitter emit) async { try { emit(LoadingInitialState()); await DevicesAPI.renamePass( - name: passwordNameController.text, doorLockUuid: deviceId, passwordId: passwordId); + name: passwordNameController.text, + doorLockUuid: deviceId, + passwordId: passwordId); add(InitialOneTimePassword()); add(InitialTimeLimitPassword()); emit(UpdateState(smartDoorModel: deviceStatus)); @@ -147,46 +190,58 @@ class SmartDoorBloc extends Bloc { } } - void getTemporaryPasswords(InitialPasswordsPage event, Emitter emit) async { + void getTemporaryPasswords( + InitialPasswordsPage event, Emitter emit) async { try { emit(LoadingInitialState()); var response = await DevicesAPI.getTemporaryPasswords( deviceId, ); if (response is List) { - temporaryPasswords = response.map((item) => TemporaryPassword.fromJson(item)).toList(); - } else if (response is Map && response.containsKey('data')) { temporaryPasswords = - (response['data'] as List).map((item) => TemporaryPassword.fromJson(item)).toList(); + response.map((item) => TemporaryPassword.fromJson(item)).toList(); + } else if (response is Map && response.containsKey('data')) { + temporaryPasswords = (response['data'] as List) + .map((item) => TemporaryPassword.fromJson(item)) + .toList(); } - emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!)); + emit(TemporaryPasswordsLoadedState( + temporaryPassword: temporaryPasswords!)); } catch (e) { emit(FailedState(errorMessage: e.toString())); } } - void getOneTimePasswords(InitialOneTimePassword event, Emitter emit) async { + void getOneTimePasswords( + InitialOneTimePassword event, Emitter emit) async { try { emit(LoadingInitialState()); var response = await DevicesAPI.getOneTimePasswords(deviceId); if (response is List) { - oneTimePasswords = response.map((item) => OfflinePasswordModel.fromJson(item)).toList(); + oneTimePasswords = response + .map((item) => OfflinePasswordModel.fromJson(item)) + .toList(); } - emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!)); + emit(TemporaryPasswordsLoadedState( + temporaryPassword: temporaryPasswords!)); } catch (e) { emit(FailedState(errorMessage: e.toString())); } } - void getTimeLimitPasswords(InitialTimeLimitPassword event, Emitter emit) async { + void getTimeLimitPasswords( + InitialTimeLimitPassword event, Emitter emit) async { try { emit(LoadingInitialState()); var response = await DevicesAPI.getTimeLimitPasswords(deviceId); if (response is List) { - timeLimitPasswords = response.map((item) => OfflinePasswordModel.fromJson(item)).toList(); + timeLimitPasswords = response + .map((item) => OfflinePasswordModel.fromJson(item)) + .toList(); } - emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!)); + emit(TemporaryPasswordsLoadedState( + temporaryPassword: temporaryPasswords!)); } catch (e) { emit(FailedState(errorMessage: e.toString())); } @@ -207,7 +262,8 @@ class SmartDoorBloc extends Bloc { return repeat; } - bool setStartEndTime(SetStartEndTimeEvent event, Emitter emit) { + bool setStartEndTime( + SetStartEndTimeEvent event, Emitter emit) { emit(LoadingInitialState()); isStartEndTime = event.val; emit(IsStartEndState(isStartEndTime: isStartEndTime)); @@ -230,7 +286,8 @@ class SmartDoorBloc extends Bloc { emit(UpdateState(smartDoorModel: deviceStatus)); } - Future selectTimeOfLinePassword(SelectTimeEvent event, Emitter emit) async { + Future selectTimeOfLinePassword( + SelectTimeEvent event, Emitter emit) async { emit(ChangeTimeState()); final DateTime? picked = await showDatePicker( context: event.context, @@ -260,20 +317,27 @@ class SmartDoorBloc extends Bloc { ).millisecondsSinceEpoch ~/ 1000; // Divide by 1000 to remove milliseconds if (event.isEffective) { - if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) { - CustomSnackBar.displaySnackBar('Effective Time cannot be later than Expiration Time.'); + if (expirationTimeTimeStamp != null && + selectedTimestamp > expirationTimeTimeStamp!) { + CustomSnackBar.displaySnackBar( + 'Effective Time cannot be later than Expiration Time.'); } else { - effectiveTime = - selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds + effectiveTime = selectedDateTime + .toString() + .split('.') + .first; // Remove seconds and milliseconds effectiveTimeTimeStamp = selectedTimestamp; } } else { - if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) { + if (effectiveTimeTimeStamp != null && + selectedTimestamp < effectiveTimeTimeStamp!) { CustomSnackBar.displaySnackBar( 'Expiration Time cannot be earlier than Effective Time.'); } else { - expirationTime = - selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds + expirationTime = selectedDateTime + .toString() + .split('.') + .first; // Remove seconds and milliseconds expirationTimeTimeStamp = selectedTimestamp; } } @@ -329,20 +393,27 @@ class SmartDoorBloc extends Bloc { ).millisecondsSinceEpoch ~/ 1000; // Divide by 1000 to remove milliseconds if (event.isEffective) { - if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) { - CustomSnackBar.displaySnackBar('Effective Time cannot be later than Expiration Time.'); + if (expirationTimeTimeStamp != null && + selectedTimestamp > expirationTimeTimeStamp!) { + CustomSnackBar.displaySnackBar( + 'Effective Time cannot be later than Expiration Time.'); } else { - effectiveTime = - selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds + effectiveTime = selectedDateTime + .toString() + .split('.') + .first; // Remove seconds and milliseconds effectiveTimeTimeStamp = selectedTimestamp; } } else { - if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) { + if (effectiveTimeTimeStamp != null && + selectedTimestamp < effectiveTimeTimeStamp!) { CustomSnackBar.displaySnackBar( 'Expiration Time cannot be earlier than Effective Time.'); } else { - expirationTime = - selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds + expirationTime = selectedDateTime + .toString() + .split('.') + .first; // Remove seconds and milliseconds expirationTimeTimeStamp = selectedTimestamp; } } @@ -351,7 +422,8 @@ class SmartDoorBloc extends Bloc { } } - Future savePassword(SavePasswordEvent event, Emitter emit) async { + Future savePassword( + SavePasswordEvent event, Emitter emit) async { if (_validateInputs() || isSavingPassword) return; try { isSavingPassword = true; @@ -381,7 +453,8 @@ class SmartDoorBloc extends Bloc { } Future generateAndSavePasswordTimeLimited( - GenerateAndSavePasswordTimeLimitEvent event, Emitter emit) async { + GenerateAndSavePasswordTimeLimitEvent event, + Emitter emit) async { if (timeLimitValidate() || isSavingPassword) return; try { isSavingPassword = true; @@ -407,10 +480,12 @@ class SmartDoorBloc extends Bloc { } } - Future deletePassword(DeletePasswordEvent event, Emitter emit) async { + Future deletePassword( + DeletePasswordEvent event, Emitter emit) async { try { emit(LoadingInitialState()); - await DevicesAPI.deletePassword(deviceId: deviceId, passwordId: event.passwordId) + await DevicesAPI.deletePassword( + deviceId: deviceId, passwordId: event.passwordId) .then((value) async { add(InitialPasswordsPage()); }); @@ -445,7 +520,8 @@ class SmartDoorBloc extends Bloc { } if (repeat == true && (endTime == null || startTime == null)) { - CustomSnackBar.displaySnackBar('Start Time and End time and the days required '); + CustomSnackBar.displaySnackBar( + 'Start Time and End time and the days required '); return true; } return false; diff --git a/lib/features/devices/bloc/sos_bloc/sos_bloc.dart b/lib/features/devices/bloc/sos_bloc/sos_bloc.dart index 44008bd..e4d73e0 100644 --- a/lib/features/devices/bloc/sos_bloc/sos_bloc.dart +++ b/lib/features/devices/bloc/sos_bloc/sos_bloc.dart @@ -422,25 +422,58 @@ class SosBloc extends Bloc { } } - _listenToChanges() { + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$sosId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) { + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = SosModel.fromJson(statusList); + // // add(DoorLockUpdated()); + // }); + // } catch (_) {} + // } + + StreamSubscription? _streamSubscription; + Timer? _timer; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$sosId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { + _streamSubscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = SosModel.fromJson(statusList); - // add(DoorLockUpdated()); }); } catch (_) {} } + + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } } diff --git a/lib/features/devices/bloc/three_gang_bloc/three_gang_bloc.dart b/lib/features/devices/bloc/three_gang_bloc/three_gang_bloc.dart index 3311ef2..0eb7757 100644 --- a/lib/features/devices/bloc/three_gang_bloc/three_gang_bloc.dart +++ b/lib/features/devices/bloc/three_gang_bloc/three_gang_bloc.dart @@ -115,13 +115,43 @@ class ThreeGangBloc extends Bloc { } } - _listenToChanges() { + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$threeGangId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + // print('=========${usersMap['status']}'); + + // deviceStatus = ThreeGangModel.fromJson(statusList); + // if (!isClosed) { + // add(ThreeGangUpdated()); + // } + // }); + // } catch (_) {} + // } + + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$threeGangId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } @@ -142,6 +172,13 @@ class ThreeGangBloc extends Bloc { } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + _threeGangUpdated(ThreeGangUpdated event, Emitter emit) { emit(UpdateState(threeGangModel: deviceStatus)); } diff --git a/lib/features/devices/bloc/two_touch_bloc/two_touch_bloc.dart b/lib/features/devices/bloc/two_touch_bloc/two_touch_bloc.dart index a429b7a..96c882d 100644 --- a/lib/features/devices/bloc/two_touch_bloc/two_touch_bloc.dart +++ b/lib/features/devices/bloc/two_touch_bloc/two_touch_bloc.dart @@ -106,25 +106,27 @@ class TwoTouchBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$twoTouchId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - + print('=========${usersMap['status']}'); deviceStatus = TwoTouchModel.fromJson(statusList); if (!isClosed) { add(TwoTouchUpdated()); @@ -133,6 +135,39 @@ class TwoTouchBloc extends Bloc { } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$twoTouchId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = TwoTouchModel.fromJson(statusList); + // if (!isClosed) { + // add(TwoTouchUpdated()); + // } + // }); + // } catch (_) {} + // } + _twoTouchUpdated(TwoTouchUpdated event, Emitter emit) { emit(UpdateState(twoTouchModel: deviceStatus)); } diff --git a/lib/features/devices/bloc/wall_sensor_bloc/wall_sensor_bloc.dart b/lib/features/devices/bloc/wall_sensor_bloc/wall_sensor_bloc.dart index dfda751..2aff727 100644 --- a/lib/features/devices/bloc/wall_sensor_bloc/wall_sensor_bloc.dart +++ b/lib/features/devices/bloc/wall_sensor_bloc/wall_sensor_bloc.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:firebase_database/firebase_database.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_app/features/devices/bloc/wall_sensor_bloc/wall_sensor_state.dart'; @@ -39,28 +41,63 @@ class WallSensorBloc extends Bloc { } } - _listenToChanges() { + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$deviceId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) { + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList + // .add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = WallSensorModel.fromJson(statusList); + // add(WallSensorUpdatedEvent()); + // }); + // } catch (_) {} + // } + Timer? _timer; + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) { + _streamSubscription = stream.listen((DatabaseEvent event) async { + if (_timer != null) { + await Future.delayed(const Duration(seconds: 2)); + } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { statusList .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = WallSensorModel.fromJson(statusList); - add(WallSensorUpdatedEvent()); + if (!isClosed) { + add(WallSensorUpdatedEvent()); + } }); } catch (_) {} } + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + _wallSensorUpdated( WallSensorUpdatedEvent event, Emitter emit) { emit(UpdateState(wallSensorModel: deviceStatus)); diff --git a/lib/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart b/lib/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart index 0df2228..86b6bcd 100644 --- a/lib/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart +++ b/lib/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart @@ -35,7 +35,8 @@ class WaterHeaterBloc extends Bloc { List listSchedule = []; DateTime? selectedTime = DateTime.now(); - WaterHeaterBloc({required this.whId, required this.switchCode}) : super(WHInitialState()) { + WaterHeaterBloc({required this.whId, required this.switchCode}) + : super(WHInitialState()) { on(_fetchWaterHeaterStatus); on(_changeFirstSwitch); on(_setCounterValue); @@ -60,7 +61,8 @@ class WaterHeaterBloc extends Bloc { on(_waterHeaterUpdated); } - void _fetchWaterHeaterStatus(WaterHeaterInitial event, Emitter emit) async { + void _fetchWaterHeaterStatus( + WaterHeaterInitial event, Emitter emit) async { emit(WHLoadingState()); try { var response = await DevicesAPI.getDeviceStatus(whId); @@ -79,22 +81,26 @@ class WaterHeaterBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$whId'); + _streamSubscription?.cancel(); + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$whId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } - Map usersMap = event.snapshot.value as Map; + Map usersMap = + event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: element['value'])); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = WHModel.fromJson(statusList); if (!isClosed) { add(WaterHeaterUpdated()); @@ -103,12 +109,45 @@ class WaterHeaterBloc extends Bloc { } catch (_) {} } - _waterHeaterUpdated(WaterHeaterUpdated event, Emitter emit) async { + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + + // _listenToChanges() { + // try { + // DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$whId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: element['value'])); + // }); + + // deviceStatus = WHModel.fromJson(statusList); + // if (!isClosed) { + // add(WaterHeaterUpdated()); + // } + // }); + // } catch (_) {} + // } + + _waterHeaterUpdated( + WaterHeaterUpdated event, Emitter emit) async { emit(WHLoadingState()); emit(UpdateState(whModel: deviceStatus)); } - void _changeFirstSwitch(WaterHeaterSwitch event, Emitter emit) async { + void _changeFirstSwitch( + WaterHeaterSwitch event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.whSwitch; @@ -118,7 +157,10 @@ class WaterHeaterBloc extends Bloc { } _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: whId, code: 'switch_1', value: deviceStatus.firstSwitch), + DeviceControlModel( + deviceId: whId, + code: 'switch_1', + value: deviceStatus.firstSwitch), whId); if (!response['success']) { @@ -132,13 +174,16 @@ class WaterHeaterBloc extends Bloc { //=====================---------- timer ---------------------------------------- - void _setCounterValue(SetCounterValue event, Emitter emit) async { + void _setCounterValue( + SetCounterValue event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); int seconds = 0; try { seconds = event.duration.inSeconds; final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: whId, code: event.deviceCode, value: seconds), whId); + DeviceControlModel( + deviceId: whId, code: event.deviceCode, value: seconds), + whId); if (response['success'] ?? false) { if (event.deviceCode == 'countdown_1') { @@ -160,7 +205,8 @@ class WaterHeaterBloc extends Bloc { } } - void _getCounterValue(GetCounterEvent event, Emitter emit) async { + void _getCounterValue( + GetCounterEvent event, Emitter emit) async { emit(WHLoadingState()); try { var response = await DevicesAPI.getDeviceStatus(whId); @@ -250,7 +296,8 @@ class WaterHeaterBloc extends Bloc { deviceId: whId, ); List jsonData = response; - listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList(); + listSchedule = + jsonData.map((item) => ScheduleModel.fromJson(item)).toList(); emit(WHInitialState()); } on DioException catch (e) { final errorData = e.response!.data; @@ -261,12 +308,13 @@ class WaterHeaterBloc extends Bloc { int? getTimeStampWithoutSeconds(DateTime? dateTime) { if (dateTime == null) return null; - DateTime dateTimeWithoutSeconds = - DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute); + DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, + dateTime.day, dateTime.hour, dateTime.minute); return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; } - Future toggleChange(ToggleScheduleEvent event, Emitter emit) async { + Future toggleChange( + ToggleScheduleEvent event, Emitter emit) async { try { emit(WHLoadingState()); final response = await DevicesAPI.changeSchedule( @@ -284,7 +332,8 @@ class WaterHeaterBloc extends Bloc { } } - Future deleteSchedule(DeleteScheduleEvent event, Emitter emit) async { + Future deleteSchedule( + DeleteScheduleEvent event, Emitter emit) async { try { emit(WHLoadingState()); final response = await DevicesAPI.deleteSchedule( @@ -303,7 +352,8 @@ class WaterHeaterBloc extends Bloc { } } - void _toggleCreateCirculate(ToggleCreateCirculate event, Emitter emit) { + void _toggleCreateCirculate( + ToggleCreateCirculate event, Emitter emit) { emit(WHLoadingState()); createCirculate = !createCirculate; selectedDays.clear(); @@ -311,13 +361,15 @@ class WaterHeaterBloc extends Bloc { emit(UpdateCreateScheduleState(createCirculate)); } - void toggleSelectedIndex(ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex( + ToggleSelectedEvent event, Emitter emit) { emit(WHLoadingState()); selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); } - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { + void toggleCreateSchedule( + ToggleCreateScheduleEvent event, Emitter emit) { emit(WHLoadingState()); createSchedule = !createSchedule; selectedDays.clear(); @@ -366,8 +418,8 @@ class WaterHeaterBloc extends Bloc { List groupWaterHeaterList = []; bool allSwitchesOn = true; - void _changeFirstWizardSwitch( - ChangeFirstWizardSwitchStatusEvent event, Emitter emit) async { + void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, + Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -379,7 +431,8 @@ class WaterHeaterBloc extends Bloc { allSwitchesValue = false; } }); - emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: allSwitchesValue)); + emit(UpdateGroupState( + twoGangList: groupWaterHeaterList, allSwitches: allSwitchesValue)); final response = await DevicesAPI.deviceBatchController( code: 'switch_1', @@ -394,7 +447,8 @@ class WaterHeaterBloc extends Bloc { } } - void _fetchWHWizardStatus(InitialWizardEvent event, Emitter emit) async { + void _fetchWHWizardStatus( + InitialWizardEvent event, Emitter emit) async { emit(WHLoadingState()); try { devicesList = []; @@ -404,7 +458,8 @@ class WaterHeaterBloc extends Bloc { HomeCubit.getInstance().selectedSpace?.id ?? '', 'WH'); for (int i = 0; i < devicesList.length; i++) { - var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); + var response = + await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); List statusModelList = []; for (var status in response['status']) { statusModelList.add(StatusModel.fromJson(status)); @@ -426,23 +481,27 @@ class WaterHeaterBloc extends Bloc { return true; }); } - emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: allSwitchesOn)); + emit(UpdateGroupState( + twoGangList: groupWaterHeaterList, allSwitches: allSwitchesOn)); } catch (e) { // emit(FailedState(error: e.toString())); return; } } - void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { + void _groupAllOn( + GroupAllOnEvent event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { for (int i = 0; i < groupWaterHeaterList.length; i++) { groupWaterHeaterList[i].firstSwitch = true; } - emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: true)); + emit(UpdateGroupState( + twoGangList: groupWaterHeaterList, allSwitches: true)); - List allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupWaterHeaterList.map((device) => device.deviceId).toList(); final response = await DevicesAPI.deviceBatchController( code: 'switch_1', @@ -460,15 +519,18 @@ class WaterHeaterBloc extends Bloc { } } - void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { + void _groupAllOff( + GroupAllOffEvent event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { for (int i = 0; i < groupWaterHeaterList.length; i++) { groupWaterHeaterList[i].firstSwitch = false; } - emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: false)); + emit(UpdateGroupState( + twoGangList: groupWaterHeaterList, allSwitches: false)); - List allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupWaterHeaterList.map((device) => device.deviceId).toList(); final response = await DevicesAPI.deviceBatchController( code: 'switch_1', diff --git a/lib/features/devices/bloc/water_leak_bloc/water_leak_bloc.dart b/lib/features/devices/bloc/water_leak_bloc/water_leak_bloc.dart index 265adda..58b1445 100644 --- a/lib/features/devices/bloc/water_leak_bloc/water_leak_bloc.dart +++ b/lib/features/devices/bloc/water_leak_bloc/water_leak_bloc.dart @@ -43,7 +43,7 @@ class WaterLeakBloc extends Bloc { emit(UpdateState(waterSensor: deviceStatus)); Future.delayed(const Duration(milliseconds: 500)); - _listenToChanges(); + _listenToChanges(); } catch (e) { emit(WaterLeakFailedState(errorMessage: e.toString())); return; @@ -135,24 +135,26 @@ class WaterLeakBloc extends Bloc { } } - _listenToChanges() { + StreamSubscription? _streamSubscription; + + void _listenToChanges() { try { + _streamSubscription?.cancel(); DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$WLId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + _streamSubscription = stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } Map usersMap = event.snapshot.value as Map; List statusList = []; - usersMap['status'].forEach((element) { - statusList.add(StatusModel(code: element['code'], value: true)); + statusList + .add(StatusModel(code: element['code'], value: element['value'])); }); - deviceStatus = WaterLeakModel.fromJson(statusList); if (!isClosed) { add( @@ -162,4 +164,39 @@ class WaterLeakBloc extends Bloc { }); } catch (_) {} } + + @override + Future close() async { + _streamSubscription?.cancel(); + _streamSubscription = null; + return super.close(); + } + + // _listenToChanges() { + // try { + // DatabaseReference ref = + // FirebaseDatabase.instance.ref('device-status/$WLId'); + // Stream stream = ref.onValue; + + // stream.listen((DatabaseEvent event) async { + // if (_timer != null) { + // await Future.delayed(const Duration(seconds: 2)); + // } + // Map usersMap = + // event.snapshot.value as Map; + // List statusList = []; + + // usersMap['status'].forEach((element) { + // statusList.add(StatusModel(code: element['code'], value: true)); + // }); + + // deviceStatus = WaterLeakModel.fromJson(statusList); + // if (!isClosed) { + // add( + // WaterLeakSwitch(switchD: deviceStatus.waterContactState), + // ); + // } + // }); + // } catch (_) {} + // } } diff --git a/lib/features/devices/view/widgets/ACs/acs_view.dart b/lib/features/devices/view/widgets/ACs/acs_view.dart index 5bde723..8c67f26 100644 --- a/lib/features/devices/view/widgets/ACs/acs_view.dart +++ b/lib/features/devices/view/widgets/ACs/acs_view.dart @@ -23,9 +23,8 @@ class ACsView extends StatelessWidget { @override Widget build(BuildContext context) { - print("ACsView deviceModel UUID: ${deviceModel?.uuid}"); - return BlocProvider( + create: (context) => ACsBloc(acId: deviceModel?.uuid ?? '') ..add(AcsInitial(allAcs: deviceModel != null ? false : true)), child: BlocBuilder( diff --git a/lib/features/devices/view/widgets/room_page_switch.dart b/lib/features/devices/view/widgets/room_page_switch.dart index 2893b63..5d9488c 100644 --- a/lib/features/devices/view/widgets/room_page_switch.dart +++ b/lib/features/devices/view/widgets/room_page_switch.dart @@ -119,6 +119,8 @@ Future showDeviceInterface( required BuildContext context, required isAllDevices, List? allDevices}) async { + print('object-----${device.uuid} ${device.name}'); + final devicesCubit = context.read(); switch (device.productType) {