From 4e345db8423c5eccd8aadfdf36b7f5b9ca70ccee Mon Sep 17 00:00:00 2001 From: mohammad Date: Thu, 26 Sep 2024 16:26:39 +0300 Subject: [PATCH 1/7] one gang wizard &two Gang wizard & wh wizard --- .../bloc/one_gang_bloc/one_gang_bloc.dart | 230 +++++++++++++-- .../bloc/one_gang_bloc/one_gang_event.dart | 27 +- .../bloc/three_gang_bloc/three_gang_bloc.dart | 85 +++++- .../three_gang_bloc/three_gang_event.dart | 4 +- .../bloc/two_gang_bloc/two_gang_bloc.dart | 275 ++++++++++++++--- .../bloc/two_gang_bloc/two_gang_event.dart | 41 ++- .../water_heater_bloc/water_heater_bloc.dart | 278 ++++++++++++++---- .../water_heater_bloc/water_heater_event.dart | 18 ++ .../water_heater_bloc/water_heater_state.dart | 16 +- lib/features/devices/model/GroupWHModel.dart | 11 + .../view/widgets/one_gang/one_gang_list.dart | 10 +- .../widgets/one_gang/one_gang_wizard.dart | 58 ++++ .../widgets/three_gang/three_gang_screen.dart | 8 +- .../widgets/three_gang/three_gang_wizard.dart | 61 ++++ .../view/widgets/two_gang/two_gang_list.dart | 17 +- .../widgets/two_gang/two_gang_wizard.dart | 61 ++++ .../view/widgets/water_heater/wh_list.dart | 69 +++++ .../view/widgets/water_heater/wh_wizard.dart | 60 ++++ .../devices/view/widgets/wizard_page.dart | 22 +- lib/services/api/api_links_endpoints.dart | 4 +- lib/services/api/devices_api.dart | 25 ++ 21 files changed, 1210 insertions(+), 170 deletions(-) create mode 100644 lib/features/devices/model/GroupWHModel.dart create mode 100644 lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart create mode 100644 lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart create mode 100644 lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart create mode 100644 lib/features/devices/view/widgets/water_heater/wh_list.dart create mode 100644 lib/features/devices/view/widgets/water_heater/wh_wizard.dart 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 db30079..12baacd 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 @@ -2,9 +2,11 @@ import 'dart:async'; import 'package:dio/dio.dart'; 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'; import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_control_model.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; +import 'package:syncrow_app/features/devices/model/group_one_gang_model.dart'; import 'package:syncrow_app/features/devices/model/one_gang_model.dart'; import 'package:syncrow_app/features/devices/model/schedule_model.dart'; import 'package:syncrow_app/features/devices/model/status_model.dart'; @@ -24,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); @@ -41,9 +44,14 @@ class OneGangBloc extends Bloc { on(deleteSchedule); on(toggleSelectedIndex); on(toggleCreateSchedule); + on(_fetchOneGangWizardStatus); + on(_changeFirstWizardSwitch); + on(_groupAllOn); + 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); @@ -62,18 +70,21 @@ class OneGangBloc extends Bloc { _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneGangId'); + 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; + 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 = OneGangModel.fromJson(statusList); @@ -88,7 +99,8 @@ class OneGangBloc extends Bloc { 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; @@ -113,17 +125,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) { @@ -146,7 +161,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); @@ -215,7 +231,7 @@ class OneGangBloc extends Bloc { add(GetScheduleEvent()); emit(SaveSchedule()); - add(const ToggleCreateScheduleEvent(index:1 )); + add(const ToggleCreateScheduleEvent(index: 1)); } else { CustomSnackBar.displaySnackBar('Please select days'); } @@ -235,7 +251,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; @@ -246,12 +263,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( @@ -270,7 +288,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( @@ -299,14 +318,14 @@ class OneGangBloc extends Bloc { // emit(ChangeSlidingSegmentState(value: 1)); // } - - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { - emit(LoadingInitialState()); - createSchedule = !createSchedule; - selectedDays.clear(); - selectedTime = DateTime.now(); - emit(UpdateCreateScheduleState(createSchedule)); -} + void toggleCreateSchedule( + ToggleCreateScheduleEvent event, Emitter emit) { + emit(LoadingInitialState()); + createSchedule = !createSchedule; + selectedDays.clear(); + selectedTime = DateTime.now(); + emit(UpdateCreateScheduleState(createSchedule)); + } bool toggleSchedule = true; List selectedDays = []; @@ -329,9 +348,168 @@ class OneGangBloc extends Bloc { int selectedTabIndex = 0; - void toggleSelectedIndex( ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex( + ToggleSelectedEvent event, Emitter emit) { emit(LoadingInitialState()); - selectedTabIndex =event.index; + selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); } + + List groupOneGangList = []; + bool allSwitchesOn = true; + + void _fetchOneGangWizardStatus( + InitialWizardEvent event, Emitter emit) async { + emit(LoadingInitialState()); + try { + devicesList = []; + groupOneGangList = []; + allSwitchesOn = true; + devicesList = await DevicesAPI.getDeviceByGroupName( + HomeCubit.getInstance().selectedSpace?.id ?? '', '1G'); + + for (int i = 0; i < devicesList.length; i++) { + var response = + await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); + List statusModelList = []; + for (var status in response['status']) { + statusModelList.add(StatusModel.fromJson(status)); + } + // deviceStatus = TwoGangModel.fromJson(statusModelList); + deviceStatus = OneGangModel.fromJson(statusModelList); + groupOneGangList.add(GroupOneGangModel( + deviceId: devicesList[i].uuid ?? '', + deviceName: devicesList[i].name ?? '', + firstSwitch: deviceStatus.firstSwitch, + )); + } + + if (groupOneGangList.isNotEmpty) { + groupOneGangList.firstWhere((element) { + if (!element.firstSwitch) { + allSwitchesOn = false; + } + return true; + }); + } + emit(UpdateGroupState( + oneGangList: groupOneGangList, allSwitches: allSwitchesOn)); + } catch (e) { + emit(FailedState(error: e.toString())); + return; + } + } + + void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, + Emitter emit) async { + emit(LoadingNewSate(oneGangModel: deviceStatus)); + try { + bool allSwitchesValue = true; + groupOneGangList.forEach((element) { + if (element.deviceId == event.deviceId) { + element.firstSwitch = !event.value; + } + if (!element.firstSwitch) { + allSwitchesValue = false; + } + }); + // List allDeviceIds = + // groupOneGangList.map((device) => device.deviceId).toList(); + final response = await DevicesAPI.deviceController( + code: 'switch_1', + devicesUuid: [event.deviceId], + value: !event.value, + ); + + emit(UpdateGroupState( + oneGangList: groupOneGangList, allSwitches: allSwitchesValue)); + if (!response['success']) { + add(InitialEvent(groupScreen: oneGangGroup)); + } + } catch (_) { + add(InitialEvent(groupScreen: oneGangGroup)); + } + } + + void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { + emit(LoadingNewSate(oneGangModel: deviceStatus)); + try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) + for (int i = 0; i < groupOneGangList.length; i++) { + groupOneGangList[i].firstSwitch = true; + } + + // Emit the state with updated values + emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: true)); + + // Get a list of all device IDs + List allDeviceIds = + groupOneGangList.map((device) => device.deviceId).toList(); + + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); + } + } catch (_) { + // In case of an error, delay and reset the screen to initial state + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); + } + } + + void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { + emit(LoadingNewSate(oneGangModel: deviceStatus)); + try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) + for (int i = 0; i < groupOneGangList.length; i++) { + groupOneGangList[i].firstSwitch = false; + } + + // Emit the state with updated values + emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: false)); + + // Get a list of all device IDs + List allDeviceIds = + groupOneGangList.map((device) => device.deviceId).toList(); + + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); + } + } catch (_) { + // In case of an error, delay and reset the screen to initial state + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); + } + } } diff --git a/lib/features/devices/bloc/one_gang_bloc/one_gang_event.dart b/lib/features/devices/bloc/one_gang_bloc/one_gang_event.dart index a59f653..21a8c85 100644 --- a/lib/features/devices/bloc/one_gang_bloc/one_gang_event.dart +++ b/lib/features/devices/bloc/one_gang_bloc/one_gang_event.dart @@ -29,12 +29,12 @@ class ChangeFirstSwitchStatusEvent extends OneGangEvent { class ChangeSecondSwitchStatusEvent extends OneGangEvent { final bool value; final String deviceId; - const ChangeSecondSwitchStatusEvent({required this.value, this.deviceId = ''}); + const ChangeSecondSwitchStatusEvent( + {required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } - class AllOffEvent extends OneGangEvent {} class AllOnEvent extends OneGangEvent {} @@ -87,27 +87,29 @@ class StopTimer extends OneGangEvent {} class OnClose extends OneGangEvent {} - - +class InitialWizardEvent extends OneGangEvent {} //------------------- Schedule ----------=--------- class GetScheduleEvent extends OneGangEvent {} + class ScheduleSave extends OneGangEvent {} + class ToggleScheduleEvent extends OneGangEvent { final String id; final bool toggle; - const ToggleScheduleEvent({required this.toggle,required this.id}); + const ToggleScheduleEvent({required this.toggle, required this.id}); @override - List get props => [toggle,id]; + List get props => [toggle, id]; } -class ToggleDaySelectionEvent extends OneGangEvent { +class ToggleDaySelectionEvent extends OneGangEvent { final String key; const ToggleDaySelectionEvent({required this.key}); @override List get props => [key]; } + class DeleteScheduleEvent extends OneGangEvent { final String id; const DeleteScheduleEvent({required this.id}); @@ -115,7 +117,6 @@ class DeleteScheduleEvent extends OneGangEvent { List get props => [id]; } - class ToggleSelectedEvent extends OneGangEvent { final int index; const ToggleSelectedEvent({required this.index}); @@ -123,10 +124,18 @@ class ToggleSelectedEvent extends OneGangEvent { List get props => [index]; } - class ToggleCreateScheduleEvent extends OneGangEvent { final int index; const ToggleCreateScheduleEvent({required this.index}); @override List get props => [index]; } + +class ChangeFirstWizardSwitchStatusEvent extends OneGangEvent { + final bool value; + final String deviceId; + const ChangeFirstWizardSwitchStatusEvent( + {required this.value, this.deviceId = ''}); + @override + List get props => [value, deviceId]; +} 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 1985acd..97b281e 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 @@ -380,15 +380,18 @@ class ThreeGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, code: 'switch_1', value: false), + deviceId: groupThreeGangList[i].deviceId, + code: 'switch_1', value: false), groupThreeGangList[i].deviceId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, code: 'switch_2', value: false), + deviceId: groupThreeGangList[i].deviceId, + code: 'switch_2', value: false), groupThreeGangList[i].deviceId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, code: 'switch_3', value: false), + deviceId: groupThreeGangList[i].deviceId, + code: 'switch_3', value: false), groupThreeGangList[i].deviceId), ]); @@ -645,4 +648,80 @@ class ThreeGangBloc extends Bloc { bool createSchedule = false; List listSchedule = []; DateTime? selectedTime = DateTime.now(); + + +// void _changeFirstSwitchWizard( ChangeFirstSwitchStatusEventWizard event, Emitter emit) async { +// emit(LoadingNewSate(threeGangModel: deviceStatus)); +// try { +// bool allSwitchesValue = true; +// groupThreeGangList.forEach((element) { +// if (element.deviceId == event.deviceId) { +// element.firstSwitch = !event.value; +// } +// if (!element.firstSwitch || +// !element.secondSwitch || +// !element.thirdSwitch) { +// allSwitchesValue = false; +// } +// }); +// emit(UpdateGroupState( +// threeGangList: groupThreeGangList, allSwitches: allSwitchesValue)); + +// if (_timer != null) { +// _timer!.cancel(); +// } +// _timer = Timer(const Duration(milliseconds: 100), () async { +// final response = await DevicesAPI.controlDevice( +// DeviceControlModel( +// deviceId: event.deviceId , +// code: 'switch_1', +// value: event.value), +// event.deviceId ); +// if (!response['success']) { +// add(InitialEvent(groupScreen: threeGangGroup)); +// } +// }); +// } catch (_) { +// add(InitialEvent(groupScreen: threeGangGroup)); +// } +// } + +// Future fetchGroupDevises( +// InitialWizardDevises event, Emitter emit) async { +// emit(LoadingInitialState()); +// devicesList = []; +// listDevises = []; +// allSwitchesOn = true; +// devicesList = await DevicesAPI.getDeviceByGroupName( +// HomeCubit.getInstance().selectedSpace?.id ?? '', '3G'); + +// for (int i = 0; i < devicesList.length; i++) { +// var response = +// await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); +// List statusModelList = []; +// for (var status in response['status']) { +// statusModelList.add(StatusModel.fromJson(status)); +// } +// deviceStatus = ThreeGangModel.fromJson(statusModelList); + +// listDevises.add(GroupThreeGangModel( +// secondSwitch: deviceStatus.secondSwitch, +// thirdSwitch: deviceStatus.thirdSwitch, +// deviceId: devicesList[i].uuid ?? '', +// deviceName: devicesList[i].name ?? '', +// firstSwitch: deviceStatus.firstSwitch, +// )); +// } +// if (listDevises.isNotEmpty) { +// listDevises.firstWhere((element) { +// if (!element.firstSwitch) { +// allSwitchesOn = false; +// } +// return true; +// }); +// } +// emit(UpdateGroupState( +// threeGangList: listDevises, allSwitches: allSwitchesOn)); +// } + } diff --git a/lib/features/devices/bloc/three_gang_bloc/three_gang_event.dart b/lib/features/devices/bloc/three_gang_bloc/three_gang_event.dart index 12e727b..da74cc2 100644 --- a/lib/features/devices/bloc/three_gang_bloc/three_gang_event.dart +++ b/lib/features/devices/bloc/three_gang_bloc/three_gang_event.dart @@ -135,4 +135,6 @@ class ToggleCreateScheduleEvent extends ThreeGangEvent { const ToggleCreateScheduleEvent({required this.index}); @override List get props => [index]; -} \ No newline at end of file +} + +class InitialWizardDevises extends ThreeGangEvent {} diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart index 0891db2..2820da4 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart @@ -57,6 +57,9 @@ class TwoGangBloc extends Bloc { on(deleteSchedule); on(toggleSelectedIndex); on(toggleCreateSchedule); + on(_fetchTwoGangWizardStatus); + on(_changeFirstWizardSwitch); + on(_changeSecondWizardSwitch); } DateTime? selectedTime = DateTime.now(); @@ -296,38 +299,117 @@ class TwoGangBloc extends Bloc { } } + // void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { + // emit(LoadingNewSate(twoGangModel: deviceStatus)); + // try { + // for (int i = 0; i < groupTwoGangList.length; i++) { + // groupTwoGangList[i].firstSwitch = true; + // groupTwoGangList[i].secondSwitch = true; + // } + // emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); + + // for (int i = 0; i < groupTwoGangList.length; i++) { + // final response = await Future.wait([ + // DevicesAPI.controlDevice( + // DeviceControlModel( + // deviceId: groupTwoGangList[i].deviceId, + // code: 'switch_1', + // value: true), + // groupTwoGangList[i].deviceId), + // DevicesAPI.controlDevice( + // DeviceControlModel( + // deviceId: groupTwoGangList[i].deviceId, + // code: 'switch_2', + // value: true), + // groupTwoGangList[i].deviceId), + // ]); + + // if (response.every((element) => !element['success'])) { + // await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + // break; + // } + // } + // } catch (_) { + // await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + // } + // } + + // void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { + // emit(LoadingNewSate(twoGangModel: deviceStatus)); + // try { + // for (int i = 0; i < groupTwoGangList.length; i++) { + // groupTwoGangList[i].firstSwitch = false; + // groupTwoGangList[i].secondSwitch = false; + // } + // emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); + + // for (int i = 0; i < groupTwoGangList.length; i++) { + // final response = await Future.wait([ + // DevicesAPI.controlDevice( + // DeviceControlModel( + // deviceId: groupTwoGangList[i].deviceId, + // code: 'switch_1', + // value: false), + // groupTwoGangList[i].deviceId), + // DevicesAPI.controlDevice( + // DeviceControlModel( + // deviceId: groupTwoGangList[i].deviceId, + // code: 'switch_2', + // value: false), + // groupTwoGangList[i].deviceId), + // ]); + + // if (response.every((element) => !element['success'])) { + // await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + // break; + // } + // } + // } catch (_) { + // await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + // } + // } + void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = true; groupTwoGangList[i].secondSwitch = true; } + + // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - for (int i = 0; i < groupTwoGangList.length; i++) { - final response = await Future.wait([ - DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: groupTwoGangList[i].deviceId, - code: 'switch_1', - value: true), - groupTwoGangList[i].deviceId), - DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: groupTwoGangList[i].deviceId, - code: 'switch_2', - value: true), - groupTwoGangList[i].deviceId), - ]); + // Get a list of all device IDs + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); - if (response.every((element) => !element['success'])) { - await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); - break; - } + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); } } catch (_) { + // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } @@ -336,35 +418,40 @@ class TwoGangBloc extends Bloc { void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = false; groupTwoGangList[i].secondSwitch = false; } + + // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - for (int i = 0; i < groupTwoGangList.length; i++) { - final response = await Future.wait([ - DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: groupTwoGangList[i].deviceId, - code: 'switch_1', - value: false), - groupTwoGangList[i].deviceId), - DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: groupTwoGangList[i].deviceId, - code: 'switch_2', - value: false), - groupTwoGangList[i].deviceId), - ]); + // Get a list of all device IDs + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); - if (response.every((element) => !element['success'])) { - await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); - break; - } + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + add(const InitialEvent(groupScreen: true)); } } catch (_) { + // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } @@ -574,4 +661,112 @@ class TwoGangBloc extends Bloc { emit(FailedState(error: errorMessage.toString())); } } + + void _fetchTwoGangWizardStatus( + InitialWizardEvent event, Emitter emit) async { + emit(LoadingInitialState()); + try { + devicesList = []; + groupTwoGangList = []; + allSwitchesOn = true; + devicesList = await DevicesAPI.getDeviceByGroupName( + HomeCubit.getInstance().selectedSpace?.id ?? '', '2G'); + + for (int i = 0; i < devicesList.length; i++) { + var response = + await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); + List statusModelList = []; + for (var status in response['status']) { + statusModelList.add(StatusModel.fromJson(status)); + } + deviceStatus = TwoGangModel.fromJson(statusModelList); + + groupTwoGangList.add(GroupTwoGangModel( + deviceId: devicesList[i].uuid ?? '', + deviceName: devicesList[i].name ?? '', + firstSwitch: deviceStatus.firstSwitch, + secondSwitch: deviceStatus.secondSwitch, + )); + } + + if (groupTwoGangList.isNotEmpty) { + groupTwoGangList.firstWhere((element) { + if (!element.firstSwitch || !element.secondSwitch) { + allSwitchesOn = false; + } + return true; + }); + } + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesOn)); + } catch (e) { + emit(FailedState(error: e.toString())); + return; + } + } + + void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, + Emitter emit) async { + emit(LoadingNewSate(twoGangModel: deviceStatus)); + try { + bool allSwitchesValue = true; + groupTwoGangList.forEach((element) { + if (element.deviceId == event.deviceId) { + element.firstSwitch = !event.value; + } + if (!element.firstSwitch || !element.secondSwitch) { + allSwitchesValue = false; + } + }); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); + final response = await DevicesAPI.deviceController( + code: 'switch_1', + devicesUuid: allDeviceIds, + value: !event.value, + ); + + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + if (!response['success']) { + add(InitialEvent(groupScreen: twoGangGroup)); + } + } catch (_) { + add(InitialEvent(groupScreen: twoGangGroup)); + } + } + + void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event, + Emitter emit) async { + emit(LoadingNewSate(twoGangModel: deviceStatus)); + try { + bool allSwitchesValue = true; + groupTwoGangList.forEach((element) { + if (element.deviceId == event.deviceId) { + element.secondSwitch = !event.value; + } + if (!element.firstSwitch || !element.secondSwitch) { + allSwitchesValue = false; + } + }); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); + + final response = await DevicesAPI.deviceController( + code: 'switch_2', + devicesUuid: allDeviceIds, + value: !event.value, + ); + + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + if (response['failedResults'].toString() != '[]') { + add(InitialEvent(groupScreen: twoGangGroup)); + } + } catch (_) { + add(InitialEvent(groupScreen: twoGangGroup)); + } + } + + } diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart index db8bd96..0555ad0 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart @@ -10,17 +10,20 @@ abstract class TwoGangEvent extends Equatable { class LoadingEvent extends TwoGangEvent {} class TwoGangUpdated extends TwoGangEvent {} + class TwoGangSave extends TwoGangEvent {} + class ToggleScheduleEvent extends TwoGangEvent { final String id; final bool toggle; - const ToggleScheduleEvent({required this.toggle,required this.id}); + const ToggleScheduleEvent({required this.toggle, required this.id}); @override - List get props => [toggle,id]; + List get props => [toggle, id]; } -class errorMessage extends TwoGangEvent {} -class ToggleDaySelectionEvent extends TwoGangEvent { +class errorMessage extends TwoGangEvent {} + +class ToggleDaySelectionEvent extends TwoGangEvent { final String key; const ToggleDaySelectionEvent({required this.key}); @@ -46,12 +49,12 @@ class ChangeFirstSwitchStatusEvent extends TwoGangEvent { class ChangeSecondSwitchStatusEvent extends TwoGangEvent { final bool value; final String deviceId; - const ChangeSecondSwitchStatusEvent({required this.value, this.deviceId = ''}); + const ChangeSecondSwitchStatusEvent( + {required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } - class AllOffEvent extends TwoGangEvent {} class AllOnEvent extends TwoGangEvent {} @@ -60,13 +63,9 @@ class GroupAllOnEvent extends TwoGangEvent {} class GroupAllOffEvent extends TwoGangEvent {} - // two_gang_event.dart // class ToggleCreateScheduleEvent extends TwoGangEvent {} - - - class ChangeSlidingSegment extends TwoGangEvent { final int value; const ChangeSlidingSegment({required this.value}); @@ -111,20 +110,20 @@ class StopTimer extends TwoGangEvent {} class OnClose extends TwoGangEvent {} - class GetScheduleEvent extends TwoGangEvent {} + class DeleteScheduleEvent extends TwoGangEvent { final String id; const DeleteScheduleEvent({required this.id}); @override List get props => [id]; } + class TabChangedEvent extends TwoGangEvent { final int index; TabChangedEvent({required this.index}); } - class ToggleSelectedEvent extends TwoGangEvent { final int index; const ToggleSelectedEvent({required this.index}); @@ -132,7 +131,6 @@ class ToggleSelectedEvent extends TwoGangEvent { List get props => [index]; } - class ToggleCreateScheduleEvent extends TwoGangEvent { final int index; const ToggleCreateScheduleEvent({required this.index}); @@ -140,5 +138,22 @@ class ToggleCreateScheduleEvent extends TwoGangEvent { List get props => [index]; } +class InitialWizardEvent extends TwoGangEvent {} +class ChangeFirstWizardSwitchStatusEvent extends TwoGangEvent { + final bool value; + final String deviceId; + const ChangeFirstWizardSwitchStatusEvent( + {required this.value, this.deviceId = ''}); + @override + List get props => [value, deviceId]; +} +class ChangeSecondWizardSwitchStatusEvent extends TwoGangEvent { + final bool value; + final String deviceId; + const ChangeSecondWizardSwitchStatusEvent( + {required this.value, this.deviceId = ''}); + @override + List get props => [value, deviceId]; +} 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 78e25ec..e1c55ca 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 @@ -2,8 +2,10 @@ import 'dart:async'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart'; import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_event.dart'; import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart'; +import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; import 'package:syncrow_app/features/devices/model/device_control_model.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/schedule_model.dart'; @@ -16,9 +18,7 @@ import 'package:syncrow_app/utils/resource_manager/color_manager.dart'; class WaterHeaterBloc extends Bloc { final String whId; final String switchCode; - WHModel deviceStatus = WHModel( - firstSwitch: false,firstCountDown: 0 - ); + WHModel deviceStatus = WHModel(firstSwitch: false, firstCountDown: 0); List deviceStatusList = []; List devicesList = []; bool allAcsPage = false; @@ -27,15 +27,15 @@ class WaterHeaterBloc extends Bloc { int globalTemp = 25; Timer? _timer; - bool toggleSchedule = true; List selectedDays = []; bool createSchedule = false; bool createCirculate = false; List listSchedule = []; - DateTime? selectedTime=DateTime.now(); + 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); @@ -49,11 +49,17 @@ class WaterHeaterBloc extends Bloc { on(_onClose); on(showTime); - on(toggleSelectedIndex); + on(toggleSelectedIndex); on(toggleCreateSchedule); + on(_fetchWHWizardStatus); + on(_changeFirstWizardSwitch); + + on(_groupAllOn); + on(_groupAllOff); } - void _fetchWaterHeaterStatus(WaterHeaterInitial event, Emitter emit) async { + void _fetchWaterHeaterStatus( + WaterHeaterInitial event, Emitter emit) async { emit(WHLoadingState()); try { var response = await DevicesAPI.getDeviceStatus(whId); @@ -61,7 +67,9 @@ class WaterHeaterBloc extends Bloc { for (var status in response['status']) { statusModelList.add(StatusModel.fromJson(status)); } - deviceStatus = WHModel.fromJson(statusModelList, ); + deviceStatus = WHModel.fromJson( + statusModelList, + ); emit(UpdateState(whModel: deviceStatus)); Future.delayed(const Duration(milliseconds: 500)); // _listenToChanges(); @@ -71,8 +79,8 @@ class WaterHeaterBloc extends Bloc { } } - - void _changeFirstSwitch(WaterHeaterSwitch event, Emitter emit) async { + void _changeFirstSwitch( + WaterHeaterSwitch event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.whSwitch; @@ -83,13 +91,13 @@ class WaterHeaterBloc extends Bloc { _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( DeviceControlModel( - deviceId: whId, + deviceId: whId, code: 'switch_1', - value: deviceStatus.firstSwitch ), + value: deviceStatus.firstSwitch), whId); if (!response['success']) { - // add(InitialEvent(groupScreen: oneGangGroup)); + // add(InitialEvent(groupScreen: oneGangGroup)); } }); } catch (_) { @@ -97,19 +105,17 @@ 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), + DeviceControlModel( + deviceId: whId, code: event.deviceCode, value: seconds), whId); if (response['success'] ?? false) { @@ -132,7 +138,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); @@ -148,7 +155,7 @@ class WaterHeaterBloc extends Bloc { : emit(UpdateTimerState(seconds: deviceStatus.firstCountDown)); } } catch (e) { - WHFailedState(errorMessage: e.toString()); + WHFailedState(errorMessage: e.toString()); return; } } @@ -173,13 +180,8 @@ class WaterHeaterBloc extends Bloc { } } - - - //=====================---------- Schedule ---------------------------------------- - - List> days = [ {"day": "Sun", "key": "Sun"}, {"day": "Mon", "key": "Mon"}, @@ -190,9 +192,12 @@ class WaterHeaterBloc extends Bloc { {"day": "Sat", "key": "Sat"}, ]; - Future saveSchedule(ScheduleSave event, Emitter emit,) async { + Future saveSchedule( + ScheduleSave event, + Emitter emit, + ) async { try { - if(selectedDays.isNotEmpty) { + if (selectedDays.isNotEmpty) { emit(WHLoadingState()); final response = await DevicesAPI.postSchedule( category: switchCode, @@ -204,24 +209,28 @@ class WaterHeaterBloc extends Bloc { CustomSnackBar.displaySnackBar('Save Successfully'); add(GetScheduleEvent()); emit(SaveSchedule()); - add(const ToggleCreateScheduleEvent(index:1 )); - }else{ + add(const ToggleCreateScheduleEvent(index: 1)); + } else { CustomSnackBar.displaySnackBar('Please select days'); } } catch (e) { - emit(WHFailedState(errorMessage:e.toString())); + emit(WHFailedState(errorMessage: e.toString())); } } - Future getSchedule(GetScheduleEvent event, Emitter emit,) async { + Future getSchedule( + GetScheduleEvent event, + Emitter emit, + ) async { try { emit(WHLoadingState()); final response = await DevicesAPI.getSchedule( category: switchCode, - deviceId: whId , + 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; @@ -252,7 +261,7 @@ class WaterHeaterBloc extends Bloc { } on DioException catch (e) { final errorData = e.response!.data; String errorMessage = errorData['message']; - emit(WHFailedState(errorMessage: errorMessage.toString())); + emit(WHFailedState(errorMessage: errorMessage.toString())); } } @@ -262,7 +271,8 @@ class WaterHeaterBloc extends Bloc { emit(WHLoadingState()); final response = await DevicesAPI.deleteSchedule( scheduleId: event.id, - deviceUuid: whId, ); + deviceUuid: whId, + ); if (response == true) { add(GetScheduleEvent()); return toggleSchedule; @@ -284,38 +294,38 @@ class WaterHeaterBloc extends Bloc { // } void toggleCreateCirculate() { - emit(WHLoadingState()); + emit(WHLoadingState()); createCirculate = !createCirculate; selectedDays.clear(); - selectedTime=DateTime.now(); + selectedTime = DateTime.now(); emit(UpdateCreateScheduleState(createCirculate)); } - // void toggleSelectedIndex(index) { // emit(WHLoadingState()); // selectedTabIndex = index; // emit(ChangeSlidingSegmentState(value: selectedTabIndex)); // } - void toggleSelectedIndex( ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex( + ToggleSelectedEvent event, Emitter emit) { emit(WHLoadingState()); - selectedTabIndex =event.index; + selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); } - - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { - emit(WHLoadingState()); - createSchedule = !createSchedule; - selectedDays.clear(); - selectedTime = DateTime.now(); - emit(UpdateCreateScheduleState(createSchedule)); -} + void toggleCreateSchedule( + ToggleCreateScheduleEvent event, Emitter emit) { + emit(WHLoadingState()); + createSchedule = !createSchedule; + selectedDays.clear(); + selectedTime = DateTime.now(); + emit(UpdateCreateScheduleState(createSchedule)); + } Future toggleDaySelection( - ToggleDaySelectionEvent event, - Emitter emit, - ) async { + ToggleDaySelectionEvent event, + Emitter emit, + ) async { emit(WHLoadingState()); if (selectedDays.contains(event.key)) { selectedDays.remove(event.key); @@ -327,7 +337,6 @@ class WaterHeaterBloc extends Bloc { int selectedTabIndex = 0; - showTime(SelectTimeEvent event, Emitter emit) async { final TimeOfDay? timePicked = await showTimePicker( context: event.context, @@ -350,4 +359,165 @@ class WaterHeaterBloc extends Bloc { }, ); } + + // List devicesList = []; + List groupTwoGangList = []; + bool allSwitchesOn = true; + + void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, + Emitter emit) async { + emit(LoadingNewSate(whModel: deviceStatus)); + try { + bool allSwitchesValue = true; + groupTwoGangList.forEach((element) { + if (element.deviceId == event.deviceId) { + element.firstSwitch = !event.value; + } + if (!element.firstSwitch) { + allSwitchesValue = false; + } + }); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); + final response = await DevicesAPI.deviceController( + code: 'switch_1', + devicesUuid: allDeviceIds, + value: !event.value, + ); + + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + if (!response['success']) { + // add(InitialEvent(groupScreen: twoGangGroup)); + } + } catch (_) { + // add(InitialEvent(groupScreen: twoGangGroup)); + } + } + + void _fetchWHWizardStatus( + InitialWizardEvent event, Emitter emit) async { + emit(WHLoadingState()); + try { + devicesList = []; + groupTwoGangList = []; + allSwitchesOn = true; + devicesList = await DevicesAPI.getDeviceByGroupName( + HomeCubit.getInstance().selectedSpace?.id ?? '', 'WH'); + + for (int i = 0; i < devicesList.length; i++) { + var response = + await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); + List statusModelList = []; + for (var status in response['status']) { + statusModelList.add(StatusModel.fromJson(status)); + } + deviceStatus = WHModel.fromJson(statusModelList); + + groupTwoGangList.add(GroupWHModel( + deviceId: devicesList[i].uuid ?? '', + deviceName: devicesList[i].name ?? '', + firstSwitch: deviceStatus.firstSwitch, + )); + } + + if (groupTwoGangList.isNotEmpty) { + groupTwoGangList.firstWhere((element) { + if (!element.firstSwitch) { + allSwitchesOn = false; + } + return true; + }); + } + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesOn)); + } catch (e) { + // emit(FailedState(error: e.toString())); + return; + } + } + + void _groupAllOn( + GroupAllOnEvent event, Emitter emit) async { + emit(LoadingNewSate(whModel: deviceStatus)); + try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) + for (int i = 0; i < groupTwoGangList.length; i++) { + groupTwoGangList[i].firstSwitch = true; + } + + // Emit the state with updated values + emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); + + // Get a list of all device IDs + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); + + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + } + } catch (_) { + // In case of an error, delay and reset the screen to initial state + await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + } + } + + void _groupAllOff( + GroupAllOffEvent event, Emitter emit) async { + emit(LoadingNewSate(whModel: deviceStatus)); + try { + // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) + for (int i = 0; i < groupTwoGangList.length; i++) { + groupTwoGangList[i].firstSwitch = false; + } + + // Emit the state with updated values + emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); + + // Get a list of all device IDs + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); + + // First call for switch_1 + final response1 = await DevicesAPI.deviceController( + code: 'switch_1', // Controls first switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Second call for switch_2 + final response2 = await DevicesAPI.deviceController( + code: 'switch_2', // Controls second switch for all devices + devicesUuid: allDeviceIds, + value: true, // true (on) or false (off) depending on the event value + ); + + // Check if either response is unsuccessful, then reset to initial state + if (!response1['success'] || !response2['success']) { + await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + } + } catch (_) { + // In case of an error, delay and reset the screen to initial state + await Future.delayed(const Duration(milliseconds: 500)); + // add(const InitialEvent(groupScreen: true)); + } + } } diff --git a/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart b/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart index d39efa9..0cd2d37 100644 --- a/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart +++ b/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart @@ -123,3 +123,21 @@ class ToggleCreateCirculateEvent extends WaterHeaterEvent { @override List get props => [index]; } + + + +class InitialWizardEvent extends WaterHeaterEvent {} + +class ChangeFirstWizardSwitchStatusEvent extends WaterHeaterEvent { + final bool value; + final String deviceId; + const ChangeFirstWizardSwitchStatusEvent( + {required this.value, this.deviceId = ''}); + @override + List get props => [value, deviceId]; +} + + +class GroupAllOnEvent extends WaterHeaterEvent {} + +class GroupAllOffEvent extends WaterHeaterEvent {} \ No newline at end of file diff --git a/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart b/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart index 254297a..de4c383 100644 --- a/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart +++ b/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart @@ -1,4 +1,5 @@ import 'package:equatable/equatable.dart'; +import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; import 'package:syncrow_app/features/devices/model/water_heater.dart'; abstract class WaterHeaterState extends Equatable { @@ -110,4 +111,17 @@ class ChangeSlidingSegmentState extends WaterHeaterState { @override List get props => [value]; -} \ No newline at end of file +} + + + + +class UpdateGroupState extends WaterHeaterState { + final List twoGangList; + final bool allSwitches; + + const UpdateGroupState({required this.twoGangList, required this.allSwitches}); + + @override + List get props => [twoGangList, allSwitches]; +} diff --git a/lib/features/devices/model/GroupWHModel.dart b/lib/features/devices/model/GroupWHModel.dart new file mode 100644 index 0000000..9d8cc4a --- /dev/null +++ b/lib/features/devices/model/GroupWHModel.dart @@ -0,0 +1,11 @@ +class GroupWHModel { + final String deviceId; + final String deviceName; + bool firstSwitch; + + GroupWHModel({ + required this.deviceId, + required this.deviceName, + required this.firstSwitch, + }); +} diff --git a/lib/features/devices/view/widgets/one_gang/one_gang_list.dart b/lib/features/devices/view/widgets/one_gang/one_gang_list.dart index ba03339..abf3c4b 100644 --- a/lib/features/devices/view/widgets/one_gang/one_gang_list.dart +++ b/lib/features/devices/view/widgets/one_gang/one_gang_list.dart @@ -8,7 +8,8 @@ import 'package:syncrow_app/features/shared_widgets/devices_default_switch.dart' import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart'; class OneGangList extends StatelessWidget { - const OneGangList({super.key, required this.oneGangList, required this.allSwitches}); + const OneGangList( + {super.key, required this.oneGangList, required this.allSwitches}); final List oneGangList; final bool allSwitches; @@ -48,9 +49,10 @@ class OneGangList extends StatelessWidget { DevicesDefaultSwitch( switchValue: oneGangList[index].firstSwitch, action: () { - BlocProvider.of(context).add(ChangeFirstSwitchStatusEvent( - value: oneGangList[index].firstSwitch, - deviceId: oneGangList[index].deviceId)); + BlocProvider.of(context).add( + ChangeFirstWizardSwitchStatusEvent( + value: oneGangList[index].firstSwitch, + deviceId: oneGangList[index].deviceId)); }, ), ], diff --git a/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart b/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart new file mode 100644 index 0000000..98f6645 --- /dev/null +++ b/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_event.dart'; +import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_state.dart'; +import 'package:syncrow_app/features/devices/model/device_model.dart'; +import 'package:syncrow_app/features/devices/model/group_one_gang_model.dart'; +import 'package:syncrow_app/features/devices/model/one_gang_model.dart'; +import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_list.dart'; +import 'package:syncrow_app/features/shared_widgets/default_container.dart'; +import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; + +class OneGangWizard extends StatelessWidget { + const OneGangWizard({super.key, this.device}); + + final DeviceModel? device; + + @override + Widget build(BuildContext context) { + List groupOneGangModel = []; + + return DefaultScaffold( + child: BlocProvider( + create: (context) => + OneGangBloc(switchCode: '', oneGangId: device?.uuid ?? '') + ..add(InitialWizardEvent()), + child: BlocBuilder( + builder: (context, state) { + OneGangModel oneGangModel = OneGangModel( + firstSwitch: false, + firstCountDown: 0, + ); + bool allSwitchesOn = false; + + if (state is LoadingNewSate) { + oneGangModel = state.oneGangModel; + } else if (state is UpdateState) { + oneGangModel = state.oneGangModel; + } else if (state is UpdateGroupState) { + groupOneGangModel = state.oneGangList; + allSwitchesOn = state.allSwitches; + } + return state is LoadingInitialState + ? const Center( + child: DefaultContainer( + width: 50, + height: 50, + child: CircularProgressIndicator()), + ) + : OneGangList( + oneGangList: groupOneGangModel, + allSwitches: allSwitchesOn, + ); + }, + ), + )); + } +} diff --git a/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart b/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart index b9a8f0c..084ecf2 100644 --- a/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart +++ b/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart @@ -51,13 +51,7 @@ class ThreeGangScreen extends StatelessWidget { ? const Center( child: DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), - ) - : device == null - ? ThreeGangList( - threeGangList: groupThreeGangModel, - allSwitches: allSwitchesOn, - ) - : RefreshIndicator( + ) : RefreshIndicator( onRefresh: () async { BlocProvider.of(context) .add(InitialEvent(groupScreen: device != null ? false : true)); diff --git a/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart b/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart new file mode 100644 index 0000000..25c7a1f --- /dev/null +++ b/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_event.dart'; +import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_state.dart'; +import 'package:syncrow_app/features/devices/model/device_model.dart'; +import 'package:syncrow_app/features/devices/model/group_three_gang_model.dart'; +import 'package:syncrow_app/features/devices/model/three_gang_model.dart'; +import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_list.dart'; +import 'package:syncrow_app/features/shared_widgets/default_container.dart'; +import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; + +class ThreeGangWizard extends StatelessWidget { + const ThreeGangWizard({super.key, this.device}); + + final DeviceModel? device; + + @override + Widget build(BuildContext context) { + return DefaultScaffold( + child: BlocProvider( + create: (context) => + ThreeGangBloc(switchCode: '', threeGangId: device?.uuid ?? '') + ..add(InitialEvent(groupScreen: device != null ? false : true)), + child: BlocBuilder( + builder: (context, state) { + ThreeGangModel threeGangModel = ThreeGangModel( + firstSwitch: false, + secondSwitch: false, + thirdSwitch: false, + firstCountDown: 0, + secondCountDown: 0, + thirdCountDown: 0); + + List groupThreeGangModel = []; + bool allSwitchesOn = false; + + if (state is LoadingNewSate) { + threeGangModel = state.threeGangModel; + } else if (state is UpdateState) { + threeGangModel = state.threeGangModel; + } else if (state is UpdateGroupState) { + groupThreeGangModel = state.threeGangList; + allSwitchesOn = state.allSwitches; + } + return state is LoadingInitialState + ? const Center( + child: DefaultContainer( + width: 50, + height: 50, + child: CircularProgressIndicator()), + ) + : ThreeGangList( + threeGangList: groupThreeGangModel, + allSwitches: allSwitchesOn, + ); + }, + ), + )); + } +} diff --git a/lib/features/devices/view/widgets/two_gang/two_gang_list.dart b/lib/features/devices/view/widgets/two_gang/two_gang_list.dart index a36de97..d0c4d78 100644 --- a/lib/features/devices/view/widgets/two_gang/two_gang_list.dart +++ b/lib/features/devices/view/widgets/two_gang/two_gang_list.dart @@ -8,7 +8,8 @@ import 'package:syncrow_app/features/shared_widgets/devices_default_switch.dart' import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart'; class TwoGangList extends StatelessWidget { - const TwoGangList({super.key, required this.twoGangList, required this.allSwitches}); + const TwoGangList( + {super.key, required this.twoGangList, required this.allSwitches}); final List twoGangList; final bool allSwitches; @@ -48,9 +49,10 @@ class TwoGangList extends StatelessWidget { DevicesDefaultSwitch( switchValue: twoGangList[index].firstSwitch, action: () { - BlocProvider.of(context).add(ChangeFirstSwitchStatusEvent( - value: twoGangList[index].firstSwitch, - deviceId: twoGangList[index].deviceId)); + BlocProvider.of(context).add( + ChangeFirstWizardSwitchStatusEvent( + value: twoGangList[index].firstSwitch, + deviceId: twoGangList[index].deviceId)); }, ), const SizedBox(height: 10), @@ -59,9 +61,10 @@ class TwoGangList extends StatelessWidget { DevicesDefaultSwitch( switchValue: twoGangList[index].secondSwitch, action: () { - BlocProvider.of(context).add(ChangeSecondSwitchStatusEvent( - value: twoGangList[index].secondSwitch, - deviceId: twoGangList[index].deviceId)); + BlocProvider.of(context).add( + ChangeSecondWizardSwitchStatusEvent( + value: twoGangList[index].secondSwitch, + deviceId: twoGangList[index].deviceId)); }, ), ], diff --git a/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart b/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart new file mode 100644 index 0000000..523cf64 --- /dev/null +++ b/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_state.dart'; +import 'package:syncrow_app/features/devices/model/device_model.dart'; +import 'package:syncrow_app/features/devices/model/group_two_gang_model.dart'; +import 'package:syncrow_app/features/devices/model/two_gang_model.dart'; +import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_list.dart'; +import 'package:syncrow_app/features/shared_widgets/default_container.dart'; +import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; + +import '../../../bloc/two_gang_bloc/two_gang_event.dart'; + +class TwoGangWizard extends StatelessWidget { + const TwoGangWizard({super.key, this.device}); + + final DeviceModel? device; + + @override + Widget build(BuildContext context) { + List groupTwoGangModel = []; + + return DefaultScaffold( + child: BlocProvider( + create: (context) => + TwoGangBloc(switchCode: '', twoGangId: device?.uuid ?? '') + ..add(InitialWizardEvent()), + child: BlocBuilder( + builder: (context, state) { + TwoGangModel twoGangModel = TwoGangModel( + firstSwitch: false, + secondSwitch: false, + firstCountDown: 0, + secondCountDown: 0, + ); + bool allSwitchesOn = false; + + if (state is LoadingNewSate) { + twoGangModel = state.twoGangModel; + } else if (state is UpdateState) { + twoGangModel = state.twoGangModel; + } else if (state is UpdateGroupState) { + groupTwoGangModel = state.twoGangList; + allSwitchesOn = state.allSwitches; + } + return state is LoadingInitialState + ? const Center( + child: DefaultContainer( + width: 50, + height: 50, + child: CircularProgressIndicator()), + ) + : TwoGangList( + twoGangList: groupTwoGangModel, + allSwitches: allSwitchesOn, + ); + }, + ), + )); + } +} diff --git a/lib/features/devices/view/widgets/water_heater/wh_list.dart b/lib/features/devices/view/widgets/water_heater/wh_list.dart new file mode 100644 index 0000000..ace29e5 --- /dev/null +++ b/lib/features/devices/view/widgets/water_heater/wh_list.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_event.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart'; +import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; +import 'package:syncrow_app/features/shared_widgets/devices_default_switch.dart'; +import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart'; + +class WHList extends StatelessWidget { + const WHList({super.key, required this.whList, required this.allSwitches}); + + final List whList; + final bool allSwitches; + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 10), + const BodySmall(text: 'All Lights'), + const SizedBox(height: 5), + DevicesDefaultSwitch( + switchValue: allSwitches, + action: () { + BlocProvider.of(context) + .add(GroupAllOnEvent()); + }, + secondAction: () { + BlocProvider.of(context) + .add(GroupAllOffEvent()); + }, + ), + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: const EdgeInsets.all(0), + itemCount: whList.length, + itemBuilder: (context, index) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 10), + BodySmall(text: whList[index].deviceName), + const SizedBox(height: 5), + DevicesDefaultSwitch( + switchValue: whList[index].firstSwitch, + action: () { + BlocProvider.of(context).add( + ChangeFirstWizardSwitchStatusEvent( + value: whList[index].firstSwitch, + deviceId: whList[index].deviceId)); + }, + ), + ], + ); + }, + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/features/devices/view/widgets/water_heater/wh_wizard.dart b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart new file mode 100644 index 0000000..f63f9db --- /dev/null +++ b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_event.dart'; +import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart'; +import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; +import 'package:syncrow_app/features/devices/model/device_model.dart'; +import 'package:syncrow_app/features/devices/model/water_heater.dart'; +import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_list.dart'; +import 'package:syncrow_app/features/devices/view/widgets/water_heater/wh_list.dart'; +import 'package:syncrow_app/features/menu/bloc/manage_unit_bloc/manage_unit_state.dart'; +import 'package:syncrow_app/features/shared_widgets/default_container.dart'; +import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; + +class WHWizard extends StatelessWidget { + const WHWizard({super.key, this.device}); + + final DeviceModel? device; + + @override + Widget build(BuildContext context) { + List groupModel = []; + + return DefaultScaffold( + child: BlocProvider( + create: (context) => + WaterHeaterBloc(switchCode: '', whId: device?.uuid ?? '') + ..add(InitialWizardEvent()), + child: BlocBuilder( + builder: (context, state) { + WHModel whModel = WHModel( + firstSwitch: false, + firstCountDown: 0, + ); + bool allSwitchesOn = false; + + if (state is LoadingNewSate) { + whModel = state.whModel; + } else if (state is UpdateState) { + whModel = state.whModel; + } else if (state is UpdateGroupState) { + groupModel = state.twoGangList; + allSwitchesOn = state.allSwitches; + } + return state is WHLoadingState + ? const Center( + child: DefaultContainer( + width: 50, + height: 50, + child: CircularProgressIndicator()), + ) + : WHList( + whList: groupModel, + allSwitches: allSwitchesOn, + ); + }, + ), + )); + } +} diff --git a/lib/features/devices/view/widgets/wizard_page.dart b/lib/features/devices/view/widgets/wizard_page.dart index fdddf05..93558b0 100644 --- a/lib/features/devices/view/widgets/wizard_page.dart +++ b/lib/features/devices/view/widgets/wizard_page.dart @@ -3,8 +3,12 @@ import 'package:flutter_svg/svg.dart'; import 'package:syncrow_app/features/devices/model/device_category_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/ACs/acs_view.dart'; import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_Interface.dart'; +import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_wizard.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_interface.dart'; +import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_wizard.dart'; import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_Interface.dart'; +import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_wizard.dart'; +import 'package:syncrow_app/features/devices/view/widgets/water_heater/wh_wizard.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart'; import 'package:syncrow_app/utils/context_extension.dart'; @@ -32,26 +36,36 @@ class WizardPage extends StatelessWidget { Navigator.push( context, PageRouteBuilder( - pageBuilder: (context, animation1, animation2) => const ACsView())); + pageBuilder: (context, animation1, animation2) => + const ACsView())); } if (groupsList[index].name == '3G') { Navigator.push( context, PageRouteBuilder( pageBuilder: (context, animation1, animation2) => - const ThreeGangInterface())); + const ThreeGangWizard())); } if (groupsList[index].name == '2G') { Navigator.push( context, PageRouteBuilder( - pageBuilder: (context, animation1, animation2) => const TwoGangInterface())); + pageBuilder: (context, animation1, animation2) => + const TwoGangWizard())); } if (groupsList[index].name == '1G') { Navigator.push( context, PageRouteBuilder( - pageBuilder: (context, animation1, animation2) => const OneGangInterface())); + pageBuilder: (context, animation1, animation2) => + const OneGangWizard())); + } + if (groupsList[index].name == 'WH') { + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: (context, animation1, animation2) => + const WHWizard())); } }, child: DefaultContainer( diff --git a/lib/services/api/api_links_endpoints.dart b/lib/services/api/api_links_endpoints.dart index af3e506..198678e 100644 --- a/lib/services/api/api_links_endpoints.dart +++ b/lib/services/api/api_links_endpoints.dart @@ -189,5 +189,7 @@ abstract class ApiEndpoints { '/schedule/{deviceUuid}?category={category}'; static const String changeSchedule = '/schedule/enable/{deviceUuid}'; static const String deleteSchedule = '/schedule/{deviceUuid}/{scheduleId}'; - static const String reportLogs = '/device/report-logs/{deviceUuid}?code={code}&startTime={startTime}&endTime={endTime}'; + static const String reportLogs = + '/device/report-logs/{deviceUuid}?code={code}&startTime={startTime}&endTime={endTime}'; + static const String controlBatch = '/device/control/batch'; } diff --git a/lib/services/api/devices_api.dart b/lib/services/api/devices_api.dart index d0c068c..064f675 100644 --- a/lib/services/api/devices_api.dart +++ b/lib/services/api/devices_api.dart @@ -378,4 +378,29 @@ class DevicesAPI { return response; } + + + static Future deviceController({ + List? devicesUuid, + String? code, + bool? value, + }) async { + try { + final response = await _httpService.post( + path: ApiEndpoints.controlBatch, + body: {"devicesUuid": devicesUuid, "code": code, "value": value}, + showServerMessage: true, + expectedResponseModel: (json) { + print('json-=-=-=-=-=--=${json}'); + return json; + }, + ); + return response; + } catch (e) { + rethrow; + } + } + + + } From 781522d4b606288ab351d1e1918d16c3f15efb51 Mon Sep 17 00:00:00 2001 From: mohammad Date: Thu, 26 Sep 2024 16:36:23 +0300 Subject: [PATCH 2/7] fixes --- .../bloc/water_heater_bloc/water_heater_bloc.dart | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) 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 e1c55ca..1d4c80c 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 @@ -381,14 +381,13 @@ class WaterHeaterBloc extends Bloc { groupTwoGangList.map((device) => device.deviceId).toList(); final response = await DevicesAPI.deviceController( code: 'switch_1', - devicesUuid: allDeviceIds, + devicesUuid: [event.deviceId], value: !event.value, ); - emit(UpdateGroupState( twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); if (!response['success']) { - // add(InitialEvent(groupScreen: twoGangGroup)); + add(InitialWizardEvent()); } } catch (_) { // add(InitialEvent(groupScreen: twoGangGroup)); @@ -470,12 +469,12 @@ class WaterHeaterBloc extends Bloc { // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } catch (_) { // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } @@ -512,12 +511,12 @@ class WaterHeaterBloc extends Bloc { // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } catch (_) { // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } } From 6e32f30970d7d1079423f4f6b0a841e967f04793 Mon Sep 17 00:00:00 2001 From: mohammad Date: Thu, 26 Sep 2024 16:36:54 +0300 Subject: [PATCH 3/7] fixes --- .../devices/bloc/water_heater_bloc/water_heater_bloc.dart | 2 -- 1 file changed, 2 deletions(-) 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 1d4c80c..057b118 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 @@ -377,8 +377,6 @@ class WaterHeaterBloc extends Bloc { allSwitchesValue = false; } }); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); final response = await DevicesAPI.deviceController( code: 'switch_1', devicesUuid: [event.deviceId], From bc1b92cd5c025befc2ddbe5fc5e6b0ff9cfaeb38 Mon Sep 17 00:00:00 2001 From: mohammad Date: Thu, 26 Sep 2024 16:47:19 +0300 Subject: [PATCH 4/7] fixes --- .../bloc/two_gang_bloc/two_gang_bloc.dart | 34 +++++-------------- .../water_heater_bloc/water_heater_bloc.dart | 32 +++++------------ 2 files changed, 16 insertions(+), 50 deletions(-) diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart index 2820da4..99c94ea 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart @@ -376,40 +376,31 @@ class TwoGangBloc extends Bloc { void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { - // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = true; groupTwoGangList[i].secondSwitch = true; } - - // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - - // Get a list of all device IDs List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - // First call for switch_1 final response1 = await DevicesAPI.deviceController( - code: 'switch_1', // Controls first switch for all devices + code: 'switch_1', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Second call for switch_2 final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices + code: 'switch_2', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } } catch (_) { - // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } @@ -418,40 +409,33 @@ class TwoGangBloc extends Bloc { void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { - // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = false; groupTwoGangList[i].secondSwitch = false; } - // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - // Get a list of all device IDs List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - // First call for switch_1 final response1 = await DevicesAPI.deviceController( - code: 'switch_1', // Controls first switch for all devices + code: 'switch_1', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Second call for switch_2 final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices + code: 'switch_2', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } } catch (_) { - // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } @@ -767,6 +751,4 @@ class TwoGangBloc extends Bloc { add(InitialEvent(groupScreen: twoGangGroup)); } } - - } 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 057b118..247c597 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 @@ -360,7 +360,6 @@ class WaterHeaterBloc extends Bloc { ); } - // List devicesList = []; List groupTwoGangList = []; bool allSwitchesOn = true; @@ -438,39 +437,32 @@ class WaterHeaterBloc extends Bloc { GroupAllOnEvent event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { - // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = true; } - // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - // Get a list of all device IDs List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - // First call for switch_1 final response1 = await DevicesAPI.deviceController( - code: 'switch_1', // Controls first switch for all devices + code: 'switch_1', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Second call for switch_2 final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices + code: 'switch_2', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } } catch (_) { - // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } @@ -480,39 +472,31 @@ class WaterHeaterBloc extends Bloc { GroupAllOffEvent event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { - // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) for (int i = 0; i < groupTwoGangList.length; i++) { groupTwoGangList[i].firstSwitch = false; } - - // Emit the state with updated values emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - // Get a list of all device IDs List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - // First call for switch_1 final response1 = await DevicesAPI.deviceController( - code: 'switch_1', // Controls first switch for all devices + code: 'switch_1', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Second call for switch_2 final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices + code: 'switch_2', devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: true, ); - // Check if either response is unsuccessful, then reset to initial state if (!response1['success'] || !response2['success']) { await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } } catch (_) { - // In case of an error, delay and reset the screen to initial state await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } From 8d784f1e95dd8cfe6dc0419afcc7b05aa3e42a6f Mon Sep 17 00:00:00 2001 From: mohammad Date: Fri, 27 Sep 2024 16:58:09 +0300 Subject: [PATCH 5/7] fixes --- .../bloc/water_heater_bloc/water_heater_bloc.dart | 13 +------------ .../bloc/water_heater_bloc/water_heater_state.dart | 5 ----- .../view/widgets/water_heater/wh_wizard.dart | 2 -- lib/features/devices/view/widgets/wizard_page.dart | 3 --- 4 files changed, 1 insertion(+), 22 deletions(-) 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 247c597..3c9f910 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 @@ -285,13 +285,6 @@ class WaterHeaterBloc extends Bloc { } } - // void toggleCreateSchedule() { - // emit(WHLoadingState()); - // createSchedule = !createSchedule; - // selectedDays.clear(); - // selectedTime=DateTime.now(); - // emit(UpdateCreateScheduleState(createSchedule)); - // } void toggleCreateCirculate() { emit(WHLoadingState()); @@ -301,11 +294,7 @@ class WaterHeaterBloc extends Bloc { emit(UpdateCreateScheduleState(createCirculate)); } - // void toggleSelectedIndex(index) { - // emit(WHLoadingState()); - // selectedTabIndex = index; - // emit(ChangeSlidingSegmentState(value: selectedTabIndex)); - // } + void toggleSelectedIndex( ToggleSelectedEvent event, Emitter emit) { emit(WHLoadingState()); diff --git a/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart b/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart index de4c383..241b556 100644 --- a/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart +++ b/lib/features/devices/bloc/water_heater_bloc/water_heater_state.dart @@ -14,13 +14,8 @@ class WHInitialState extends WaterHeaterState {} class WHLoadingState extends WaterHeaterState {} class WHChangeLoading extends WaterHeaterState { - // final WHStatusModel WHStatusModel; const WHChangeLoading( - // {required this. WHStatusModel} ); - - // @override - // List get props => [acStatusModel]; } class WHModifyingState extends WaterHeaterState { diff --git a/lib/features/devices/view/widgets/water_heater/wh_wizard.dart b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart index f63f9db..d755e71 100644 --- a/lib/features/devices/view/widgets/water_heater/wh_wizard.dart +++ b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart @@ -6,9 +6,7 @@ import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/water_heater.dart'; -import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_list.dart'; import 'package:syncrow_app/features/devices/view/widgets/water_heater/wh_list.dart'; -import 'package:syncrow_app/features/menu/bloc/manage_unit_bloc/manage_unit_state.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; diff --git a/lib/features/devices/view/widgets/wizard_page.dart b/lib/features/devices/view/widgets/wizard_page.dart index 93558b0..a23f505 100644 --- a/lib/features/devices/view/widgets/wizard_page.dart +++ b/lib/features/devices/view/widgets/wizard_page.dart @@ -2,11 +2,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:syncrow_app/features/devices/model/device_category_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/ACs/acs_view.dart'; -import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_Interface.dart'; import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_wizard.dart'; -import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_interface.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_wizard.dart'; -import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_Interface.dart'; import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_wizard.dart'; import 'package:syncrow_app/features/devices/view/widgets/water_heater/wh_wizard.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; From 2fb18965f476c052e301b75359c279ca47c40acd Mon Sep 17 00:00:00 2001 From: Abdullah Alassaf Date: Sun, 29 Sep 2024 01:52:17 +0300 Subject: [PATCH 6/7] Bug fixes --- .../bloc/one_gang_bloc/one_gang_bloc.dart | 106 +-- .../bloc/three_gang_bloc/three_gang_bloc.dart | 127 +--- .../bloc/two_gang_bloc/two_gang_bloc.dart | 316 +++------ .../bloc/two_gang_bloc/two_gang_event.dart | 14 +- .../water_heater_bloc/water_heater_bloc.dart | 133 ++-- .../water_heater_bloc/water_heater_event.dart | 26 +- .../widgets/one_gang/one_gang_screen.dart | 266 ++++--- .../widgets/one_gang/one_gang_wizard.dart | 20 +- .../widgets/three_gang/three_gang_screen.dart | 650 +++++++++--------- .../widgets/three_gang/three_gang_wizard.dart | 26 +- .../widgets/two_gang/two_gang_screen.dart | 528 +++++++------- .../widgets/two_gang/two_gang_wizard.dart | 25 +- .../wh_timer_schedule_screen.dart | 271 +++----- .../view/widgets/water_heater/wh_wizard.dart | 20 +- lib/services/api/api_links_endpoints.dart | 28 +- lib/services/api/devices_api.dart | 78 +-- 16 files changed, 1036 insertions(+), 1598 deletions(-) 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 12baacd..1ebe48e 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,8 +26,7 @@ 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); @@ -50,8 +49,7 @@ 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); @@ -70,21 +68,18 @@ class OneGangBloc extends Bloc { _listenToChanges() { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$oneGangId'); + 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; + 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 = OneGangModel.fromJson(statusList); @@ -99,8 +94,7 @@ class OneGangBloc extends Bloc { 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; @@ -125,20 +119,17 @@ 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) { @@ -161,8 +152,7 @@ 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); @@ -251,8 +241,7 @@ 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; @@ -263,13 +252,12 @@ 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( @@ -288,8 +276,7 @@ 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( @@ -318,8 +305,7 @@ class OneGangBloc extends Bloc { // emit(ChangeSlidingSegmentState(value: 1)); // } - void toggleCreateSchedule( - ToggleCreateScheduleEvent event, Emitter emit) { + void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { emit(LoadingInitialState()); createSchedule = !createSchedule; selectedDays.clear(); @@ -343,13 +329,12 @@ class OneGangBloc extends Bloc { selectedDays.add(event.key); } emit(ChangeTimeState()); - add(ChangeSlidingSegment(value: 1)); + add(const ChangeSlidingSegment(value: 1)); } int selectedTabIndex = 0; - void toggleSelectedIndex( - ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex(ToggleSelectedEvent event, Emitter emit) { emit(LoadingInitialState()); selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); @@ -358,8 +343,7 @@ 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 = []; @@ -369,8 +353,7 @@ 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)); @@ -392,16 +375,15 @@ 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; @@ -413,17 +395,16 @@ class OneGangBloc extends Bloc { allSwitchesValue = false; } }); - // List allDeviceIds = - // groupOneGangList.map((device) => device.deviceId).toList(); - final response = await DevicesAPI.deviceController( + + emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: allSwitchesValue)); + + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: [event.deviceId], value: !event.value, ); - emit(UpdateGroupState( - oneGangList: groupOneGangList, allSwitches: allSwitchesValue)); - if (!response['success']) { + if (response['failedResults'].toString() != '[]') { add(InitialEvent(groupScreen: oneGangGroup)); } } catch (_) { @@ -443,25 +424,16 @@ 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 response1 = await DevicesAPI.deviceController( + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', // Controls first switch for all devices devicesUuid: allDeviceIds, value: true, // true (on) or false (off) depending on the event value ); - - // Second call for switch_2 - final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices - devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value - ); - // Check if either response is unsuccessful, then reset to initial state - if (!response1['success'] || !response2['success']) { + if (response['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } @@ -484,25 +456,17 @@ 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 response1 = await DevicesAPI.deviceController( + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', // Controls first switch for all devices devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value - ); - - // Second call for switch_2 - final response2 = await DevicesAPI.deviceController( - code: 'switch_2', // Controls second switch for all devices - devicesUuid: allDeviceIds, - value: true, // true (on) or false (off) depending on the event value + value: false, // true (on) or false (off) depending on the event value ); // Check if either response is unsuccessful, then reset to initial state - if (!response1['success'] || !response2['success']) { + if (response['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); add(const InitialEvent(groupScreen: true)); } 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 97b281e..2066b10 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 @@ -25,9 +25,6 @@ class ThreeGangBloc extends Bloc { secondCountDown: 0, thirdCountDown: 0); Timer? _timer; - // Timer? _firstSwitchTimer; - // Timer? _secondSwitchTimer; - // Timer? _thirdSwitchTimer; bool threeGangGroup = false; List devicesList = []; @@ -380,18 +377,15 @@ class ThreeGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, - code: 'switch_1', value: false), + deviceId: groupThreeGangList[i].deviceId, code: 'switch_1', value: false), groupThreeGangList[i].deviceId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, - code: 'switch_2', value: false), + deviceId: groupThreeGangList[i].deviceId, code: 'switch_2', value: false), groupThreeGangList[i].deviceId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: groupThreeGangList[i].deviceId, - code: 'switch_3', value: false), + deviceId: groupThreeGangList[i].deviceId, code: 'switch_3', value: false), groupThreeGangList[i].deviceId), ]); @@ -534,7 +528,7 @@ class ThreeGangBloc extends Bloc { CustomSnackBar.displaySnackBar('Save Successfully'); add(GetScheduleEvent()); emit(ThreeGangSaveSchedule()); - add(const ToggleCreateScheduleEvent(index:1 )); + add(const ToggleCreateScheduleEvent(index: 1)); } else { CustomSnackBar.displaySnackBar('Please select days'); } @@ -609,38 +603,19 @@ class ThreeGangBloc extends Bloc { } } - // void toggleCreateSchedule() { - // emit(LoadingInitialState()); - // createSchedule = !createSchedule; - // selectedDays.clear(); - // selectedTime = DateTime.now(); - // emit(UpdateCreateScheduleState(createSchedule)); - // emit(ChangeSlidingSegmentState(value: 1)); - // } - - - - // void toggleSelectedIndex(index) { - // emit(LoadingInitialState()); - // selectedTabIndex = index; - // emit(ChangeSlidingSegmentState(value: selectedTabIndex)); - // } - - - void toggleSelectedIndex( ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex(ToggleSelectedEvent event, Emitter emit) { emit(LoadingInitialState()); - selectedTabIndex =event.index; + selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); } - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { - emit(LoadingInitialState()); - createSchedule = !createSchedule; - selectedDays.clear(); - selectedTime = DateTime.now(); - emit(UpdateCreateScheduleState(createSchedule)); -} - + void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { + emit(LoadingInitialState()); + createSchedule = !createSchedule; + selectedDays.clear(); + selectedTime = DateTime.now(); + emit(UpdateCreateScheduleState(createSchedule)); + } int selectedTabIndex = 0; bool toggleSchedule = true; @@ -648,80 +623,4 @@ class ThreeGangBloc extends Bloc { bool createSchedule = false; List listSchedule = []; DateTime? selectedTime = DateTime.now(); - - -// void _changeFirstSwitchWizard( ChangeFirstSwitchStatusEventWizard event, Emitter emit) async { -// emit(LoadingNewSate(threeGangModel: deviceStatus)); -// try { -// bool allSwitchesValue = true; -// groupThreeGangList.forEach((element) { -// if (element.deviceId == event.deviceId) { -// element.firstSwitch = !event.value; -// } -// if (!element.firstSwitch || -// !element.secondSwitch || -// !element.thirdSwitch) { -// allSwitchesValue = false; -// } -// }); -// emit(UpdateGroupState( -// threeGangList: groupThreeGangList, allSwitches: allSwitchesValue)); - -// if (_timer != null) { -// _timer!.cancel(); -// } -// _timer = Timer(const Duration(milliseconds: 100), () async { -// final response = await DevicesAPI.controlDevice( -// DeviceControlModel( -// deviceId: event.deviceId , -// code: 'switch_1', -// value: event.value), -// event.deviceId ); -// if (!response['success']) { -// add(InitialEvent(groupScreen: threeGangGroup)); -// } -// }); -// } catch (_) { -// add(InitialEvent(groupScreen: threeGangGroup)); -// } -// } - -// Future fetchGroupDevises( -// InitialWizardDevises event, Emitter emit) async { -// emit(LoadingInitialState()); -// devicesList = []; -// listDevises = []; -// allSwitchesOn = true; -// devicesList = await DevicesAPI.getDeviceByGroupName( -// HomeCubit.getInstance().selectedSpace?.id ?? '', '3G'); - -// for (int i = 0; i < devicesList.length; i++) { -// var response = -// await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); -// List statusModelList = []; -// for (var status in response['status']) { -// statusModelList.add(StatusModel.fromJson(status)); -// } -// deviceStatus = ThreeGangModel.fromJson(statusModelList); - -// listDevises.add(GroupThreeGangModel( -// secondSwitch: deviceStatus.secondSwitch, -// thirdSwitch: deviceStatus.thirdSwitch, -// deviceId: devicesList[i].uuid ?? '', -// deviceName: devicesList[i].name ?? '', -// firstSwitch: deviceStatus.firstSwitch, -// )); -// } -// if (listDevises.isNotEmpty) { -// listDevises.firstWhere((element) { -// if (!element.firstSwitch) { -// allSwitchesOn = false; -// } -// return true; -// }); -// } -// emit(UpdateGroupState( -// threeGangList: listDevises, allSwitches: allSwitchesOn)); -// } - } diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart index 99c94ea..ce44b9f 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart @@ -35,8 +35,7 @@ class TwoGangBloc extends Bloc { bool createSchedule = false; List listSchedule = []; - TwoGangBloc({required this.twoGangId, required this.switchCode}) - : super(InitialState()) { + TwoGangBloc({required this.twoGangId, required this.switchCode}) : super(InitialState()) { on(_fetchTwoGangStatus); on(_twoGangUpdated); on(_changeFirstSwitch); @@ -64,32 +63,15 @@ class TwoGangBloc extends Bloc { DateTime? selectedTime = DateTime.now(); - // void toggleCreateSchedule() { - // emit(LoadingInitialState()); - // createSchedule = !createSchedule; - // selectedDays.clear(); - // selectedTime = DateTime.now(); - // emit(UpdateCreateScheduleState(createSchedule)); - // emit(ChangeSlidingSegmentState(value: 1)); - // } - int selectedTabIndex = 0; - // void toggleSelectedIndex(index) { - // emit(LoadingInitialState()); - // selectedTabIndex = index; - // emit(ChangeSlidingSegmentState(value: selectedTabIndex)); - // } - - void toggleSelectedIndex( - ToggleSelectedEvent event, Emitter emit) { + void toggleSelectedIndex(ToggleSelectedEvent event, Emitter emit) { emit(LoadingInitialState()); selectedTabIndex = event.index; emit(ChangeSlidingSegmentState(value: selectedTabIndex)); } - void toggleCreateSchedule( - ToggleCreateScheduleEvent event, Emitter emit) { + void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { emit(LoadingInitialState()); createSchedule = !createSchedule; selectedDays.clear(); @@ -97,55 +79,17 @@ class TwoGangBloc extends Bloc { emit(UpdateCreateScheduleState(createSchedule)); } - void _fetchTwoGangStatus( - InitialEvent event, Emitter emit) async { + void _fetchTwoGangStatus(InitialEvent event, Emitter emit) async { emit(LoadingInitialState()); try { - twoGangGroup = event.groupScreen; - if (twoGangGroup) { - devicesList = []; - groupTwoGangList = []; - allSwitchesOn = true; - devicesList = await DevicesAPI.getDeviceByGroupName( - HomeCubit.getInstance().selectedSpace?.id ?? '', '2G'); - - for (int i = 0; i < devicesList.length; i++) { - var response = - await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? ''); - List statusModelList = []; - for (var status in response['status']) { - statusModelList.add(StatusModel.fromJson(status)); - } - deviceStatus = TwoGangModel.fromJson(statusModelList); - - groupTwoGangList.add(GroupTwoGangModel( - deviceId: devicesList[i].uuid ?? '', - deviceName: devicesList[i].name ?? '', - firstSwitch: deviceStatus.firstSwitch, - secondSwitch: deviceStatus.secondSwitch, - )); - } - - if (groupTwoGangList.isNotEmpty) { - groupTwoGangList.firstWhere((element) { - if (!element.firstSwitch || !element.secondSwitch) { - allSwitchesOn = false; - } - return true; - }); - } - emit(UpdateGroupState( - twoGangList: groupTwoGangList, allSwitches: allSwitchesOn)); - } else { - var response = await DevicesAPI.getDeviceStatus(twoGangId); - List statusModelList = []; - for (var status in response['status']) { - statusModelList.add(StatusModel.fromJson(status)); - } - deviceStatus = TwoGangModel.fromJson(statusModelList); - emit(UpdateState(twoGangModel: deviceStatus)); - _listenToChanges(); + var response = await DevicesAPI.getDeviceStatus(twoGangId); + List statusModelList = []; + for (var status in response['status']) { + statusModelList.add(StatusModel.fromJson(status)); } + deviceStatus = TwoGangModel.fromJson(statusModelList); + emit(UpdateState(twoGangModel: deviceStatus)); + _listenToChanges(); } catch (e) { emit(FailedState(error: e.toString())); return; @@ -154,21 +98,18 @@ class TwoGangBloc extends Bloc { _listenToChanges() { try { - DatabaseReference ref = - FirebaseDatabase.instance.ref('device-status/$twoGangId'); + DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$twoGangId'); 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; + 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 = TwoGangModel.fromJson(statusList); @@ -183,8 +124,7 @@ class TwoGangBloc extends Bloc { emit(UpdateState(twoGangModel: deviceStatus)); } - void _changeFirstSwitch( - ChangeFirstSwitchStatusEvent event, Emitter emit) async { + void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.value; @@ -195,23 +135,19 @@ class TwoGangBloc extends Bloc { _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: twoGangGroup ? event.deviceId : twoGangId, - code: 'switch_1', - value: !event.value), - twoGangGroup ? event.deviceId : twoGangId); + DeviceControlModel(deviceId: twoGangId, code: 'switch_1', value: !event.value), + twoGangId); if (!response['success']) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(const InitialEvent()); } }); } catch (_) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(const InitialEvent()); } } - void _changeSecondSwitch( - ChangeSecondSwitchStatusEvent event, Emitter emit) async { + void _changeSecondSwitch(ChangeSecondSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { deviceStatus.secondSwitch = !event.value; @@ -221,18 +157,15 @@ class TwoGangBloc extends Bloc { } _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: twoGangGroup ? event.deviceId : twoGangId, - code: 'switch_2', - value: !event.value), - twoGangGroup ? event.deviceId : twoGangId); + DeviceControlModel(deviceId: twoGangId, code: 'switch_2', value: !event.value), + twoGangId); if (!response['success']) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(const InitialEvent()); } }); } catch (_) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(const InitialEvent()); } } @@ -247,25 +180,21 @@ class TwoGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, - code: 'switch_1', - value: deviceStatus.firstSwitch), + deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch), twoGangId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, - code: 'switch_2', - value: deviceStatus.secondSwitch), + deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch), twoGangId), ]); if (response.every((element) => !element['success'])) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: false)); + add(const InitialEvent()); } } catch (_) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: false)); + add(const InitialEvent()); } } @@ -278,101 +207,23 @@ class TwoGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, - code: 'switch_1', - value: deviceStatus.firstSwitch), + deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch), twoGangId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, - code: 'switch_2', - value: deviceStatus.secondSwitch), + deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch), twoGangId), ]); if (response.every((element) => !element['success'])) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: false)); + add(const InitialEvent()); } } catch (_) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: false)); + add(const InitialEvent()); } } - // void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { - // emit(LoadingNewSate(twoGangModel: deviceStatus)); - // try { - // for (int i = 0; i < groupTwoGangList.length; i++) { - // groupTwoGangList[i].firstSwitch = true; - // groupTwoGangList[i].secondSwitch = true; - // } - // emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - - // for (int i = 0; i < groupTwoGangList.length; i++) { - // final response = await Future.wait([ - // DevicesAPI.controlDevice( - // DeviceControlModel( - // deviceId: groupTwoGangList[i].deviceId, - // code: 'switch_1', - // value: true), - // groupTwoGangList[i].deviceId), - // DevicesAPI.controlDevice( - // DeviceControlModel( - // deviceId: groupTwoGangList[i].deviceId, - // code: 'switch_2', - // value: true), - // groupTwoGangList[i].deviceId), - // ]); - - // if (response.every((element) => !element['success'])) { - // await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); - // break; - // } - // } - // } catch (_) { - // await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); - // } - // } - - // void _groupAllOff(GroupAllOffEvent event, Emitter emit) async { - // emit(LoadingNewSate(twoGangModel: deviceStatus)); - // try { - // for (int i = 0; i < groupTwoGangList.length; i++) { - // groupTwoGangList[i].firstSwitch = false; - // groupTwoGangList[i].secondSwitch = false; - // } - // emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - - // for (int i = 0; i < groupTwoGangList.length; i++) { - // final response = await Future.wait([ - // DevicesAPI.controlDevice( - // DeviceControlModel( - // deviceId: groupTwoGangList[i].deviceId, - // code: 'switch_1', - // value: false), - // groupTwoGangList[i].deviceId), - // DevicesAPI.controlDevice( - // DeviceControlModel( - // deviceId: groupTwoGangList[i].deviceId, - // code: 'switch_2', - // value: false), - // groupTwoGangList[i].deviceId), - // ]); - - // if (response.every((element) => !element['success'])) { - // await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); - // break; - // } - // } - // } catch (_) { - // await Future.delayed(const Duration(milliseconds: 500)); - // add(const InitialEvent(groupScreen: true)); - // } - // } - void _groupAllOn(GroupAllOnEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { @@ -381,28 +232,28 @@ class TwoGangBloc extends Bloc { groupTwoGangList[i].secondSwitch = true; } emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - final response1 = await DevicesAPI.deviceController( + final response1 = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, value: true, ); - final response2 = await DevicesAPI.deviceController( + final response2 = await DevicesAPI.deviceBatchController( code: 'switch_2', devicesUuid: allDeviceIds, value: true, ); - if (!response1['success'] || !response2['success']) { + if (response1['failedResults'].toString() != '[]' || + response2['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } catch (_) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } @@ -416,45 +267,42 @@ class TwoGangBloc extends Bloc { emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - final response1 = await DevicesAPI.deviceController( + final response1 = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, value: true, ); - final response2 = await DevicesAPI.deviceController( + final response2 = await DevicesAPI.deviceBatchController( code: 'switch_2', devicesUuid: allDeviceIds, value: true, ); - if (!response1['success'] || !response2['success']) { + if (response1['failedResults'].toString() != '[]' || + response2['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } catch (_) { await Future.delayed(const Duration(milliseconds: 500)); - add(const InitialEvent(groupScreen: true)); + add(InitialWizardEvent()); } } - 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(twoGangModel: deviceStatus)); int seconds = 0; try { seconds = event.duration.inSeconds; final response = await DevicesAPI.controlDevice( - DeviceControlModel( - deviceId: twoGangId, code: event.deviceCode, value: seconds), + DeviceControlModel(deviceId: twoGangId, code: event.deviceCode, value: seconds), twoGangId); if (response['success'] ?? false) { @@ -479,8 +327,7 @@ class TwoGangBloc extends Bloc { } } - void _getCounterValue( - GetCounterEvent event, Emitter emit) async { + void _getCounterValue(GetCounterEvent event, Emitter emit) async { emit(LoadingInitialState()); try { add(GetScheduleEvent()); @@ -547,7 +394,7 @@ class TwoGangBloc extends Bloc { selectedDays.add(event.key); } emit(ChangeTimeState()); - add(ChangeSlidingSegment(value: 1)); + add(const ChangeSlidingSegment(value: 1)); } Future saveSchedule( @@ -557,7 +404,7 @@ class TwoGangBloc extends Bloc { try { if (selectedDays.isNotEmpty) { emit(LoadingInitialState()); - final response = await DevicesAPI.postSchedule( + await DevicesAPI.postSchedule( category: switchCode, deviceId: twoGangId, time: getTimeStampWithoutSeconds(selectedTime).toString(), @@ -588,8 +435,7 @@ class TwoGangBloc extends Bloc { deviceId: twoGangId, ); 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; @@ -600,13 +446,12 @@ class TwoGangBloc 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 toggleRepeat( - ToggleScheduleEvent event, Emitter emit) async { + Future toggleRepeat(ToggleScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.changeSchedule( @@ -625,8 +470,7 @@ class TwoGangBloc extends Bloc { } } - Future deleteSchedule( - DeleteScheduleEvent event, Emitter emit) async { + Future deleteSchedule(DeleteScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.deleteSchedule( @@ -646,8 +490,7 @@ class TwoGangBloc extends Bloc { } } - void _fetchTwoGangWizardStatus( - InitialWizardEvent event, Emitter emit) async { + void _fetchTwoGangWizardStatus(InitialWizardEvent event, Emitter emit) async { emit(LoadingInitialState()); try { devicesList = []; @@ -657,8 +500,7 @@ class TwoGangBloc extends Bloc { HomeCubit.getInstance().selectedSpace?.id ?? '', '2G'); 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)); @@ -681,16 +523,15 @@ class TwoGangBloc extends Bloc { return true; }); } - emit(UpdateGroupState( - twoGangList: groupTwoGangList, allSwitches: allSwitchesOn)); + emit(UpdateGroupState(twoGangList: groupTwoGangList, 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(twoGangModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -702,26 +543,26 @@ class TwoGangBloc extends Bloc { allSwitchesValue = false; } }); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); - final response = await DevicesAPI.deviceController( + + emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + + List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, value: !event.value, ); - emit(UpdateGroupState( - twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); - if (!response['success']) { - add(InitialEvent(groupScreen: twoGangGroup)); + if (response['failedResults'].toString() != '[]') { + add(InitialWizardEvent()); } } catch (_) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(InitialWizardEvent()); } } - void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event, - Emitter emit) async { + void _changeSecondWizardSwitch( + ChangeSecondWizardSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -733,22 +574,21 @@ class TwoGangBloc extends Bloc { allSwitchesValue = false; } }); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); - final response = await DevicesAPI.deviceController( + emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + + final response = await DevicesAPI.deviceBatchController( code: 'switch_2', devicesUuid: allDeviceIds, value: !event.value, ); - emit(UpdateGroupState( - twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); if (response['failedResults'].toString() != '[]') { - add(InitialEvent(groupScreen: twoGangGroup)); + add(InitialWizardEvent()); } } catch (_) { - add(InitialEvent(groupScreen: twoGangGroup)); + add(InitialWizardEvent()); } } } diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart index 0555ad0..be8ac0e 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_event.dart @@ -32,10 +32,9 @@ class ToggleDaySelectionEvent extends TwoGangEvent { } class InitialEvent extends TwoGangEvent { - final bool groupScreen; - const InitialEvent({required this.groupScreen}); + const InitialEvent(); @override - List get props => [groupScreen]; + List get props => []; } class ChangeFirstSwitchStatusEvent extends TwoGangEvent { @@ -49,8 +48,7 @@ class ChangeFirstSwitchStatusEvent extends TwoGangEvent { class ChangeSecondSwitchStatusEvent extends TwoGangEvent { final bool value; final String deviceId; - const ChangeSecondSwitchStatusEvent( - {required this.value, this.deviceId = ''}); + const ChangeSecondSwitchStatusEvent({required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } @@ -143,8 +141,7 @@ class InitialWizardEvent extends TwoGangEvent {} class ChangeFirstWizardSwitchStatusEvent extends TwoGangEvent { final bool value; final String deviceId; - const ChangeFirstWizardSwitchStatusEvent( - {required this.value, this.deviceId = ''}); + const ChangeFirstWizardSwitchStatusEvent({required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } @@ -152,8 +149,7 @@ class ChangeFirstWizardSwitchStatusEvent extends TwoGangEvent { class ChangeSecondWizardSwitchStatusEvent extends TwoGangEvent { final bool value; final String deviceId; - const ChangeSecondWizardSwitchStatusEvent( - {required this.value, this.deviceId = ''}); + const ChangeSecondWizardSwitchStatusEvent({required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } 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 3c9f910..97220c6 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 @@ -34,8 +34,7 @@ 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); @@ -56,10 +55,10 @@ class WaterHeaterBloc extends Bloc { on(_groupAllOn); on(_groupAllOff); + on(_toggleCreateCirculate); } - void _fetchWaterHeaterStatus( - WaterHeaterInitial event, Emitter emit) async { + void _fetchWaterHeaterStatus(WaterHeaterInitial event, Emitter emit) async { emit(WHLoadingState()); try { var response = await DevicesAPI.getDeviceStatus(whId); @@ -79,8 +78,7 @@ class WaterHeaterBloc extends Bloc { } } - void _changeFirstSwitch( - WaterHeaterSwitch event, Emitter emit) async { + void _changeFirstSwitch(WaterHeaterSwitch event, Emitter emit) async { emit(LoadingNewSate(whModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.whSwitch; @@ -90,10 +88,7 @@ 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']) { @@ -107,16 +102,13 @@ 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') { @@ -138,8 +130,7 @@ 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); @@ -199,7 +190,7 @@ class WaterHeaterBloc extends Bloc { try { if (selectedDays.isNotEmpty) { emit(WHLoadingState()); - final response = await DevicesAPI.postSchedule( + await DevicesAPI.postSchedule( category: switchCode, deviceId: whId, time: getTimeStampWithoutSeconds(selectedTime).toString(), @@ -229,8 +220,7 @@ 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; @@ -241,13 +231,12 @@ 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( @@ -265,8 +254,7 @@ 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( @@ -285,8 +273,7 @@ class WaterHeaterBloc extends Bloc { } } - - void toggleCreateCirculate() { + void _toggleCreateCirculate(ToggleCreateCirculate event, Emitter emit) { emit(WHLoadingState()); createCirculate = !createCirculate; selectedDays.clear(); @@ -294,16 +281,13 @@ 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(); @@ -327,7 +311,7 @@ class WaterHeaterBloc extends Bloc { int selectedTabIndex = 0; showTime(SelectTimeEvent event, Emitter emit) async { - final TimeOfDay? timePicked = await showTimePicker( + await showTimePicker( context: event.context, initialTime: TimeOfDay.now(), builder: (context, child) { @@ -349,15 +333,15 @@ class WaterHeaterBloc extends Bloc { ); } - List groupTwoGangList = []; + 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; - groupTwoGangList.forEach((element) { + groupWaterHeaterList.forEach((element) { if (element.deviceId == event.deviceId) { element.firstSwitch = !event.value; } @@ -365,89 +349,78 @@ class WaterHeaterBloc extends Bloc { allSwitchesValue = false; } }); - final response = await DevicesAPI.deviceController( + emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: allSwitchesValue)); + + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: [event.deviceId], value: !event.value, ); - emit(UpdateGroupState( - twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); - if (!response['success']) { + if (response['failedResults'].toString() != '[]') { add(InitialWizardEvent()); } } catch (_) { - // add(InitialEvent(groupScreen: twoGangGroup)); + add(InitialWizardEvent()); } } - void _fetchWHWizardStatus( - InitialWizardEvent event, Emitter emit) async { + void _fetchWHWizardStatus(InitialWizardEvent event, Emitter emit) async { emit(WHLoadingState()); try { devicesList = []; - groupTwoGangList = []; + groupWaterHeaterList = []; allSwitchesOn = true; devicesList = await DevicesAPI.getDeviceByGroupName( 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)); } deviceStatus = WHModel.fromJson(statusModelList); - groupTwoGangList.add(GroupWHModel( + groupWaterHeaterList.add(GroupWHModel( deviceId: devicesList[i].uuid ?? '', deviceName: devicesList[i].name ?? '', firstSwitch: deviceStatus.firstSwitch, )); } - if (groupTwoGangList.isNotEmpty) { - groupTwoGangList.firstWhere((element) { + if (groupWaterHeaterList.isNotEmpty) { + groupWaterHeaterList.firstWhere((element) { if (!element.firstSwitch) { allSwitchesOn = false; } return true; }); } - emit(UpdateGroupState( - twoGangList: groupTwoGangList, 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 < groupTwoGangList.length; i++) { - groupTwoGangList[i].firstSwitch = true; + for (int i = 0; i < groupWaterHeaterList.length; i++) { + groupWaterHeaterList[i].firstSwitch = true; } - emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); + emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: true)); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList(); - final response1 = await DevicesAPI.deviceController( + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, value: true, ); - final response2 = await DevicesAPI.deviceController( - code: 'switch_2', - devicesUuid: allDeviceIds, - value: true, - ); - - if (!response1['success'] || !response2['success']) { + if (response['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } @@ -457,31 +430,23 @@ 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 < groupTwoGangList.length; i++) { - groupTwoGangList[i].firstSwitch = false; + for (int i = 0; i < groupWaterHeaterList.length; i++) { + groupWaterHeaterList[i].firstSwitch = false; } - emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); + emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: false)); - List allDeviceIds = - groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList(); - final response1 = await DevicesAPI.deviceController( + final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, - value: true, + value: false, ); - final response2 = await DevicesAPI.deviceController( - code: 'switch_2', - devicesUuid: allDeviceIds, - value: true, - ); - - if (!response1['success'] || !response2['success']) { + if (response['failedResults'].toString() != '[]') { await Future.delayed(const Duration(milliseconds: 500)); add(InitialWizardEvent()); } diff --git a/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart b/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart index 0cd2d37..6e3d05a 100644 --- a/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart +++ b/lib/features/devices/bloc/water_heater_bloc/water_heater_event.dart @@ -28,7 +28,6 @@ class WaterHeaterInitial extends WaterHeaterEvent { class WaterHeaterChangeStatus extends WaterHeaterEvent {} - class GetCounterEvent extends WaterHeaterEvent { final String deviceCode; const GetCounterEvent({required this.deviceCode}); @@ -66,25 +65,27 @@ class StopTimer extends WaterHeaterEvent {} class OnClose extends WaterHeaterEvent {} - //------------------- Schedule ----------=--------- class GetScheduleEvent extends WaterHeaterEvent {} + class ScheduleSave extends WaterHeaterEvent {} + class ToggleScheduleEvent extends WaterHeaterEvent { final String id; final bool toggle; - const ToggleScheduleEvent({required this.toggle,required this.id}); + const ToggleScheduleEvent({required this.toggle, required this.id}); @override - List get props => [toggle,id]; + List get props => [toggle, id]; } -class ToggleDaySelectionEvent extends WaterHeaterEvent { +class ToggleDaySelectionEvent extends WaterHeaterEvent { final String key; const ToggleDaySelectionEvent({required this.key}); @override List get props => [key]; } + class DeleteScheduleEvent extends WaterHeaterEvent { final String id; const DeleteScheduleEvent({required this.id}); @@ -100,7 +101,6 @@ class SelectTimeEvent extends WaterHeaterEvent { List get props => [context, isEffective]; } - class ToggleSelectedEvent extends WaterHeaterEvent { final int index; const ToggleSelectedEvent({required this.index}); @@ -108,7 +108,6 @@ class ToggleSelectedEvent extends WaterHeaterEvent { List get props => [index]; } - class ToggleCreateScheduleEvent extends WaterHeaterEvent { final int index; const ToggleCreateScheduleEvent({required this.index}); @@ -116,28 +115,25 @@ class ToggleCreateScheduleEvent extends WaterHeaterEvent { List get props => [index]; } - -class ToggleCreateCirculateEvent extends WaterHeaterEvent { +class ToggleCreateCirculateEvent extends WaterHeaterEvent { final int index; const ToggleCreateCirculateEvent({required this.index}); @override List get props => [index]; } - - class InitialWizardEvent extends WaterHeaterEvent {} class ChangeFirstWizardSwitchStatusEvent extends WaterHeaterEvent { final bool value; final String deviceId; - const ChangeFirstWizardSwitchStatusEvent( - {required this.value, this.deviceId = ''}); + const ChangeFirstWizardSwitchStatusEvent({required this.value, this.deviceId = ''}); @override List get props => [value, deviceId]; } - class GroupAllOnEvent extends WaterHeaterEvent {} -class GroupAllOffEvent extends WaterHeaterEvent {} \ No newline at end of file +class GroupAllOffEvent extends WaterHeaterEvent {} + +class ToggleCreateCirculate extends WaterHeaterEvent {} diff --git a/lib/features/devices/view/widgets/one_gang/one_gang_screen.dart b/lib/features/devices/view/widgets/one_gang/one_gang_screen.dart index 2bc3353..5474ece 100644 --- a/lib/features/devices/view/widgets/one_gang/one_gang_screen.dart +++ b/lib/features/devices/view/widgets/one_gang/one_gang_screen.dart @@ -3,9 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_bloc.dart'; import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; -import 'package:syncrow_app/features/devices/model/group_one_gang_model.dart'; import 'package:syncrow_app/features/devices/model/one_gang_model.dart'; -import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_list.dart'; import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_timer_screen.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/gang_switch.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; @@ -22,9 +20,8 @@ class OneGangScreen extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => - OneGangBloc(switchCode: 'switch_1', oneGangId: device?.uuid ?? '') - ..add(const InitialEvent(groupScreen: false)), + create: (context) => OneGangBloc(switchCode: 'switch_1', oneGangId: device?.uuid ?? '') + ..add(const InitialEvent(groupScreen: false)), child: BlocBuilder( builder: (context, state) { OneGangModel oneGangModel = OneGangModel( @@ -32,164 +29,135 @@ class OneGangScreen extends StatelessWidget { firstCountDown: 0, ); - List groupOneGangModel = []; - bool allSwitchesOn = false; - if (state is LoadingNewSate) { oneGangModel = state.oneGangModel; } else if (state is UpdateState) { oneGangModel = state.oneGangModel; - } else if (state is UpdateGroupState) { - groupOneGangModel = state.oneGangList; - allSwitchesOn = state.allSwitches; } return state is LoadingInitialState ? const Center( - child: DefaultContainer( - width: 50, - height: 50, - child: CircularProgressIndicator()), + child: + DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) - : device == null - ? OneGangList( - oneGangList: groupOneGangModel, - allSwitches: allSwitchesOn) - : RefreshIndicator( - onRefresh: () async { - BlocProvider.of(context).add(InitialEvent( - groupScreen: device != null ? false : true)); - }, - child: ListView( - children: [ - SizedBox( - height: MediaQuery.of(context).size.height, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Expanded(child: SizedBox.shrink()), - Expanded( - child: Row( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - crossAxisAlignment: - CrossAxisAlignment.center, + : RefreshIndicator( + onRefresh: () async { + BlocProvider.of(context) + .add(InitialEvent(groupScreen: device != null ? false : true)); + }, + child: ListView( + children: [ + SizedBox( + height: MediaQuery.of(context).size.height, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Expanded(child: SizedBox.shrink()), + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( children: [ - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: oneGangModel.firstSwitch, - action: () { - BlocProvider.of( - context) - .add( - ChangeFirstSwitchStatusEvent( - value: oneGangModel - .firstSwitch)); - }, - ), - const SizedBox(height: 20), - const SizedBox( - width: 70, - child: BodySmall( - text: " Entrance Light", - fontColor: ColorsManager - .textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], + GangSwitch( + threeGangSwitch: device!, + value: oneGangModel.firstSwitch, + action: () { + BlocProvider.of(context).add( + ChangeFirstSwitchStatusEvent( + value: oneGangModel.firstSwitch)); + }, + ), + const SizedBox(height: 20), + const SizedBox( + width: 70, + child: BodySmall( + text: " Entrance Light", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), ), ], ), - ), - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - Navigator.push( - context, - PageRouteBuilder( - pageBuilder: (context, - animation1, - animation2) => - TimerScheduleScreen( - switchCode: - 'switch_1', - device: device!, - deviceCode: - 'countdown_1', - ))); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: - BorderRadius.circular( - 100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: - BorderRadius.circular( - 100), - ), - child: Center( - child: Icon( - Icons.access_time, - color: ColorsManager - .primaryColorWithOpacity, - size: 25, - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 10), - BodySmall( - text: "Timer", - style: context.bodyMedium.copyWith( - color: ColorsManager - .textPrimaryColor, - ), - ), - ], - ), - ], - ), - ), - Expanded(child: SizedBox()) - ], + ], + ), ), - ), - ], + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: + (context, animation1, animation2) => + TimerScheduleScreen( + switchCode: 'switch_1', + device: device!, + deviceCode: 'countdown_1', + ))); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: Icon( + Icons.access_time, + color: ColorsManager.primaryColorWithOpacity, + size: 25, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + BodySmall( + text: "Timer", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), + ), + ], + ), + ], + ), + ), + Expanded(child: SizedBox()) + ], + ), ), - ); + ], + ), + ); }, ), ); diff --git a/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart b/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart index 98f6645..92013ed 100644 --- a/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart +++ b/lib/features/devices/view/widgets/one_gang/one_gang_wizard.dart @@ -5,7 +5,6 @@ import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_event.d import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/group_one_gang_model.dart'; -import 'package:syncrow_app/features/devices/model/one_gang_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/one_gang/one_gang_list.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; @@ -22,30 +21,19 @@ class OneGangWizard extends StatelessWidget { return DefaultScaffold( child: BlocProvider( create: (context) => - OneGangBloc(switchCode: '', oneGangId: device?.uuid ?? '') - ..add(InitialWizardEvent()), + OneGangBloc(switchCode: '', oneGangId: device?.uuid ?? '')..add(InitialWizardEvent()), child: BlocBuilder( builder: (context, state) { - OneGangModel oneGangModel = OneGangModel( - firstSwitch: false, - firstCountDown: 0, - ); bool allSwitchesOn = false; - if (state is LoadingNewSate) { - oneGangModel = state.oneGangModel; - } else if (state is UpdateState) { - oneGangModel = state.oneGangModel; - } else if (state is UpdateGroupState) { + if (state is UpdateGroupState) { groupOneGangModel = state.oneGangList; allSwitchesOn = state.allSwitches; } return state is LoadingInitialState ? const Center( - child: DefaultContainer( - width: 50, - height: 50, - child: CircularProgressIndicator()), + child: + DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) : OneGangList( oneGangList: groupOneGangModel, diff --git a/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart b/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart index 084ecf2..1545848 100644 --- a/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart +++ b/lib/features/devices/view/widgets/three_gang/three_gang_screen.dart @@ -4,11 +4,9 @@ import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_blo import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_event.dart'; import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; -import 'package:syncrow_app/features/devices/model/group_three_gang_model.dart'; import 'package:syncrow_app/features/devices/model/three_gang_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/gang_switch.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/schedule_screen.dart'; -import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_list.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart'; import 'package:syncrow_app/utils/context_extension.dart'; @@ -22,9 +20,7 @@ class ThreeGangScreen extends StatelessWidget { @override Widget build(BuildContext context) { return BlocProvider( - create: (context) => ThreeGangBloc( - switchCode: '', - threeGangId: device?.uuid ?? '') + create: (context) => ThreeGangBloc(switchCode: '', threeGangId: device?.uuid ?? '') ..add(InitialEvent(groupScreen: device != null ? false : true)), child: BlocBuilder( builder: (context, state) { @@ -36,360 +32,354 @@ class ThreeGangScreen extends StatelessWidget { secondCountDown: 0, thirdCountDown: 0); - List groupThreeGangModel = []; - bool allSwitchesOn = false; - if (state is LoadingNewSate) { threeGangModel = state.threeGangModel; } else if (state is UpdateState) { threeGangModel = state.threeGangModel; - } else if (state is UpdateGroupState) { - groupThreeGangModel = state.threeGangList; - allSwitchesOn = state.allSwitches; } return state is LoadingInitialState ? const Center( child: DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), - ) : RefreshIndicator( - onRefresh: () async { - BlocProvider.of(context) - .add(InitialEvent(groupScreen: device != null ? false : true)); - }, - child: ListView( - children: [ - SizedBox( - height: MediaQuery.of(context).size.height, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Expanded(child: SizedBox.shrink()), - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.center, + ) + : RefreshIndicator( + onRefresh: () async { + BlocProvider.of(context) + .add(InitialEvent(groupScreen: device != null ? false : true)); + }, + child: ListView( + children: [ + SizedBox( + height: MediaQuery.of(context).size.height, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Expanded(child: SizedBox.shrink()), + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( children: [ - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: threeGangModel.firstSwitch, - action: () { - BlocProvider.of(context).add( - ChangeFirstSwitchStatusEvent( - value: threeGangModel.firstSwitch)); - }, - // control: DeviceControlModel( - // deviceId: device.uuid, - // // code: 'switch_1', - // code: device.status[0].code, - // // value: true, - // value: device.status[0].value, - // ), - ), - const SizedBox(height: 20), - const SizedBox( - width: 70, - child: BodySmall( - text: "Bedside Light", - fontColor: ColorsManager.textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], + GangSwitch( + threeGangSwitch: device!, + value: threeGangModel.firstSwitch, + action: () { + BlocProvider.of(context).add( + ChangeFirstSwitchStatusEvent( + value: threeGangModel.firstSwitch)); + }, + // control: DeviceControlModel( + // deviceId: device.uuid, + // // code: 'switch_1', + // code: device.status[0].code, + // // value: true, + // value: device.status[0].value, + // ), ), - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: threeGangModel.secondSwitch, - action: () { - BlocProvider.of(context).add( - ChangeSecondSwitchStatusEvent( - value: threeGangModel.secondSwitch)); - }, - // control: DeviceControlModel( - // // deviceId: 'bfe10693d4fd263206ocq9', - // // code: 'switch_2', - // // value: true, - // deviceId: device.uuid, - // code: device.status[1].code, - // value: device.status[1].value, - // ), - ), - const SizedBox(height: 20), - const SizedBox( - width: 70, - child: BodySmall( - text: "Ceiling Light", - fontColor: ColorsManager.textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], - ), - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: threeGangModel.thirdSwitch, - action: () { - BlocProvider.of(context).add( - ChangeThirdSwitchStatusEvent( - value: threeGangModel.thirdSwitch)); - }, - ), - const SizedBox(height: 20), - const SizedBox( - width: 70, - child: BodySmall( - text: "Spotlight", - fontColor: ColorsManager.textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], + const SizedBox(height: 20), + const SizedBox( + width: 70, + child: BodySmall( + text: "Bedside Light", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), ), ], ), - ), - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, + Column( children: [ - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_1', - // value: true, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_2', - // value: true, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_3', - // value: true, - // ), - // device.uuid!, - // ); - BlocProvider.of(context) - .add(AllOnEvent()); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: BodySmall( - text: "On", - style: context.bodyMedium.copyWith( - color: ColorsManager - .primaryColorWithOpacity, - fontWeight: FontWeight.bold), - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 10), - BodySmall( - text: "All On", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + GangSwitch( + threeGangSwitch: device!, + value: threeGangModel.secondSwitch, + action: () { + BlocProvider.of(context).add( + ChangeSecondSwitchStatusEvent( + value: threeGangModel.secondSwitch)); + }, + // control: DeviceControlModel( + // // deviceId: 'bfe10693d4fd263206ocq9', + // // code: 'switch_2', + // // value: true, + // deviceId: device.uuid, + // code: device.status[1].code, + // value: device.status[1].value, + // ), ), + const SizedBox(height: 20), const SizedBox( - width: 20, + width: 70, + child: BodySmall( + text: "Ceiling Light", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - Navigator.push( - context, - PageRouteBuilder( - pageBuilder: - (context, animation1, animation2) => - ScheduleScreen( - device: device!, - ))); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: Icon( - Icons.access_time, + ], + ), + Column( + children: [ + GangSwitch( + threeGangSwitch: device!, + value: threeGangModel.thirdSwitch, + action: () { + BlocProvider.of(context).add( + ChangeThirdSwitchStatusEvent( + value: threeGangModel.thirdSwitch)); + }, + ), + const SizedBox(height: 20), + const SizedBox( + width: 70, + child: BodySmall( + text: "Spotlight", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), + ), + ], + ), + ], + ), + ), + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_1', + // value: true, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_2', + // value: true, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_3', + // value: true, + // ), + // device.uuid!, + // ); + BlocProvider.of(context) + .add(AllOnEvent()); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: BodySmall( + text: "On", + style: context.bodyMedium.copyWith( color: ColorsManager.primaryColorWithOpacity, - size: 25, - ), - ), + fontWeight: FontWeight.bold), ), - ], + ), ), - ), + ], ), - const SizedBox(height: 10), - BodySmall( - text: "Timer", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + ), ), - const SizedBox( - width: 20, - ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_1', - // value: false, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_2', - // value: false, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_3', - // value: false, - // ), - // device.uuid!, - // ); - BlocProvider.of(context) - .add(AllOffEvent()); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: BodySmall( - text: "Off", - style: context.bodyMedium.copyWith( - color: ColorsManager - .primaryColorWithOpacity, - fontWeight: FontWeight.bold), - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 10), - BodySmall( - text: "All Off", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + const SizedBox(height: 10), + BodySmall( + text: "All On", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), ), ], ), - ), - Expanded(child: SizedBox()) - ], + const SizedBox( + width: 20, + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: + (context, animation1, animation2) => + ScheduleScreen( + device: device!, + ))); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: Icon( + Icons.access_time, + color: ColorsManager.primaryColorWithOpacity, + size: 25, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + BodySmall( + text: "Timer", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), + ), + ], + ), + const SizedBox( + width: 20, + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_1', + // value: false, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_2', + // value: false, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_3', + // value: false, + // ), + // device.uuid!, + // ); + BlocProvider.of(context) + .add(AllOffEvent()); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: BodySmall( + text: "Off", + style: context.bodyMedium.copyWith( + color: + ColorsManager.primaryColorWithOpacity, + fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + BodySmall( + text: "All Off", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), + ), + ], + ), + ], + ), ), - ), - ], + Expanded(child: SizedBox()) + ], + ), ), - ); + ], + ), + ); }, ), ); diff --git a/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart b/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart index 25c7a1f..392ad20 100644 --- a/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart +++ b/lib/features/devices/view/widgets/three_gang/three_gang_wizard.dart @@ -5,7 +5,6 @@ import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_eve import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/group_three_gang_model.dart'; -import 'package:syncrow_app/features/devices/model/three_gang_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/three_gang_list.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; @@ -19,36 +18,21 @@ class ThreeGangWizard extends StatelessWidget { Widget build(BuildContext context) { return DefaultScaffold( child: BlocProvider( - create: (context) => - ThreeGangBloc(switchCode: '', threeGangId: device?.uuid ?? '') - ..add(InitialEvent(groupScreen: device != null ? false : true)), + create: (context) => ThreeGangBloc(switchCode: '', threeGangId: device?.uuid ?? '') + ..add(InitialEvent(groupScreen: device != null ? false : true)), child: BlocBuilder( builder: (context, state) { - ThreeGangModel threeGangModel = ThreeGangModel( - firstSwitch: false, - secondSwitch: false, - thirdSwitch: false, - firstCountDown: 0, - secondCountDown: 0, - thirdCountDown: 0); - List groupThreeGangModel = []; bool allSwitchesOn = false; - if (state is LoadingNewSate) { - threeGangModel = state.threeGangModel; - } else if (state is UpdateState) { - threeGangModel = state.threeGangModel; - } else if (state is UpdateGroupState) { + if (state is UpdateGroupState) { groupThreeGangModel = state.threeGangList; allSwitchesOn = state.allSwitches; } return state is LoadingInitialState ? const Center( - child: DefaultContainer( - width: 50, - height: 50, - child: CircularProgressIndicator()), + child: + DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) : ThreeGangList( threeGangList: groupThreeGangModel, diff --git a/lib/features/devices/view/widgets/two_gang/two_gang_screen.dart b/lib/features/devices/view/widgets/two_gang/two_gang_screen.dart index 240a5ff..4aa2e2f 100644 --- a/lib/features/devices/view/widgets/two_gang/two_gang_screen.dart +++ b/lib/features/devices/view/widgets/two_gang/two_gang_screen.dart @@ -4,10 +4,8 @@ import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_bloc.da import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_event.dart'; import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; -import 'package:syncrow_app/features/devices/model/group_two_gang_model.dart'; import 'package:syncrow_app/features/devices/model/two_gang_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/three_gang/gang_switch.dart'; -import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_list.dart'; import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_schedule_screen.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart'; @@ -23,7 +21,7 @@ class TwoGangScreen extends StatelessWidget { Widget build(BuildContext context) { return BlocProvider( create: (context) => TwoGangBloc(switchCode: switchCode ?? '', twoGangId: device?.uuid ?? '') - ..add(InitialEvent(groupScreen: device != null ? false : true)), + ..add(const InitialEvent()), child: BlocBuilder( builder: (context, state) { TwoGangModel twoGangModel = TwoGangModel( @@ -33,304 +31,292 @@ class TwoGangScreen extends StatelessWidget { secondCountDown: 0, ); - List groupTwoGangModel = []; - bool allSwitchesOn = false; if (state is LoadingNewSate) { twoGangModel = state.twoGangModel; } else if (state is UpdateState) { twoGangModel = state.twoGangModel; - } else if (state is UpdateGroupState) { - groupTwoGangModel = state.twoGangList; - allSwitchesOn = state.allSwitches; } + return state is LoadingInitialState ? const Center( child: DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) - : device == null - ? TwoGangList( - twoGangList: groupTwoGangModel, - allSwitches: allSwitchesOn, - ) - : RefreshIndicator( - onRefresh: () async { - BlocProvider.of(context) - .add(InitialEvent(groupScreen: device != null ? false : true)); - }, - child: ListView( - children: [ - SizedBox( - height: MediaQuery.of(context).size.height, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Expanded(child: SizedBox.shrink()), - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.center, + : RefreshIndicator( + onRefresh: () async { + BlocProvider.of(context).add(const InitialEvent()); + }, + child: ListView( + children: [ + SizedBox( + height: MediaQuery.of(context).size.height, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Expanded(child: SizedBox.shrink()), + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( children: [ - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: twoGangModel.firstSwitch, - action: () { - BlocProvider.of(context).add( - ChangeFirstSwitchStatusEvent( - value: twoGangModel.firstSwitch)); - }, - ), - const SizedBox(height: 20), - const SizedBox( - width: 77, - child: BodySmall( - text: "Cove Light", - fontColor: ColorsManager.textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], + GangSwitch( + threeGangSwitch: device!, + value: twoGangModel.firstSwitch, + action: () { + BlocProvider.of(context).add( + ChangeFirstSwitchStatusEvent( + value: twoGangModel.firstSwitch)); + }, ), - Column( - children: [ - GangSwitch( - threeGangSwitch: device!, - value: twoGangModel.secondSwitch, - action: () { - BlocProvider.of(context).add( - ChangeSecondSwitchStatusEvent( - value: twoGangModel.secondSwitch)); - }, - ), - const SizedBox(height: 20), - const SizedBox( - width: 77, - child: BodySmall( - text: "Chandelier", - fontColor: ColorsManager.textPrimaryColor, - textAlign: TextAlign.center, - ), - ), - ], + const SizedBox(height: 20), + const SizedBox( + width: 77, + child: BodySmall( + text: "Cove Light", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), ), ], ), - ), - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, + Column( children: [ - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - BlocProvider.of(context) - .add(AllOnEvent()); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: BodySmall( - text: "On", - style: context.bodyMedium.copyWith( - color: ColorsManager - .primaryColorWithOpacity, - fontWeight: FontWeight.bold), - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 10), - BodySmall( - text: "All On", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + GangSwitch( + threeGangSwitch: device!, + value: twoGangModel.secondSwitch, + action: () { + BlocProvider.of(context).add( + ChangeSecondSwitchStatusEvent( + value: twoGangModel.secondSwitch)); + }, ), + const SizedBox(height: 20), const SizedBox( - width: 20, + width: 77, + child: BodySmall( + text: "Chandelier", + fontColor: ColorsManager.textPrimaryColor, + textAlign: TextAlign.center, + ), ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - Navigator.push( - context, - PageRouteBuilder( - pageBuilder: - (context, animation1, animation2) => - TwoGangScheduleScreen( - device: device!, - ))); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: Icon( - Icons.access_time, + ], + ), + ], + ), + ), + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + BlocProvider.of(context).add(AllOnEvent()); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: BodySmall( + text: "On", + style: context.bodyMedium.copyWith( color: ColorsManager.primaryColorWithOpacity, - size: 25, - ), - ), + fontWeight: FontWeight.bold), ), - ], + ), ), - ), + ], ), - const SizedBox(height: 10), - BodySmall( - text: "Timer", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + ), ), - const SizedBox( - width: 20, - ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - Card( - elevation: 3, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100), - ), - child: GestureDetector( - onTap: () { - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_1', - // value: false, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_2', - // value: false, - // ), - // device.uuid!, - // ); - // DevicesCubit.getInstance().deviceControl( - // DeviceControlModel( - // deviceId: device.uuid, - // code: 'switch_3', - // value: false, - // ), - // device.uuid!, - // ); - BlocProvider.of(context) - .add(AllOffEvent()); - }, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: 60, - height: 60, - decoration: BoxDecoration( - color: Colors.grey[300], - borderRadius: BorderRadius.circular(100), - ), - ), - Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(100), - ), - child: Center( - child: BodySmall( - text: "Off", - style: context.bodyMedium.copyWith( - color: ColorsManager - .primaryColorWithOpacity, - fontWeight: FontWeight.bold), - ), - ), - ), - ], - ), - ), - ), - const SizedBox(height: 10), - BodySmall( - text: "All Off", - style: context.bodyMedium.copyWith( - color: ColorsManager.textPrimaryColor, - ), - ), - ], + const SizedBox(height: 10), + BodySmall( + text: "All On", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), ), ], ), - ), - Expanded(child: SizedBox()) - ], + const SizedBox( + width: 20, + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: + (context, animation1, animation2) => + TwoGangScheduleScreen( + device: device!, + ))); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: Icon( + Icons.access_time, + color: ColorsManager.primaryColorWithOpacity, + size: 25, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + BodySmall( + text: "Timer", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), + ), + ], + ), + const SizedBox( + width: 20, + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Card( + elevation: 3, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100), + ), + child: GestureDetector( + onTap: () { + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_1', + // value: false, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_2', + // value: false, + // ), + // device.uuid!, + // ); + // DevicesCubit.getInstance().deviceControl( + // DeviceControlModel( + // deviceId: device.uuid, + // code: 'switch_3', + // value: false, + // ), + // device.uuid!, + // ); + BlocProvider.of(context) + .add(AllOffEvent()); + }, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(100), + ), + ), + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(100), + ), + child: Center( + child: BodySmall( + text: "Off", + style: context.bodyMedium.copyWith( + color: + ColorsManager.primaryColorWithOpacity, + fontWeight: FontWeight.bold), + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 10), + BodySmall( + text: "All Off", + style: context.bodyMedium.copyWith( + color: ColorsManager.textPrimaryColor, + ), + ), + ], + ), + ], + ), ), - ), - ], + Expanded(child: SizedBox()) + ], + ), ), - ); + ], + ), + ); }, ), ); diff --git a/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart b/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart index 523cf64..04055c5 100644 --- a/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart +++ b/lib/features/devices/view/widgets/two_gang/two_gang_wizard.dart @@ -1,16 +1,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart'; +import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_event.dart'; import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_state.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/group_two_gang_model.dart'; -import 'package:syncrow_app/features/devices/model/two_gang_model.dart'; import 'package:syncrow_app/features/devices/view/widgets/two_gang/two_gang_list.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; -import '../../../bloc/two_gang_bloc/two_gang_event.dart'; - class TwoGangWizard extends StatelessWidget { const TwoGangWizard({super.key, this.device}); @@ -23,32 +21,19 @@ class TwoGangWizard extends StatelessWidget { return DefaultScaffold( child: BlocProvider( create: (context) => - TwoGangBloc(switchCode: '', twoGangId: device?.uuid ?? '') - ..add(InitialWizardEvent()), + TwoGangBloc(switchCode: '', twoGangId: device?.uuid ?? '')..add(InitialWizardEvent()), child: BlocBuilder( builder: (context, state) { - TwoGangModel twoGangModel = TwoGangModel( - firstSwitch: false, - secondSwitch: false, - firstCountDown: 0, - secondCountDown: 0, - ); bool allSwitchesOn = false; - if (state is LoadingNewSate) { - twoGangModel = state.twoGangModel; - } else if (state is UpdateState) { - twoGangModel = state.twoGangModel; - } else if (state is UpdateGroupState) { + if (state is UpdateGroupState) { groupTwoGangModel = state.twoGangList; allSwitchesOn = state.allSwitches; } return state is LoadingInitialState ? const Center( - child: DefaultContainer( - width: 50, - height: 50, - child: CircularProgressIndicator()), + child: + DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) : TwoGangList( twoGangList: groupTwoGangModel, diff --git a/lib/features/devices/view/widgets/water_heater/wh_timer_schedule_screen.dart b/lib/features/devices/view/widgets/water_heater/wh_timer_schedule_screen.dart index 1bafc83..c5ab9ce 100644 --- a/lib/features/devices/view/widgets/water_heater/wh_timer_schedule_screen.dart +++ b/lib/features/devices/view/widgets/water_heater/wh_timer_schedule_screen.dart @@ -25,10 +25,7 @@ class WHTimerScheduleScreen extends StatelessWidget { final String deviceCode; final String switchCode; const WHTimerScheduleScreen( - {required this.device, - required this.deviceCode, - required this.switchCode, - super.key}); + {required this.device, required this.deviceCode, required this.switchCode, super.key}); @override Widget build(BuildContext context) { @@ -38,10 +35,9 @@ class WHTimerScheduleScreen extends StatelessWidget { statusBarIconBrightness: Brightness.light, ), child: BlocProvider( - create: (context) => - WaterHeaterBloc(switchCode: switchCode, whId: device.uuid ?? '') - ..add(GetCounterEvent(deviceCode: deviceCode)) - ..add(GetScheduleEvent()), + create: (context) => WaterHeaterBloc(switchCode: switchCode, whId: device.uuid ?? '') + ..add(GetCounterEvent(deviceCode: deviceCode)) + ..add(GetScheduleEvent()), child: BlocBuilder( builder: (context, state) { final waterHeaterBloc = BlocProvider.of(context); @@ -87,9 +83,8 @@ class WHTimerScheduleScreen extends StatelessWidget { ? IconButton( onPressed: () { // waterHeaterBloc.toggleCreateSchedule(); - waterHeaterBloc.add( - const ToggleCreateScheduleEvent( - index: 1)); + waterHeaterBloc + .add(const ToggleCreateScheduleEvent(index: 1)); }, icon: const Icon(Icons.add), ) @@ -104,7 +99,7 @@ class WHTimerScheduleScreen extends StatelessWidget { : waterHeaterBloc.selectedTabIndex == 2 ? IconButton( onPressed: () { - waterHeaterBloc.toggleCreateCirculate(); + waterHeaterBloc.add(ToggleCreateCirculate()); }, icon: const Icon(Icons.add), ) @@ -120,8 +115,7 @@ class WHTimerScheduleScreen extends StatelessWidget { decoration: const ShapeDecoration( color: ColorsManager.onPrimaryColor, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(30)), + borderRadius: BorderRadius.all(Radius.circular(30)), ), ), child: TabBar( @@ -130,49 +124,34 @@ class WHTimerScheduleScreen extends StatelessWidget { labelPadding: EdgeInsets.zero, onTap: (value) { if (value == 0) { - if (waterHeaterBloc.createSchedule == - true) { + if (waterHeaterBloc.createSchedule == true) { // waterHeaterBloc // .toggleCreateSchedule(); - waterHeaterBloc.add( - const ToggleCreateScheduleEvent( - index: 1)); + waterHeaterBloc + .add(const ToggleCreateScheduleEvent(index: 1)); } - waterHeaterBloc.add( - ToggleSelectedEvent( - index: value)); + waterHeaterBloc.add(ToggleSelectedEvent(index: value)); // waterHeaterBloc // .toggleSelectedIndex(value); } else if (value == 2) { - if (waterHeaterBloc.createCirculate == - true) { - waterHeaterBloc.add( - ToggleCreateCirculateEvent( - index: value)); + if (waterHeaterBloc.createCirculate == true) { + waterHeaterBloc + .add(ToggleCreateCirculateEvent(index: value)); // waterHeaterBloc // .toggleCreateCirculate(); } - waterHeaterBloc.add( - ToggleSelectedEvent( - index: value)); + waterHeaterBloc.add(ToggleSelectedEvent(index: value)); // waterHeaterBloc // .toggleSelectedIndex(value); } else { - if (waterHeaterBloc.createSchedule == - true) { - waterHeaterBloc.add( - ToggleSelectedEvent( - index: value)); + if (waterHeaterBloc.createSchedule == true) { + waterHeaterBloc.add(ToggleSelectedEvent(index: value)); // waterHeaterBloc // .toggleCreateSchedule(); } - waterHeaterBloc.createCirculate = - false; - waterHeaterBloc.createSchedule = - false; - waterHeaterBloc.add( - ToggleSelectedEvent( - index: value)); + waterHeaterBloc.createCirculate = false; + waterHeaterBloc.createSchedule = false; + waterHeaterBloc.add(ToggleSelectedEvent(index: value)); // waterHeaterBloc // .toggleSelectedIndex(value); } @@ -183,39 +162,31 @@ class WHTimerScheduleScreen extends StatelessWidget { indicator: const ShapeDecoration( color: ColorsManager.slidingBlueColor, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(20)), + borderRadius: BorderRadius.all(Radius.circular(20)), ), ), isScrollable: false, - labelColor: Colors - .white, // Text color when selected - unselectedLabelColor: ColorsManager - .blackColor, // Text color when not selected + labelColor: Colors.white, // Text color when selected + unselectedLabelColor: + ColorsManager.blackColor, // Text color when not selected tabs: [ Tab( icon: Padding( - padding: const EdgeInsets.only( - top: 10.0), + padding: const EdgeInsets.only(top: 10.0), child: SvgPicture.asset( Assets.scheduleTimeIcon, - color: waterHeaterBloc - .selectedTabIndex == - 0 + color: waterHeaterBloc.selectedTabIndex == 0 ? Colors.white : ColorsManager .blackColor, // Change icon color based on selectedIndex ), ), child: Container( - padding: const EdgeInsets.symmetric( - vertical: 5), + padding: const EdgeInsets.symmetric(vertical: 5), child: BodySmall( text: 'Countdown', style: context.bodySmall.copyWith( - color: waterHeaterBloc - .selectedTabIndex == - 0 + color: waterHeaterBloc.selectedTabIndex == 0 ? Colors.white : ColorsManager .blackColor, // Text color based on selectedTabIndex @@ -227,26 +198,20 @@ class WHTimerScheduleScreen extends StatelessWidget { ), Tab( icon: Padding( - padding: - const EdgeInsets.only(top: 10), + padding: const EdgeInsets.only(top: 10), child: SvgPicture.asset( Assets.scheduleCelenderIcon, - color: waterHeaterBloc - .selectedTabIndex == - 1 + color: waterHeaterBloc.selectedTabIndex == 1 ? Colors.white : ColorsManager.blackColor, ), ), child: Container( - padding: const EdgeInsets.symmetric( - vertical: 5), + padding: const EdgeInsets.symmetric(vertical: 5), child: Text( 'Schedule', style: context.bodySmall.copyWith( - color: waterHeaterBloc - .selectedTabIndex == - 1 + color: waterHeaterBloc.selectedTabIndex == 1 ? Colors.white : ColorsManager.blackColor, fontSize: 12, @@ -257,26 +222,20 @@ class WHTimerScheduleScreen extends StatelessWidget { ), Tab( icon: Padding( - padding: - const EdgeInsets.only(top: 10), + padding: const EdgeInsets.only(top: 10), child: SvgPicture.asset( Assets.scheduleCirculateIcon, - color: waterHeaterBloc - .selectedTabIndex == - 2 + color: waterHeaterBloc.selectedTabIndex == 2 ? Colors.white : ColorsManager.blackColor, ), ), child: Container( - padding: const EdgeInsets.symmetric( - vertical: 5), + padding: const EdgeInsets.symmetric(vertical: 5), child: Text( 'Circulate', style: context.bodySmall.copyWith( - color: waterHeaterBloc - .selectedTabIndex == - 2 + color: waterHeaterBloc.selectedTabIndex == 2 ? Colors.white : ColorsManager.blackColor, fontSize: 12, @@ -287,26 +246,20 @@ class WHTimerScheduleScreen extends StatelessWidget { ), Tab( icon: Padding( - padding: - const EdgeInsets.only(top: 10), + padding: const EdgeInsets.only(top: 10), child: SvgPicture.asset( Assets.scheduleInchingIcon, - color: waterHeaterBloc - .selectedTabIndex == - 3 + color: waterHeaterBloc.selectedTabIndex == 3 ? Colors.white : ColorsManager.blackColor, ), ), child: Container( - padding: const EdgeInsets.symmetric( - vertical: 5), + padding: const EdgeInsets.symmetric(vertical: 5), child: Text( 'Inching', style: context.bodySmall.copyWith( - color: waterHeaterBloc - .selectedTabIndex == - 3 + color: waterHeaterBloc.selectedTabIndex == 3 ? Colors.white : ColorsManager.blackColor, fontSize: 12, @@ -325,106 +278,75 @@ class WHTimerScheduleScreen extends StatelessWidget { Center( child: Container( child: Column( - mainAxisAlignment: - MainAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ countNum > 0 ? BodyLarge( - text: _formatDuration( - countNum), - fontColor: ColorsManager - .slidingBlueColor, + text: _formatDuration(countNum), + fontColor: ColorsManager.slidingBlueColor, fontSize: 40, ) : CupertinoTimerPicker( - mode: - CupertinoTimerPickerMode - .hm, + mode: CupertinoTimerPickerMode.hm, onTimerDurationChanged: - (Duration - newDuration) { + (Duration newDuration) { duration = newDuration; }, ), GestureDetector( onTap: () { - if (state - is LoadingNewSate) { + if (state is LoadingNewSate) { return; } if (countNum > 0) { - waterHeaterBloc.add( - SetCounterValue( - deviceCode: - deviceCode, - duration: Duration - .zero)); - } else if (duration != - Duration.zero) { - waterHeaterBloc.add( - SetCounterValue( - deviceCode: - deviceCode, - duration: - duration)); + waterHeaterBloc.add(SetCounterValue( + deviceCode: deviceCode, + duration: Duration.zero)); + } else if (duration != Duration.zero) { + waterHeaterBloc.add(SetCounterValue( + deviceCode: deviceCode, + duration: duration)); } }, - child: SvgPicture.asset( - countNum > 0 - ? Assets.pauseIcon - : Assets.playIcon)), + child: SvgPicture.asset(countNum > 0 + ? Assets.pauseIcon + : Assets.playIcon)), ], ), ), ), SizedBox( - child: waterHeaterBloc.createSchedule == - true + child: waterHeaterBloc.createSchedule == true ? CreateSchedule( onToggleChanged: (bool isOn) { - waterHeaterBloc - .toggleSchedule = isOn; + waterHeaterBloc.toggleSchedule = isOn; }, - onDateTimeChanged: - (DateTime dateTime) { - waterHeaterBloc.selectedTime = - dateTime; + onDateTimeChanged: (DateTime dateTime) { + waterHeaterBloc.selectedTime = dateTime; }, days: waterHeaterBloc.days, - selectDays: (List - selectedDays) { - waterHeaterBloc.selectedDays = - selectedDays; + selectDays: (List selectedDays) { + waterHeaterBloc.selectedDays = selectedDays; }, ) : Padding( - padding: const EdgeInsets.only( - top: 10), + padding: const EdgeInsets.only(top: 10), child: Column( children: [ Expanded( child: ScheduleListView( - listSchedule: - waterHeaterBloc - .listSchedule, // Pass the schedule list here - onDismissed: - (scheduleId) { - waterHeaterBloc - .listSchedule - .removeWhere( - (schedule) => - schedule - .scheduleId == - scheduleId); + listSchedule: waterHeaterBloc + .listSchedule, // Pass the schedule list here + onDismissed: (scheduleId) { + waterHeaterBloc.listSchedule.removeWhere( + (schedule) => + schedule.scheduleId == + scheduleId); waterHeaterBloc.add( - DeleteScheduleEvent( - id: scheduleId)); + DeleteScheduleEvent(id: scheduleId)); }, - onToggleSchedule: - (scheduleId, - isEnabled) { - waterHeaterBloc.add( - ToggleScheduleEvent( + onToggleSchedule: (scheduleId, isEnabled) { + waterHeaterBloc.add(ToggleScheduleEvent( id: scheduleId, toggle: isEnabled, )); @@ -437,56 +359,39 @@ class WHTimerScheduleScreen extends StatelessWidget { ), Center( child: Column( - crossAxisAlignment: - CrossAxisAlignment.center, - mainAxisAlignment: - MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ - waterHeaterBloc.createCirculate == - true + waterHeaterBloc.createCirculate == true ? CirculateWidget( endDuration: () { - waterHeaterBloc.add( - SelectTimeEvent( - context: context, - isEffective: - false)); + waterHeaterBloc.add(SelectTimeEvent( + context: context, isEffective: false)); }, startDuration: () { - waterHeaterBloc.add( - SelectTimeEvent( - context: context, - isEffective: - false)); + waterHeaterBloc.add(SelectTimeEvent( + context: context, isEffective: false)); }, isStartEndTime: true, startTime: DateTime.now(), endTime: DateTime.now(), days: waterHeaterBloc.days, selectedDays: [], - onToggleStartEndTime: - (c) {}, + onToggleStartEndTime: (c) {}, onTimeChanged: (x, f) {}, onDaySelected: (p0) {}, ) : CirculateListView( listSchedule: [], // Pass the schedule list here onDismissed: (scheduleId) { + waterHeaterBloc.listSchedule.removeWhere( + (schedule) => + schedule.scheduleId == scheduleId); waterHeaterBloc - .listSchedule - .removeWhere((schedule) => - schedule - .scheduleId == - scheduleId); - waterHeaterBloc.add( - DeleteScheduleEvent( - id: scheduleId)); + .add(DeleteScheduleEvent(id: scheduleId)); }, - onToggleSchedule: - (scheduleId, - isEnabled) { - waterHeaterBloc.add( - ToggleScheduleEvent( + onToggleSchedule: (scheduleId, isEnabled) { + waterHeaterBloc.add(ToggleScheduleEvent( id: scheduleId, toggle: isEnabled, )); diff --git a/lib/features/devices/view/widgets/water_heater/wh_wizard.dart b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart index d755e71..c27fd55 100644 --- a/lib/features/devices/view/widgets/water_heater/wh_wizard.dart +++ b/lib/features/devices/view/widgets/water_heater/wh_wizard.dart @@ -5,7 +5,6 @@ import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater import 'package:syncrow_app/features/devices/bloc/water_heater_bloc/water_heater_state.dart'; import 'package:syncrow_app/features/devices/model/GroupWHModel.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart'; -import 'package:syncrow_app/features/devices/model/water_heater.dart'; import 'package:syncrow_app/features/devices/view/widgets/water_heater/wh_list.dart'; import 'package:syncrow_app/features/shared_widgets/default_container.dart'; import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart'; @@ -22,30 +21,19 @@ class WHWizard extends StatelessWidget { return DefaultScaffold( child: BlocProvider( create: (context) => - WaterHeaterBloc(switchCode: '', whId: device?.uuid ?? '') - ..add(InitialWizardEvent()), + WaterHeaterBloc(switchCode: '', whId: device?.uuid ?? '')..add(InitialWizardEvent()), child: BlocBuilder( builder: (context, state) { - WHModel whModel = WHModel( - firstSwitch: false, - firstCountDown: 0, - ); bool allSwitchesOn = false; - if (state is LoadingNewSate) { - whModel = state.whModel; - } else if (state is UpdateState) { - whModel = state.whModel; - } else if (state is UpdateGroupState) { + if (state is UpdateGroupState) { groupModel = state.twoGangList; allSwitchesOn = state.allSwitches; } return state is WHLoadingState ? const Center( - child: DefaultContainer( - width: 50, - height: 50, - child: CircularProgressIndicator()), + child: + DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()), ) : WHList( whList: groupModel, diff --git a/lib/services/api/api_links_endpoints.dart b/lib/services/api/api_links_endpoints.dart index 198678e..d065b65 100644 --- a/lib/services/api/api_links_endpoints.dart +++ b/lib/services/api/api_links_endpoints.dart @@ -81,8 +81,7 @@ abstract class ApiEndpoints { static const String controlGroup = '/group/control'; //GET static const String groupBySpace = '/group/{unitUuid}'; - static const String devicesByGroupName = - '/group/{unitUuid}/devices/{groupName}'; + static const String devicesByGroupName = '/group/{unitUuid}/devices/{groupName}'; static const String groupByUuid = '/group/{groupUuid}'; //DELETE @@ -94,8 +93,7 @@ abstract class ApiEndpoints { static const String addDeviceToRoom = '/device/room'; static const String addDeviceToGroup = '/device/group'; static const String controlDevice = '/device/{deviceUuid}/control'; - static const String firmwareDevice = - '/device/{deviceUuid}/firmware/{firmwareVersion}'; + static const String firmwareDevice = '/device/{deviceUuid}/firmware/{firmwareVersion}'; static const String getDevicesByUserId = '/device/user/{userId}'; static const String getDevicesByUnitId = '/device/unit/{unitUuid}'; static const String openDoorLock = '/door-lock/open/{doorLockUuid}'; @@ -105,8 +103,7 @@ abstract class ApiEndpoints { static const String deviceByUuid = '/device/{deviceUuid}'; static const String deviceFunctions = '/device/{deviceUuid}/functions'; static const String gatewayApi = '/device/gateway/{gatewayUuid}/devices'; - static const String deviceFunctionsStatus = - '/device/{deviceUuid}/functions/status'; + static const String deviceFunctionsStatus = '/device/{deviceUuid}/functions/status'; ///Device Permission Module //POST @@ -131,29 +128,24 @@ abstract class ApiEndpoints { static const String getUnitAutomation = '/automation/{unitUuid}'; - static const String getAutomationDetails = - '/automation/details/{automationId}'; + static const String getAutomationDetails = '/automation/details/{automationId}'; /// PUT static const String updateScene = '/scene/tap-to-run/{sceneId}'; static const String updateAutomation = '/automation/{automationId}'; - static const String updateAutomationStatus = - '/automation/status/{automationId}'; + static const String updateAutomationStatus = '/automation/status/{automationId}'; /// DELETE static const String deleteScene = '/scene/tap-to-run/{unitUuid}/{sceneId}'; - static const String deleteAutomation = - '/automation/{unitUuid}/{automationId}'; + static const String deleteAutomation = '/automation/{unitUuid}/{automationId}'; //////////////////////Door Lock ////////////////////// //online - static const String addTemporaryPassword = - '/door-lock/temporary-password/online/{doorLockUuid}'; - static const String getTemporaryPassword = - '/door-lock/temporary-password/online/{doorLockUuid}'; + static const String addTemporaryPassword = '/door-lock/temporary-password/online/{doorLockUuid}'; + static const String getTemporaryPassword = '/door-lock/temporary-password/online/{doorLockUuid}'; //one-time offline static const String addOneTimeTemporaryPassword = @@ -185,11 +177,11 @@ abstract class ApiEndpoints { '/door-lock/temporary-password/online/{doorLockUuid}/{passwordId}'; static const String saveSchedule = '/schedule/{deviceUuid}'; - static const String getSchedule = - '/schedule/{deviceUuid}?category={category}'; + static const String getSchedule = '/schedule/{deviceUuid}?category={category}'; static const String changeSchedule = '/schedule/enable/{deviceUuid}'; static const String deleteSchedule = '/schedule/{deviceUuid}/{scheduleId}'; static const String reportLogs = '/device/report-logs/{deviceUuid}?code={code}&startTime={startTime}&endTime={endTime}'; static const String controlBatch = '/device/control/batch'; + static const String statusBatch = '/device/status/batch'; } diff --git a/lib/services/api/devices_api.dart b/lib/services/api/devices_api.dart index 064f675..2b18884 100644 --- a/lib/services/api/devices_api.dart +++ b/lib/services/api/devices_api.dart @@ -72,8 +72,7 @@ class DevicesAPI { static Future> getDeviceStatus(String deviceId) async { final response = await _httpService.get( - path: ApiEndpoints.deviceFunctionsStatus - .replaceAll('{deviceUuid}', deviceId), + path: ApiEndpoints.deviceFunctionsStatus.replaceAll('{deviceUuid}', deviceId), showServerMessage: false, expectedResponseModel: (json) { return json; @@ -83,9 +82,7 @@ class DevicesAPI { } static Future> renamePass( - {required String name, - required String doorLockUuid, - required String passwordId}) async { + {required String name, required String doorLockUuid, required String passwordId}) async { final response = await _httpService.put( path: ApiEndpoints.renamePassword .replaceAll('{doorLockUuid}', doorLockUuid) @@ -110,8 +107,7 @@ class DevicesAPI { return response; } - static Future> getDeviceByGroupName( - String unitId, String groupName) async { + static Future> getDeviceByGroupName(String unitId, String groupName) async { final response = await _httpService.get( path: ApiEndpoints.devicesByGroupName .replaceAll('{unitUuid}', unitId) @@ -150,8 +146,7 @@ class DevicesAPI { return response; } - static Future> getDevicesByGatewayId( - String gatewayId) async { + static Future> getDevicesByGatewayId(String gatewayId) async { final response = await _httpService.get( path: ApiEndpoints.gatewayApi.replaceAll('{gatewayUuid}', gatewayId), showServerMessage: false, @@ -173,8 +168,7 @@ class DevicesAPI { String deviceId, ) async { final response = await _httpService.get( - path: ApiEndpoints.getTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.getTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), showServerMessage: false, expectedResponseModel: (json) { return json; @@ -185,8 +179,7 @@ class DevicesAPI { static Future getOneTimePasswords(String deviceId) async { final response = await _httpService.get( - path: ApiEndpoints.getOneTimeTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.getOneTimeTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), showServerMessage: false, expectedResponseModel: (json) { return json; @@ -197,8 +190,7 @@ class DevicesAPI { static Future getTimeLimitPasswords(String deviceId) async { final response = await _httpService.get( - path: ApiEndpoints.getMultipleTimeTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.getMultipleTimeTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), showServerMessage: false, expectedResponseModel: (json) { return json; @@ -223,12 +215,10 @@ class DevicesAPI { "invalidTime": invalidTime, }; if (scheduleList != null) { - body["scheduleList"] = - scheduleList.map((schedule) => schedule.toJson()).toList(); + body["scheduleList"] = scheduleList.map((schedule) => schedule.toJson()).toList(); } final response = await _httpService.post( - path: ApiEndpoints.addTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.addTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), body: body, showServerMessage: false, expectedResponseModel: (json) => json, @@ -239,8 +229,7 @@ class DevicesAPI { static Future generateOneTimePassword({deviceId}) async { try { final response = await _httpService.post( - path: ApiEndpoints.addOneTimeTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.addOneTimeTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), showServerMessage: false, expectedResponseModel: (json) { return json; @@ -252,12 +241,10 @@ class DevicesAPI { } } - static Future generateMultiTimePassword( - {deviceId, effectiveTime, invalidTime}) async { + static Future generateMultiTimePassword({deviceId, effectiveTime, invalidTime}) async { try { final response = await _httpService.post( - path: ApiEndpoints.addMultipleTimeTemporaryPassword - .replaceAll('{doorLockUuid}', deviceId), + path: ApiEndpoints.addMultipleTimeTemporaryPassword.replaceAll('{doorLockUuid}', deviceId), showServerMessage: true, body: {"effectiveTime": effectiveTime, "invalidTime": invalidTime}, expectedResponseModel: (json) { @@ -379,28 +366,33 @@ class DevicesAPI { return response; } - - static Future deviceController({ + static Future deviceBatchController({ List? devicesUuid, String? code, bool? value, }) async { - try { - final response = await _httpService.post( - path: ApiEndpoints.controlBatch, - body: {"devicesUuid": devicesUuid, "code": code, "value": value}, - showServerMessage: true, - expectedResponseModel: (json) { - print('json-=-=-=-=-=--=${json}'); - return json; - }, - ); - return response; - } catch (e) { - rethrow; - } + final response = await _httpService.post( + path: ApiEndpoints.controlBatch, + body: {"devicesUuid": devicesUuid, "code": code, "value": value}, + showServerMessage: true, + expectedResponseModel: (json) { + return json; + }, + ); + return response; } - - + static Future deviceBatchStatus({ + List? devicesUuid, + }) async { + final response = await _httpService.get( + path: ApiEndpoints.statusBatch, + queryParameters: {"devicesUuid": devicesUuid}, + showServerMessage: false, + expectedResponseModel: (json) { + return json; + }, + ); + return response; + } } From 3082148e8c20f7fbaf9aded451714ef5b06466d0 Mon Sep 17 00:00:00 2001 From: mohammad Date: Sun, 29 Sep 2024 12:03:58 +0300 Subject: [PATCH 7/7] Bug fixes 2 --- .../bloc/one_gang_bloc/one_gang_bloc.dart | 9 -- .../bloc/three_gang_bloc/three_gang_bloc.dart | 2 +- .../bloc/two_gang_bloc/two_gang_bloc.dart | 113 +++++++++++------ .../water_heater_bloc/water_heater_bloc.dart | 118 +++++++++++++----- 4 files changed, 164 insertions(+), 78 deletions(-) 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 1ebe48e..6d40c61 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 @@ -296,14 +296,6 @@ class OneGangBloc extends Bloc { } } - // void toggleCreateSchedule() { - // emit(LoadingInitialState()); - // createSchedule = !createSchedule; - // selectedDays.clear(); - // selectedTime = DateTime.now(); - // emit(UpdateCreateScheduleState(createSchedule)); - // emit(ChangeSlidingSegmentState(value: 1)); - // } void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { emit(LoadingInitialState()); @@ -358,7 +350,6 @@ class OneGangBloc extends Bloc { for (var status in response['status']) { statusModelList.add(StatusModel.fromJson(status)); } - // deviceStatus = TwoGangModel.fromJson(statusModelList); deviceStatus = OneGangModel.fromJson(statusModelList); groupOneGangList.add(GroupOneGangModel( deviceId: devicesList[i].uuid ?? '', 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 2066b10..087d569 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 @@ -114,7 +114,7 @@ class ThreeGangBloc extends Bloc { DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$threeGangId'); Stream stream = ref.onValue; - stream.listen((DatabaseEvent event) async { + stream.listen((DatabaseEvent event) async { if (_timer != null) { await Future.delayed(const Duration(seconds: 2)); } diff --git a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart index ce44b9f..6b43274 100644 --- a/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart +++ b/lib/features/devices/bloc/two_gang_bloc/two_gang_bloc.dart @@ -35,7 +35,8 @@ class TwoGangBloc extends Bloc { bool createSchedule = false; List listSchedule = []; - TwoGangBloc({required this.twoGangId, required this.switchCode}) : super(InitialState()) { + TwoGangBloc({required this.twoGangId, required this.switchCode}) + : super(InitialState()) { on(_fetchTwoGangStatus); on(_twoGangUpdated); on(_changeFirstSwitch); @@ -65,13 +66,15 @@ class TwoGangBloc 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)); } - void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter emit) { + void toggleCreateSchedule( + ToggleCreateScheduleEvent event, Emitter emit) { emit(LoadingInitialState()); createSchedule = !createSchedule; selectedDays.clear(); @@ -79,7 +82,8 @@ class TwoGangBloc extends Bloc { emit(UpdateCreateScheduleState(createSchedule)); } - void _fetchTwoGangStatus(InitialEvent event, Emitter emit) async { + void _fetchTwoGangStatus( + InitialEvent event, Emitter emit) async { emit(LoadingInitialState()); try { var response = await DevicesAPI.getDeviceStatus(twoGangId); @@ -98,18 +102,21 @@ class TwoGangBloc extends Bloc { _listenToChanges() { try { - DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$twoGangId'); + DatabaseReference ref = + FirebaseDatabase.instance.ref('device-status/$twoGangId'); 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; + 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 = TwoGangModel.fromJson(statusList); @@ -124,7 +131,8 @@ class TwoGangBloc extends Bloc { emit(UpdateState(twoGangModel: deviceStatus)); } - void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter emit) async { + void _changeFirstSwitch( + ChangeFirstSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.value; @@ -135,7 +143,8 @@ class TwoGangBloc extends Bloc { _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: twoGangId, code: 'switch_1', value: !event.value), + DeviceControlModel( + deviceId: twoGangId, code: 'switch_1', value: !event.value), twoGangId); if (!response['success']) { @@ -147,7 +156,8 @@ class TwoGangBloc extends Bloc { } } - void _changeSecondSwitch(ChangeSecondSwitchStatusEvent event, Emitter emit) async { + void _changeSecondSwitch( + ChangeSecondSwitchStatusEvent event, Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { deviceStatus.secondSwitch = !event.value; @@ -157,7 +167,8 @@ class TwoGangBloc extends Bloc { } _timer = Timer(const Duration(milliseconds: 500), () async { final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: twoGangId, code: 'switch_2', value: !event.value), + DeviceControlModel( + deviceId: twoGangId, code: 'switch_2', value: !event.value), twoGangId); if (!response['success']) { @@ -180,11 +191,15 @@ class TwoGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch), + deviceId: twoGangId, + code: 'switch_1', + value: deviceStatus.firstSwitch), twoGangId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch), + deviceId: twoGangId, + code: 'switch_2', + value: deviceStatus.secondSwitch), twoGangId), ]); @@ -207,11 +222,15 @@ class TwoGangBloc extends Bloc { final response = await Future.wait([ DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch), + deviceId: twoGangId, + code: 'switch_1', + value: deviceStatus.firstSwitch), twoGangId), DevicesAPI.controlDevice( DeviceControlModel( - deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch), + deviceId: twoGangId, + code: 'switch_2', + value: deviceStatus.secondSwitch), twoGangId), ]); if (response.every((element) => !element['success'])) { @@ -232,7 +251,8 @@ class TwoGangBloc extends Bloc { groupTwoGangList[i].secondSwitch = true; } emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true)); - List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); final response1 = await DevicesAPI.deviceBatchController( code: 'switch_1', @@ -267,18 +287,19 @@ class TwoGangBloc extends Bloc { emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false)); - List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); final response1 = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, - value: true, + value: false, ); final response2 = await DevicesAPI.deviceBatchController( code: 'switch_2', devicesUuid: allDeviceIds, - value: true, + value: false, ); if (response1['failedResults'].toString() != '[]' || @@ -292,17 +313,20 @@ class TwoGangBloc 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(twoGangModel: deviceStatus)); int seconds = 0; try { seconds = event.duration.inSeconds; final response = await DevicesAPI.controlDevice( - DeviceControlModel(deviceId: twoGangId, code: event.deviceCode, value: seconds), + DeviceControlModel( + deviceId: twoGangId, code: event.deviceCode, value: seconds), twoGangId); if (response['success'] ?? false) { @@ -327,7 +351,8 @@ class TwoGangBloc extends Bloc { } } - void _getCounterValue(GetCounterEvent event, Emitter emit) async { + void _getCounterValue( + GetCounterEvent event, Emitter emit) async { emit(LoadingInitialState()); try { add(GetScheduleEvent()); @@ -435,7 +460,8 @@ class TwoGangBloc extends Bloc { deviceId: twoGangId, ); 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; @@ -446,12 +472,13 @@ class TwoGangBloc 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 toggleRepeat(ToggleScheduleEvent event, Emitter emit) async { + Future toggleRepeat( + ToggleScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.changeSchedule( @@ -470,7 +497,8 @@ class TwoGangBloc extends Bloc { } } - Future deleteSchedule(DeleteScheduleEvent event, Emitter emit) async { + Future deleteSchedule( + DeleteScheduleEvent event, Emitter emit) async { try { emit(LoadingInitialState()); final response = await DevicesAPI.deleteSchedule( @@ -490,7 +518,8 @@ class TwoGangBloc extends Bloc { } } - void _fetchTwoGangWizardStatus(InitialWizardEvent event, Emitter emit) async { + void _fetchTwoGangWizardStatus( + InitialWizardEvent event, Emitter emit) async { emit(LoadingInitialState()); try { devicesList = []; @@ -500,7 +529,8 @@ class TwoGangBloc extends Bloc { HomeCubit.getInstance().selectedSpace?.id ?? '', '2G'); 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)); @@ -523,15 +553,16 @@ class TwoGangBloc extends Bloc { return true; }); } - emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesOn)); + emit(UpdateGroupState( + twoGangList: groupTwoGangList, 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(twoGangModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -544,9 +575,11 @@ class TwoGangBloc extends Bloc { } }); - emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); - List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); final response = await DevicesAPI.deviceBatchController( code: 'switch_1', devicesUuid: allDeviceIds, @@ -561,8 +594,8 @@ class TwoGangBloc extends Bloc { } } - void _changeSecondWizardSwitch( - ChangeSecondWizardSwitchStatusEvent event, Emitter emit) async { + void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event, + Emitter emit) async { emit(LoadingNewSate(twoGangModel: deviceStatus)); try { bool allSwitchesValue = true; @@ -574,9 +607,11 @@ class TwoGangBloc extends Bloc { allSwitchesValue = false; } }); - List allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList(); + List allDeviceIds = + groupTwoGangList.map((device) => device.deviceId).toList(); - emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); + emit(UpdateGroupState( + twoGangList: groupTwoGangList, allSwitches: allSwitchesValue)); final response = await DevicesAPI.deviceBatchController( code: 'switch_2', 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 97220c6..7d3e29d 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 @@ -1,5 +1,6 @@ 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'; @@ -34,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); @@ -56,9 +58,11 @@ class WaterHeaterBloc extends Bloc { on(_groupAllOn); on(_groupAllOff); on(_toggleCreateCirculate); + 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); @@ -70,15 +74,48 @@ class WaterHeaterBloc extends Bloc { statusModelList, ); emit(UpdateState(whModel: deviceStatus)); - Future.delayed(const Duration(milliseconds: 500)); - // _listenToChanges(); + _listenToChanges(); } catch (e) { emit(WHFailedState(errorMessage: e.toString())); return; } } - void _changeFirstSwitch(WaterHeaterSwitch event, Emitter emit) async { + _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 { emit(LoadingNewSate(whModel: deviceStatus)); try { deviceStatus.firstSwitch = !event.whSwitch; @@ -88,7 +125,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']) { @@ -102,13 +142,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') { @@ -130,7 +173,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); @@ -220,7 +264,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; @@ -231,12 +276,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( @@ -254,7 +300,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( @@ -273,7 +320,8 @@ class WaterHeaterBloc extends Bloc { } } - void _toggleCreateCirculate(ToggleCreateCirculate event, Emitter emit) { + void _toggleCreateCirculate( + ToggleCreateCirculate event, Emitter emit) { emit(WHLoadingState()); createCirculate = !createCirculate; selectedDays.clear(); @@ -281,13 +329,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(); @@ -336,8 +386,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; @@ -349,7 +399,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', @@ -364,7 +415,8 @@ class WaterHeaterBloc extends Bloc { } } - void _fetchWHWizardStatus(InitialWizardEvent event, Emitter emit) async { + void _fetchWHWizardStatus( + InitialWizardEvent event, Emitter emit) async { emit(WHLoadingState()); try { devicesList = []; @@ -374,7 +426,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)); @@ -396,23 +449,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', @@ -430,15 +487,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',