one gang wizard &two Gang wizard & wh wizard

This commit is contained in:
mohammad
2024-09-26 16:26:39 +03:00
parent 8508995108
commit 4e345db842
21 changed files with 1210 additions and 170 deletions

View File

@ -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<OneGangEvent, OneGangState> {
bool oneGangGroup = false;
List<DeviceModel> devicesList = [];
OneGangBloc({required this.oneGangId, required this.switchCode}) : super(InitialState()) {
OneGangBloc({required this.oneGangId, required this.switchCode})
: super(InitialState()) {
on<InitialEvent>(_fetchOneGangStatus);
on<OneGangUpdated>(_oneGangUpdated);
on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
@ -41,9 +44,14 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
on<DeleteScheduleEvent>(deleteSchedule);
on<ToggleSelectedEvent>(toggleSelectedIndex);
on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
on<InitialWizardEvent>(_fetchOneGangWizardStatus);
on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
on<GroupAllOnEvent>(_groupAllOn);
on<GroupAllOffEvent>(_groupAllOff);
}
void _fetchOneGangStatus(InitialEvent event, Emitter<OneGangState> emit) async {
void _fetchOneGangStatus(
InitialEvent event, Emitter<OneGangState> emit) async {
emit(LoadingInitialState());
try {
var response = await DevicesAPI.getDeviceStatus(oneGangId);
@ -62,18 +70,21 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
_listenToChanges() {
try {
DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneGangId');
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$oneGangId');
Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 2));
}
Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> 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<OneGangEvent, OneGangState> {
emit(UpdateState(oneGangModel: deviceStatus));
}
void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter<OneGangState> emit) async {
void _changeFirstSwitch(
ChangeFirstSwitchStatusEvent event, Emitter<OneGangState> emit) async {
emit(LoadingNewSate(oneGangModel: deviceStatus));
try {
deviceStatus.firstSwitch = !event.value;
@ -113,17 +125,20 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
}
}
void _changeSliding(ChangeSlidingSegment event, Emitter<OneGangState> emit) async {
void _changeSliding(
ChangeSlidingSegment event, Emitter<OneGangState> emit) async {
emit(ChangeSlidingSegmentState(value: event.value));
}
void _setCounterValue(SetCounterValue event, Emitter<OneGangState> emit) async {
void _setCounterValue(
SetCounterValue event, Emitter<OneGangState> 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<OneGangEvent, OneGangState> {
}
}
void _getCounterValue(GetCounterEvent event, Emitter<OneGangState> emit) async {
void _getCounterValue(
GetCounterEvent event, Emitter<OneGangState> emit) async {
emit(LoadingInitialState());
try {
var response = await DevicesAPI.getDeviceStatus(oneGangId);
@ -215,7 +231,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
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<OneGangEvent, OneGangState> {
deviceId: oneGangId,
);
List<dynamic> 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<OneGangEvent, OneGangState> {
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<OneGangState> emit) async {
Future toggleChange(
ToggleScheduleEvent event, Emitter<OneGangState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.changeSchedule(
@ -270,7 +288,8 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
}
}
Future deleteSchedule(DeleteScheduleEvent event, Emitter<OneGangState> emit) async {
Future deleteSchedule(
DeleteScheduleEvent event, Emitter<OneGangState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.deleteSchedule(
@ -299,14 +318,14 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
// emit(ChangeSlidingSegmentState(value: 1));
// }
void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<OneGangState> emit) {
emit(LoadingInitialState());
createSchedule = !createSchedule;
selectedDays.clear();
selectedTime = DateTime.now();
emit(UpdateCreateScheduleState(createSchedule));
}
void toggleCreateSchedule(
ToggleCreateScheduleEvent event, Emitter<OneGangState> emit) {
emit(LoadingInitialState());
createSchedule = !createSchedule;
selectedDays.clear();
selectedTime = DateTime.now();
emit(UpdateCreateScheduleState(createSchedule));
}
bool toggleSchedule = true;
List<String> selectedDays = [];
@ -329,9 +348,168 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
int selectedTabIndex = 0;
void toggleSelectedIndex( ToggleSelectedEvent event, Emitter<OneGangState> emit) {
void toggleSelectedIndex(
ToggleSelectedEvent event, Emitter<OneGangState> emit) {
emit(LoadingInitialState());
selectedTabIndex =event.index;
selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex));
}
List<GroupOneGangModel> groupOneGangList = [];
bool allSwitchesOn = true;
void _fetchOneGangWizardStatus(
InitialWizardEvent event, Emitter<OneGangState> 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<StatusModel> 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<OneGangState> 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<String> 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<OneGangState> 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<String> 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<OneGangState> 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<String> 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));
}
}
}

View File

@ -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<Object> 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<Object> get props => [toggle,id];
List<Object> get props => [toggle, id];
}
class ToggleDaySelectionEvent extends OneGangEvent {
class ToggleDaySelectionEvent extends OneGangEvent {
final String key;
const ToggleDaySelectionEvent({required this.key});
@override
List<Object> get props => [key];
}
class DeleteScheduleEvent extends OneGangEvent {
final String id;
const DeleteScheduleEvent({required this.id});
@ -115,7 +117,6 @@ class DeleteScheduleEvent extends OneGangEvent {
List<Object> get props => [id];
}
class ToggleSelectedEvent extends OneGangEvent {
final int index;
const ToggleSelectedEvent({required this.index});
@ -123,10 +124,18 @@ class ToggleSelectedEvent extends OneGangEvent {
List<Object> get props => [index];
}
class ToggleCreateScheduleEvent extends OneGangEvent {
final int index;
const ToggleCreateScheduleEvent({required this.index});
@override
List<Object> get props => [index];
}
class ChangeFirstWizardSwitchStatusEvent extends OneGangEvent {
final bool value;
final String deviceId;
const ChangeFirstWizardSwitchStatusEvent(
{required this.value, this.deviceId = ''});
@override
List<Object> get props => [value, deviceId];
}

View File

@ -380,15 +380,18 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
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<ThreeGangEvent, ThreeGangState> {
bool createSchedule = false;
List<ScheduleModel> listSchedule = [];
DateTime? selectedTime = DateTime.now();
// void _changeFirstSwitchWizard( ChangeFirstSwitchStatusEventWizard event, Emitter<ThreeGangState> 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<void> fetchGroupDevises(
// InitialWizardDevises event, Emitter<ThreeGangState> 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<StatusModel> 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));
// }
}

View File

@ -135,4 +135,6 @@ class ToggleCreateScheduleEvent extends ThreeGangEvent {
const ToggleCreateScheduleEvent({required this.index});
@override
List<Object> get props => [index];
}
}
class InitialWizardDevises extends ThreeGangEvent {}

View File

@ -57,6 +57,9 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
on<DeleteScheduleEvent>(deleteSchedule);
on<ToggleSelectedEvent>(toggleSelectedIndex);
on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
on<InitialWizardEvent>(_fetchTwoGangWizardStatus);
on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
on<ChangeSecondWizardSwitchStatusEvent>(_changeSecondWizardSwitch);
}
DateTime? selectedTime = DateTime.now();
@ -296,38 +299,117 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
// void _groupAllOn(GroupAllOnEvent event, Emitter<TwoGangState> 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<TwoGangState> 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<TwoGangState> 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<String> 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<TwoGangEvent, TwoGangState> {
void _groupAllOff(GroupAllOffEvent event, Emitter<TwoGangState> 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<String> 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<TwoGangEvent, TwoGangState> {
emit(FailedState(error: errorMessage.toString()));
}
}
void _fetchTwoGangWizardStatus(
InitialWizardEvent event, Emitter<TwoGangState> 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<StatusModel> 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<TwoGangState> 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<String> 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<TwoGangState> 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<String> 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));
}
}
}

View File

@ -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<Object> get props => [toggle,id];
List<Object> 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<Object> 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<Object> 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<Object> get props => [index];
}
class ToggleCreateScheduleEvent extends TwoGangEvent {
final int index;
const ToggleCreateScheduleEvent({required this.index});
@ -140,5 +138,22 @@ class ToggleCreateScheduleEvent extends TwoGangEvent {
List<Object> 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<Object> get props => [value, deviceId];
}
class ChangeSecondWizardSwitchStatusEvent extends TwoGangEvent {
final bool value;
final String deviceId;
const ChangeSecondWizardSwitchStatusEvent(
{required this.value, this.deviceId = ''});
@override
List<Object> get props => [value, deviceId];
}

View File

@ -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<WaterHeaterEvent, WaterHeaterState> {
final String whId;
final String switchCode;
WHModel deviceStatus = WHModel(
firstSwitch: false,firstCountDown: 0
);
WHModel deviceStatus = WHModel(firstSwitch: false, firstCountDown: 0);
List<WHModel> deviceStatusList = [];
List<DeviceModel> devicesList = [];
bool allAcsPage = false;
@ -27,15 +27,15 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
int globalTemp = 25;
Timer? _timer;
bool toggleSchedule = true;
List<String> selectedDays = [];
bool createSchedule = false;
bool createCirculate = false;
List<ScheduleModel> 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<WaterHeaterInitial>(_fetchWaterHeaterStatus);
on<WaterHeaterSwitch>(_changeFirstSwitch);
on<SetCounterValue>(_setCounterValue);
@ -49,11 +49,17 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
on<OnClose>(_onClose);
on<SelectTimeEvent>(showTime);
on<ToggleSelectedEvent>(toggleSelectedIndex);
on<ToggleSelectedEvent>(toggleSelectedIndex);
on<ToggleCreateScheduleEvent>(toggleCreateSchedule);
on<InitialWizardEvent>(_fetchWHWizardStatus);
on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
on<GroupAllOnEvent>(_groupAllOn);
on<GroupAllOffEvent>(_groupAllOff);
}
void _fetchWaterHeaterStatus(WaterHeaterInitial event, Emitter<WaterHeaterState> emit) async {
void _fetchWaterHeaterStatus(
WaterHeaterInitial event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState());
try {
var response = await DevicesAPI.getDeviceStatus(whId);
@ -61,7 +67,9 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
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<WaterHeaterEvent, WaterHeaterState> {
}
}
void _changeFirstSwitch(WaterHeaterSwitch event, Emitter<WaterHeaterState> emit) async {
void _changeFirstSwitch(
WaterHeaterSwitch event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus));
try {
deviceStatus.firstSwitch = !event.whSwitch;
@ -83,13 +91,13 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
_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<WaterHeaterEvent, WaterHeaterState> {
}
}
//=====================---------- timer ----------------------------------------
void _setCounterValue(SetCounterValue event, Emitter<WaterHeaterState> emit) async {
void _setCounterValue(
SetCounterValue event, Emitter<WaterHeaterState> 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<WaterHeaterEvent, WaterHeaterState> {
}
}
void _getCounterValue(GetCounterEvent event, Emitter<WaterHeaterState> emit) async {
void _getCounterValue(
GetCounterEvent event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState());
try {
var response = await DevicesAPI.getDeviceStatus(whId);
@ -148,7 +155,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
: emit(UpdateTimerState(seconds: deviceStatus.firstCountDown));
}
} catch (e) {
WHFailedState(errorMessage: e.toString());
WHFailedState(errorMessage: e.toString());
return;
}
}
@ -173,13 +180,8 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
}
}
//=====================---------- Schedule ----------------------------------------
List<Map<String, String>> days = [
{"day": "Sun", "key": "Sun"},
{"day": "Mon", "key": "Mon"},
@ -190,9 +192,12 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
{"day": "Sat", "key": "Sat"},
];
Future<void> saveSchedule(ScheduleSave event, Emitter<WaterHeaterState> emit,) async {
Future<void> saveSchedule(
ScheduleSave event,
Emitter<WaterHeaterState> 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<WaterHeaterEvent, WaterHeaterState> {
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<void> getSchedule(GetScheduleEvent event, Emitter<WaterHeaterState> emit,) async {
Future<void> getSchedule(
GetScheduleEvent event,
Emitter<WaterHeaterState> emit,
) async {
try {
emit(WHLoadingState());
final response = await DevicesAPI.getSchedule(
category: switchCode,
deviceId: whId ,
deviceId: whId,
);
List<dynamic> 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<WaterHeaterEvent, WaterHeaterState> {
} 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<WaterHeaterEvent, WaterHeaterState> {
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<WaterHeaterEvent, WaterHeaterState> {
// }
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<WaterHeaterState> emit) {
void toggleSelectedIndex(
ToggleSelectedEvent event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState());
selectedTabIndex =event.index;
selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex));
}
void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState());
createSchedule = !createSchedule;
selectedDays.clear();
selectedTime = DateTime.now();
emit(UpdateCreateScheduleState(createSchedule));
}
void toggleCreateSchedule(
ToggleCreateScheduleEvent event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState());
createSchedule = !createSchedule;
selectedDays.clear();
selectedTime = DateTime.now();
emit(UpdateCreateScheduleState(createSchedule));
}
Future<void> toggleDaySelection(
ToggleDaySelectionEvent event,
Emitter<WaterHeaterState> emit,
) async {
ToggleDaySelectionEvent event,
Emitter<WaterHeaterState> emit,
) async {
emit(WHLoadingState());
if (selectedDays.contains(event.key)) {
selectedDays.remove(event.key);
@ -327,7 +337,6 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
int selectedTabIndex = 0;
showTime(SelectTimeEvent event, Emitter<WaterHeaterState> emit) async {
final TimeOfDay? timePicked = await showTimePicker(
context: event.context,
@ -350,4 +359,165 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
},
);
}
// List<DeviceModel> devicesList = [];
List<GroupWHModel> groupTwoGangList = [];
bool allSwitchesOn = true;
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event,
Emitter<WaterHeaterState> 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<String> 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<WaterHeaterState> 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<StatusModel> 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<WaterHeaterState> 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<String> 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<WaterHeaterState> 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<String> 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));
}
}
}

View File

@ -123,3 +123,21 @@ class ToggleCreateCirculateEvent extends WaterHeaterEvent {
@override
List<Object> 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<Object> get props => [value, deviceId];
}
class GroupAllOnEvent extends WaterHeaterEvent {}
class GroupAllOffEvent extends WaterHeaterEvent {}

View File

@ -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<Object> get props => [value];
}
}
class UpdateGroupState extends WaterHeaterState {
final List<GroupWHModel> twoGangList;
final bool allSwitches;
const UpdateGroupState({required this.twoGangList, required this.allSwitches});
@override
List<Object> get props => [twoGangList, allSwitches];
}

View File

@ -0,0 +1,11 @@
class GroupWHModel {
final String deviceId;
final String deviceName;
bool firstSwitch;
GroupWHModel({
required this.deviceId,
required this.deviceName,
required this.firstSwitch,
});
}

View File

@ -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<GroupOneGangModel> oneGangList;
final bool allSwitches;
@ -48,9 +49,10 @@ class OneGangList extends StatelessWidget {
DevicesDefaultSwitch(
switchValue: oneGangList[index].firstSwitch,
action: () {
BlocProvider.of<OneGangBloc>(context).add(ChangeFirstSwitchStatusEvent(
value: oneGangList[index].firstSwitch,
deviceId: oneGangList[index].deviceId));
BlocProvider.of<OneGangBloc>(context).add(
ChangeFirstWizardSwitchStatusEvent(
value: oneGangList[index].firstSwitch,
deviceId: oneGangList[index].deviceId));
},
),
],

View File

@ -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> groupOneGangModel = [];
return DefaultScaffold(
child: BlocProvider(
create: (context) =>
OneGangBloc(switchCode: '', oneGangId: device?.uuid ?? '')
..add(InitialWizardEvent()),
child: BlocBuilder<OneGangBloc, OneGangState>(
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,
);
},
),
));
}
}

View File

@ -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<ThreeGangBloc>(context)
.add(InitialEvent(groupScreen: device != null ? false : true));

View File

@ -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<ThreeGangBloc, ThreeGangState>(
builder: (context, state) {
ThreeGangModel threeGangModel = ThreeGangModel(
firstSwitch: false,
secondSwitch: false,
thirdSwitch: false,
firstCountDown: 0,
secondCountDown: 0,
thirdCountDown: 0);
List<GroupThreeGangModel> 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,
);
},
),
));
}
}

View File

@ -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<GroupTwoGangModel> twoGangList;
final bool allSwitches;
@ -48,9 +49,10 @@ class TwoGangList extends StatelessWidget {
DevicesDefaultSwitch(
switchValue: twoGangList[index].firstSwitch,
action: () {
BlocProvider.of<TwoGangBloc>(context).add(ChangeFirstSwitchStatusEvent(
value: twoGangList[index].firstSwitch,
deviceId: twoGangList[index].deviceId));
BlocProvider.of<TwoGangBloc>(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<TwoGangBloc>(context).add(ChangeSecondSwitchStatusEvent(
value: twoGangList[index].secondSwitch,
deviceId: twoGangList[index].deviceId));
BlocProvider.of<TwoGangBloc>(context).add(
ChangeSecondWizardSwitchStatusEvent(
value: twoGangList[index].secondSwitch,
deviceId: twoGangList[index].deviceId));
},
),
],

View File

@ -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> groupTwoGangModel = [];
return DefaultScaffold(
child: BlocProvider(
create: (context) =>
TwoGangBloc(switchCode: '', twoGangId: device?.uuid ?? '')
..add(InitialWizardEvent()),
child: BlocBuilder<TwoGangBloc, TwoGangState>(
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,
);
},
),
));
}
}

View File

@ -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<GroupWHModel> whList;
final bool allSwitches;
@override
Widget build(BuildContext context) {
return BlocBuilder<WaterHeaterBloc, WaterHeaterState>(
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<WaterHeaterBloc>(context)
.add(GroupAllOnEvent());
},
secondAction: () {
BlocProvider.of<WaterHeaterBloc>(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<WaterHeaterBloc>(context).add(
ChangeFirstWizardSwitchStatusEvent(
value: whList[index].firstSwitch,
deviceId: whList[index].deviceId));
},
),
],
);
},
),
],
),
);
},
);
}
}

View File

@ -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<GroupWHModel> groupModel = [];
return DefaultScaffold(
child: BlocProvider(
create: (context) =>
WaterHeaterBloc(switchCode: '', whId: device?.uuid ?? '')
..add(InitialWizardEvent()),
child: BlocBuilder<WaterHeaterBloc, WaterHeaterState>(
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,
);
},
),
));
}
}

View File

@ -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(

View File

@ -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';
}

View File

@ -378,4 +378,29 @@ class DevicesAPI {
return response;
}
static Future deviceController({
List<String>? 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;
}
}
}