Enabled real time data

This commit is contained in:
Abdullah Alassaf
2024-10-28 17:03:05 +03:00
parent 3adb84125a
commit bcc31d53a1
15 changed files with 225 additions and 437 deletions

View File

@ -61,11 +61,10 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
} }
deviceStatus = deviceStatus = AcStatusModel.fromJson(response['productUuid'], statusModelList);
AcStatusModel.fromJson(response['productUuid'], statusModelList);
emit(GetAcStatusState(acStatusModel: deviceStatus)); emit(GetAcStatusState(acStatusModel: deviceStatus));
Future.delayed(const Duration(milliseconds: 500)); Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges(); _listenToChanges();
} }
} catch (e) { } catch (e) {
emit(AcsFailedState(errorMessage: e.toString())); emit(AcsFailedState(errorMessage: e.toString()));
@ -75,22 +74,18 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$acId');
FirebaseDatabase.instance.ref('device-status/$acId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) { stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = deviceStatus = AcStatusModel.fromJson(usersMap['productUuid'], statusList);
AcStatusModel.fromJson(usersMap['productUuid'], statusList);
add(AcUpdated()); add(AcUpdated());
}); });
} catch (_) {} } catch (_) {}
@ -107,14 +102,12 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', 'AC'); HomeCubit.getInstance().selectedSpace?.id ?? '', 'AC');
for (int i = 0; i < devicesList.length; i++) { for (int i = 0; i < devicesList.length; i++) {
var response = var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = []; List<StatusModel> statusModelList = [];
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
} }
deviceStatusList.add( deviceStatusList.add(AcStatusModel.fromJson(response['productUuid'], statusModelList));
AcStatusModel.fromJson(response['productUuid'], statusModelList));
} }
_setAllAcsTempsAndSwitches(); _setAllAcsTempsAndSwitches();
} }
@ -136,8 +129,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
emit(AcModifyingState(acStatusModel: deviceStatus)); emit(AcModifyingState(acStatusModel: deviceStatus));
} }
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(deviceId: event.deviceId, code: 'switch', value: acSwitchValue);
deviceId: event.deviceId, code: 'switch', value: acSwitchValue);
} }
void _changeAllAcSwitch(ChangeAllSwitch event, Emitter<AcsState> emit) async { void _changeAllAcSwitch(ChangeAllSwitch event, Emitter<AcsState> emit) async {
@ -198,8 +190,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
deviceStatus.childLock = lockValue; deviceStatus.childLock = lockValue;
emit(AcModifyingState(acStatusModel: deviceStatus)); emit(AcModifyingState(acStatusModel: deviceStatus));
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(deviceId: acId, code: 'child_lock', value: lockValue);
deviceId: acId, code: 'child_lock', value: lockValue);
} }
void _increaseCoolTo(IncreaseCoolToTemp event, Emitter<AcsState> emit) async { void _increaseCoolTo(IncreaseCoolToTemp event, Emitter<AcsState> emit) async {
@ -227,8 +218,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
emit(AcModifyingState(acStatusModel: deviceStatus)); emit(AcModifyingState(acStatusModel: deviceStatus));
} }
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(deviceId: event.deviceId, code: 'temp_set', value: value);
deviceId: event.deviceId, code: 'temp_set', value: value);
} }
void _decreaseCoolTo(DecreaseCoolToTemp event, Emitter<AcsState> emit) async { void _decreaseCoolTo(DecreaseCoolToTemp event, Emitter<AcsState> emit) async {
@ -256,8 +246,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
emit(AcModifyingState(acStatusModel: deviceStatus)); emit(AcModifyingState(acStatusModel: deviceStatus));
} }
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(deviceId: event.deviceId, code: 'temp_set', value: value);
deviceId: event.deviceId, code: 'temp_set', value: value);
} }
void _changeAcMode(ChangeAcMode event, Emitter<AcsState> emit) async { void _changeAcMode(ChangeAcMode event, Emitter<AcsState> emit) async {
@ -279,9 +268,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
} }
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(
deviceId: event.deviceId, deviceId: event.deviceId, code: 'mode', value: getACModeString(tempMode));
code: 'mode',
value: getACModeString(tempMode));
} }
void _changeFanSpeed(ChangeFanSpeed event, Emitter<AcsState> emit) async { void _changeFanSpeed(ChangeFanSpeed event, Emitter<AcsState> emit) async {
@ -294,23 +281,19 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
for (AcStatusModel ac in deviceStatusList) { for (AcStatusModel ac in deviceStatusList) {
if (ac.uuid == event.productId) { if (ac.uuid == event.productId) {
ac.fanSpeedsString = getNextFanSpeedKey(fanSpeed); ac.fanSpeedsString = getNextFanSpeedKey(fanSpeed);
ac.acFanSpeed = ac.acFanSpeed = AcStatusModel.getFanSpeed(getNextFanSpeedKey(fanSpeed));
AcStatusModel.getFanSpeed(getNextFanSpeedKey(fanSpeed));
} }
} }
_emitAcsStatus(emit); _emitAcsStatus(emit);
} else { } else {
emit(AcChangeLoading(acStatusModel: deviceStatus)); emit(AcChangeLoading(acStatusModel: deviceStatus));
deviceStatus.fanSpeedsString = getNextFanSpeedKey(fanSpeed); deviceStatus.fanSpeedsString = getNextFanSpeedKey(fanSpeed);
deviceStatus.acFanSpeed = deviceStatus.acFanSpeed = AcStatusModel.getFanSpeed(getNextFanSpeedKey(fanSpeed));
AcStatusModel.getFanSpeed(getNextFanSpeedKey(fanSpeed));
emit(AcModifyingState(acStatusModel: deviceStatus)); emit(AcModifyingState(acStatusModel: deviceStatus));
} }
await _runDeBouncerForOneDevice( await _runDeBouncerForOneDevice(
deviceId: event.deviceId, deviceId: event.deviceId, code: 'level', value: getNextFanSpeedKey(fanSpeed));
code: 'level',
value: getNextFanSpeedKey(fanSpeed));
} }
String getACModeString(TempModes value) { String getACModeString(TempModes value) {
@ -355,8 +338,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
for (int i = 0; i < deviceStatusList.length; i++) { for (int i = 0; i < deviceStatusList.length; i++) {
try { try {
await DevicesAPI.controlDevice( await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: devicesList[i].uuid, code: code, value: value),
deviceId: devicesList[i].uuid, code: code, value: value),
devicesList[i].uuid ?? ''); devicesList[i].uuid ?? '');
} catch (_) { } catch (_) {
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
@ -378,10 +360,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
_timer = Timer(const Duration(seconds: 1), () async { _timer = Timer(const Duration(seconds: 1), () async {
try { try {
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: allAcsPage ? deviceId : acId, code: code, value: value),
deviceId: allAcsPage ? deviceId : acId,
code: code,
value: value),
allAcsPage ? deviceId : acId); allAcsPage ? deviceId : acId);
if (!response['success']) { if (!response['success']) {
@ -398,8 +377,7 @@ class ACsBloc extends Bloc<AcsEvent, AcsState> {
if (value >= 20 && value <= 30) { if (value >= 20 && value <= 30) {
return true; return true;
} else { } else {
emit(const AcsFailedState( emit(const AcsFailedState(errorMessage: 'The temperature must be between 20 and 30'));
errorMessage: 'The temperature must be between 20 and 30'));
emit(GetAllAcsStatusState( emit(GetAllAcsStatusState(
allAcsStatues: deviceStatusList, allAcsStatues: deviceStatusList,
allAcs: devicesList, allAcs: devicesList,

View File

@ -19,8 +19,7 @@ class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
on<CeilingSensorUpdated>(_onCeilingSensorUpdated); on<CeilingSensorUpdated>(_onCeilingSensorUpdated);
} }
void _fetchCeilingSensorStatus( void _fetchCeilingSensorStatus(InitialEvent event, Emitter<CeilingSensorState> emit) async {
InitialEvent event, Emitter<CeilingSensorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(deviceId); var response = await DevicesAPI.getDeviceStatus(deviceId);
@ -30,7 +29,7 @@ class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
} }
deviceStatus = CeilingSensorModel.fromJson(statusModelList); deviceStatus = CeilingSensorModel.fromJson(statusModelList);
emit(UpdateState(ceilingSensorModel: deviceStatus)); emit(UpdateState(ceilingSensorModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
@ -39,18 +38,15 @@ class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
FirebaseDatabase.instance.ref('device-status/$deviceId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) { stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = CeilingSensorModel.fromJson(statusList); deviceStatus = CeilingSensorModel.fromJson(statusList);
@ -59,19 +55,15 @@ class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
} catch (_) {} } catch (_) {}
} }
_onCeilingSensorUpdated( _onCeilingSensorUpdated(CeilingSensorUpdated event, Emitter<CeilingSensorState> emit) {
CeilingSensorUpdated event, Emitter<CeilingSensorState> emit) {
emit(UpdateState(ceilingSensorModel: deviceStatus)); emit(UpdateState(ceilingSensorModel: deviceStatus));
} }
void _changeValue( void _changeValue(ChangeValueEvent event, Emitter<CeilingSensorState> emit) async {
ChangeValueEvent event, Emitter<CeilingSensorState> emit) async {
emit(LoadingNewSate(ceilingSensorModel: deviceStatus)); emit(LoadingNewSate(ceilingSensorModel: deviceStatus));
try { try {
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: deviceId, code: event.code, value: event.value), deviceId);
deviceId: deviceId, code: event.code, value: event.value),
deviceId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
deviceStatus.sensitivity = event.value; deviceStatus.sensitivity = event.value;

View File

@ -25,11 +25,9 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
bool lowBattery = false; bool lowBattery = false;
bool closingReminder = false; bool closingReminder = false;
bool doorAlarm = false; bool doorAlarm = false;
DoorSensorModel deviceStatus = DoorSensorModel deviceStatus = DoorSensorModel(doorContactState: false, batteryPercentage: 0);
DoorSensorModel(doorContactState: false, batteryPercentage: 0);
void _fetchStatus( void _fetchStatus(DoorSensorInitial event, Emitter<DoorSensorState> emit) async {
DoorSensorInitial event, Emitter<DoorSensorState> emit) async {
emit(DoorSensorLoadingState()); emit(DoorSensorLoadingState());
try { try {
var response = await DevicesAPI.getDeviceStatus(DSId); var response = await DevicesAPI.getDeviceStatus(DSId);
@ -42,7 +40,7 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
); );
emit(UpdateState(doorSensor: deviceStatus)); emit(UpdateState(doorSensor: deviceStatus));
Future.delayed(const Duration(milliseconds: 500)); Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(DoorSensorFailedState(errorMessage: e.toString())); emit(DoorSensorFailedState(errorMessage: e.toString()));
return; return;
@ -50,8 +48,7 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
} }
// Toggle functions for each switch // Toggle functions for each switch
void _toggleLowBattery( void _toggleLowBattery(ToggleLowBatteryEvent event, Emitter<DoorSensorState> emit) async {
ToggleLowBatteryEvent event, Emitter<DoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
lowBattery = event.isLowBatteryEnabled; lowBattery = event.isLowBatteryEnabled;
@ -92,8 +89,7 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
} }
} }
void _toggleDoorAlarm( void _toggleDoorAlarm(ToggleDoorAlarmEvent event, Emitter<DoorSensorState> emit) async {
ToggleDoorAlarmEvent event, Emitter<DoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
doorAlarm = event.isDoorAlarmEnabled; doorAlarm = event.isDoorAlarmEnabled;
@ -112,11 +108,9 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
} }
} }
DeviceReport recordGroups = DeviceReport recordGroups = DeviceReport(startTime: '0', endTime: '0', data: []);
DeviceReport(startTime: '0', endTime: '0', data: []);
Future<void> fetchLogsForLastMonth( Future<void> fetchLogsForLastMonth(ReportLogsInitial event, Emitter<DoorSensorState> emit) async {
ReportLogsInitial event, Emitter<DoorSensorState> emit) async {
DateTime now = DateTime.now(); DateTime now = DateTime.now();
DateTime lastMonth = DateTime(now.year, now.month - 1, now.day); DateTime lastMonth = DateTime(now.year, now.month - 1, now.day);
@ -126,9 +120,8 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
try { try {
emit(DoorSensorLoadingState()); emit(DoorSensorLoadingState());
var response = await DevicesAPI.getReportLogs( var response = await DevicesAPI.getReportLogs(
startTime: startTime: startTime.toString(),
startTime.toString(), endTime: endTime.toString(),
endTime: endTime.toString(),
deviceUuid: DSId, deviceUuid: DSId,
code: 'doorcontact_state', code: 'doorcontact_state',
); );
@ -142,16 +135,14 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$DSId');
FirebaseDatabase.instance.ref('device-status/$DSId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {

View File

@ -65,8 +65,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
batteryPercentage: 0, batteryPercentage: 0,
); );
void _fetchStatus( void _fetchStatus(GarageDoorInitial event, Emitter<GarageDoorSensorState> emit) async {
GarageDoorInitial event, Emitter<GarageDoorSensorState> emit) async {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
try { try {
var response = await DevicesAPI.getDeviceStatus(GDId); var response = await DevicesAPI.getDeviceStatus(GDId);
@ -81,7 +80,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
toggleDoor = deviceStatus.switch1; toggleDoor = deviceStatus.switch1;
emit(UpdateState(garageSensor: deviceStatus)); emit(UpdateState(garageSensor: deviceStatus));
Future.delayed(const Duration(milliseconds: 500)); Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(GarageDoorFailedState(errorMessage: e.toString())); emit(GarageDoorFailedState(errorMessage: e.toString()));
return; return;
@ -114,8 +113,8 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _toggleClosingReminder(ToggleClosingReminderEvent event, void _toggleClosingReminder(
Emitter<GarageDoorSensorState> emit) async { ToggleClosingReminderEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
closingReminder = event.isClosingReminderEnabled; closingReminder = event.isClosingReminderEnabled;
@ -133,8 +132,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _toggleDoorAlarm( void _toggleDoorAlarm(ToggleDoorAlarmEvent event, Emitter<GarageDoorSensorState> emit) async {
ToggleDoorAlarmEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
doorAlarm = event.isDoorAlarmEnabled; doorAlarm = event.isDoorAlarmEnabled;
@ -152,8 +150,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
DeviceReport recordGroups = DeviceReport recordGroups = DeviceReport(startTime: '0', endTime: '0', data: []);
DeviceReport(startTime: '0', endTime: '0', data: []);
Future<void> fetchLogsForLastMonth( Future<void> fetchLogsForLastMonth(
ReportLogsInitial event, Emitter<GarageDoorSensorState> emit) async { ReportLogsInitial event, Emitter<GarageDoorSensorState> emit) async {
@ -172,8 +169,6 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
); );
recordGroups = response; recordGroups = response;
emit(UpdateState(garageSensor: deviceStatus)); emit(UpdateState(garageSensor: deviceStatus));
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -184,16 +179,14 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$GDId');
FirebaseDatabase.instance.ref('device-status/$GDId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList.add(StatusModel(code: element['code'], value: true)); statusList.add(StatusModel(code: element['code'], value: true));
@ -268,8 +261,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
deviceId: GDId, deviceId: GDId,
); );
List<dynamic> jsonData = response; List<dynamic> jsonData = response;
listSchedule = listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(UpdateState(garageSensor: deviceStatus)); emit(UpdateState(garageSensor: deviceStatus));
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -280,13 +272,12 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) { int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null; if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, DateTime dateTimeWithoutSeconds =
dateTime.day, dateTime.hour, dateTime.minute); DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
} }
Future toggleChange( Future toggleChange(ToggleScheduleEvent event, Emitter<GarageDoorSensorState> emit) async {
ToggleScheduleEvent event, Emitter<GarageDoorSensorState> emit) async {
try { try {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
final response = await DevicesAPI.changeSchedule( final response = await DevicesAPI.changeSchedule(
@ -304,8 +295,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
Future deleteSchedule( Future deleteSchedule(DeleteScheduleEvent event, Emitter<GarageDoorSensorState> emit) async {
DeleteScheduleEvent event, Emitter<GarageDoorSensorState> emit) async {
try { try {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
final response = await DevicesAPI.deleteSchedule( final response = await DevicesAPI.deleteSchedule(
@ -324,15 +314,13 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void toggleSelectedIndex( void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<GarageDoorSensorState> emit) {
ToggleSelectedEvent event, Emitter<GarageDoorSensorState> emit) {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
selectedTabIndex = event.index; selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex)); emit(ChangeSlidingSegmentState(value: selectedTabIndex));
} }
void toggleCreateSchedule( void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<GarageDoorSensorState> emit) {
ToggleCreateScheduleEvent event, Emitter<GarageDoorSensorState> emit) {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
createSchedule = !createSchedule; createSchedule = !createSchedule;
selectedDays.clear(); selectedDays.clear();
@ -349,16 +337,13 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
int secondSelected = 0; int secondSelected = 0;
bool toggleDoor = false; bool toggleDoor = false;
Future<void> selectSeconds( Future<void> selectSeconds(SelectSecondsEvent event, Emitter<GarageDoorSensorState> emit) async {
SelectSecondsEvent event, Emitter<GarageDoorSensorState> emit) async {
try { try {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
secondSelected = event.seconds; secondSelected = event.seconds;
await DevicesAPI.controlDevice( await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: GDId, code: 'tr_timecon', value: secondSelected), GDId);
deviceId: GDId, code: 'tr_timecon', value: secondSelected),
GDId);
emit(UpdateState(garageSensor: deviceStatus)); emit(UpdateState(garageSensor: deviceStatus));
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -367,15 +352,12 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
openCloseGarageDoor( openCloseGarageDoor(ToggleDoorEvent event, Emitter<GarageDoorSensorState> emit) async {
ToggleDoorEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(GarageDoorLoadingState()); emit(GarageDoorLoadingState());
try { try {
toggleDoor = !event.toggle; toggleDoor = !event.toggle;
await DevicesAPI.controlDevice( await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: GDId, code: 'switch_1', value: toggleDoor), GDId);
deviceId: GDId, code: 'switch_1', value: toggleDoor),
GDId);
add(const GarageDoorInitial()); add(const GarageDoorInitial());
emit(UpdateState(garageSensor: deviceStatus)); emit(UpdateState(garageSensor: deviceStatus));
} on DioException catch (e) { } on DioException catch (e) {
@ -385,16 +367,13 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _setCounterValue( void _setCounterValue(SetCounterValue event, Emitter<GarageDoorSensorState> emit) async {
SetCounterValue event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
int seconds = 0; int seconds = 0;
try { try {
seconds = event.duration.inSeconds; seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: GDId, code: 'countdown_1', value: seconds), GDId);
deviceId: GDId, code: 'countdown_1', value: seconds),
GDId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
deviceStatus.countdown1 = seconds; deviceStatus.countdown1 = seconds;
@ -414,8 +393,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _getCounterValue( void _getCounterValue(GetCounterEvent event, Emitter<GarageDoorSensorState> emit) async {
GetCounterEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(GDId); var response = await DevicesAPI.getDeviceStatus(GDId);
@ -456,8 +434,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
List<GroupGarageModel> groupList = []; List<GroupGarageModel> groupList = [];
bool allSwitchesOn = true; bool allSwitchesOn = true;
void _fetchWizardStatus( void _fetchWizardStatus(InitialWizardEvent event, Emitter<GarageDoorSensorState> emit) async {
InitialWizardEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
devicesList = []; devicesList = [];
@ -467,8 +444,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', 'GD'); HomeCubit.getInstance().selectedSpace?.id ?? '', 'GD');
for (int i = 0; i < devicesList.length; i++) { for (int i = 0; i < devicesList.length; i++) {
var response = var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = []; List<StatusModel> statusModelList = [];
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
@ -497,8 +473,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _groupAllOn( void _groupAllOn(GroupAllOnEvent event, Emitter<GarageDoorSensorState> emit) async {
GroupAllOnEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
// Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off)
@ -510,8 +485,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
emit(UpdateGroupState(garageList: groupList, allSwitches: true)); emit(UpdateGroupState(garageList: groupList, allSwitches: true));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupList.map((device) => device.deviceId).toList();
groupList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
@ -531,8 +505,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _groupAllOff( void _groupAllOff(GroupAllOffEvent event, Emitter<GarageDoorSensorState> emit) async {
GroupAllOffEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
// Set all switches (firstSwitch and secondSwitch) based on the event value (on/off) // Set all switches (firstSwitch and secondSwitch) based on the event value (on/off)
@ -544,8 +517,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
emit(UpdateGroupState(garageList: groupList, allSwitches: false)); emit(UpdateGroupState(garageList: groupList, allSwitches: false));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupList.map((device) => device.deviceId).toList();
groupList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
@ -566,8 +538,8 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, void _changeFirstWizardSwitch(
Emitter<GarageDoorSensorState> emit) async { ChangeFirstWizardSwitchStatusEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
try { try {
bool allSwitchesValue = true; bool allSwitchesValue = true;
@ -580,8 +552,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
}); });
emit(UpdateGroupState( emit(UpdateGroupState(garageList: groupList, allSwitches: allSwitchesValue));
garageList: groupList, allSwitches: allSwitchesValue));
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
code: 'switch_1', code: 'switch_1',
@ -597,16 +568,13 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
} }
} }
void _setTimeOutAlarm( void _setTimeOutAlarm(SetTimeOutValue event, Emitter<GarageDoorSensorState> emit) async {
SetTimeOutValue event, Emitter<GarageDoorSensorState> emit) async {
emit(LoadingNewSate(doorSensor: deviceStatus)); emit(LoadingNewSate(doorSensor: deviceStatus));
int seconds = 0; int seconds = 0;
try { try {
seconds = event.duration.inSeconds; seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: GDId, code: 'countdown_alarm', value: seconds), GDId);
deviceId: GDId, code: 'countdown_alarm', value: seconds),
GDId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
deviceStatus.countdownAlarm = seconds; deviceStatus.countdownAlarm = seconds;

View File

@ -26,8 +26,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
bool oneGangGroup = false; bool oneGangGroup = false;
List<DeviceModel> devicesList = []; List<DeviceModel> devicesList = [];
OneGangBloc({required this.oneGangId, required this.switchCode}) OneGangBloc({required this.oneGangId, required this.switchCode}) : super(InitialState()) {
: super(InitialState()) {
on<InitialEvent>(_fetchOneGangStatus); on<InitialEvent>(_fetchOneGangStatus);
on<OneGangUpdated>(_oneGangUpdated); on<OneGangUpdated>(_oneGangUpdated);
on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch); on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
@ -50,8 +49,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
on<GroupAllOffEvent>(_groupAllOff); on<GroupAllOffEvent>(_groupAllOff);
} }
void _fetchOneGangStatus( void _fetchOneGangStatus(InitialEvent event, Emitter<OneGangState> emit) async {
InitialEvent event, Emitter<OneGangState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(oneGangId); var response = await DevicesAPI.getDeviceStatus(oneGangId);
@ -61,7 +59,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
deviceStatus = OneGangModel.fromJson(statusModelList); deviceStatus = OneGangModel.fromJson(statusModelList);
emit(UpdateState(oneGangModel: deviceStatus)); emit(UpdateState(oneGangModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
@ -70,21 +68,18 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneGangId');
FirebaseDatabase.instance.ref('device-status/$oneGangId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = OneGangModel.fromJson(statusList); deviceStatus = OneGangModel.fromJson(statusList);
@ -99,8 +94,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
emit(UpdateState(oneGangModel: deviceStatus)); emit(UpdateState(oneGangModel: deviceStatus));
} }
void _changeFirstSwitch( void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter<OneGangState> emit) async {
ChangeFirstSwitchStatusEvent event, Emitter<OneGangState> emit) async {
emit(LoadingNewSate(oneGangModel: deviceStatus)); emit(LoadingNewSate(oneGangModel: deviceStatus));
try { try {
deviceStatus.firstSwitch = !event.value; deviceStatus.firstSwitch = !event.value;
@ -125,20 +119,17 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
} }
void _changeSliding( void _changeSliding(ChangeSlidingSegment event, Emitter<OneGangState> emit) async {
ChangeSlidingSegment event, Emitter<OneGangState> emit) async {
emit(ChangeSlidingSegmentState(value: event.value)); emit(ChangeSlidingSegmentState(value: event.value));
} }
void _setCounterValue( void _setCounterValue(SetCounterValue event, Emitter<OneGangState> emit) async {
SetCounterValue event, Emitter<OneGangState> emit) async {
emit(LoadingNewSate(oneGangModel: deviceStatus)); emit(LoadingNewSate(oneGangModel: deviceStatus));
int seconds = 0; int seconds = 0;
try { try {
seconds = event.duration.inSeconds; seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: oneGangId, code: event.deviceCode, value: seconds),
deviceId: oneGangId, code: event.deviceCode, value: seconds),
oneGangId); oneGangId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
@ -161,8 +152,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
} }
void _getCounterValue( void _getCounterValue(GetCounterEvent event, Emitter<OneGangState> emit) async {
GetCounterEvent event, Emitter<OneGangState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(oneGangId); var response = await DevicesAPI.getDeviceStatus(oneGangId);
@ -251,8 +241,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
deviceId: oneGangId, deviceId: oneGangId,
); );
List<dynamic> jsonData = response; List<dynamic> jsonData = response;
listSchedule = listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(InitialState()); emit(InitialState());
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -263,13 +252,12 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) { int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null; if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, DateTime dateTimeWithoutSeconds =
dateTime.day, dateTime.hour, dateTime.minute); DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
} }
Future toggleChange( Future toggleChange(ToggleScheduleEvent event, Emitter<OneGangState> emit) async {
ToggleScheduleEvent event, Emitter<OneGangState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
final response = await DevicesAPI.changeSchedule( final response = await DevicesAPI.changeSchedule(
@ -288,8 +276,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
} }
Future deleteSchedule( Future deleteSchedule(DeleteScheduleEvent event, Emitter<OneGangState> emit) async {
DeleteScheduleEvent event, Emitter<OneGangState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
final response = await DevicesAPI.deleteSchedule( final response = await DevicesAPI.deleteSchedule(
@ -309,8 +296,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
} }
void toggleCreateSchedule( void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<OneGangState> emit) {
ToggleCreateScheduleEvent event, Emitter<OneGangState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
createSchedule = !createSchedule; createSchedule = !createSchedule;
selectedDays.clear(); selectedDays.clear();
@ -339,8 +325,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
int selectedTabIndex = 0; int selectedTabIndex = 0;
void toggleSelectedIndex( void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<OneGangState> emit) {
ToggleSelectedEvent event, Emitter<OneGangState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
selectedTabIndex = event.index; selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex)); emit(ChangeSlidingSegmentState(value: selectedTabIndex));
@ -349,8 +334,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
List<GroupOneGangModel> groupOneGangList = []; List<GroupOneGangModel> groupOneGangList = [];
bool allSwitchesOn = true; bool allSwitchesOn = true;
void _fetchOneGangWizardStatus( void _fetchOneGangWizardStatus(InitialWizardEvent event, Emitter<OneGangState> emit) async {
InitialWizardEvent event, Emitter<OneGangState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
devicesList = []; devicesList = [];
@ -360,8 +344,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', '1G'); HomeCubit.getInstance().selectedSpace?.id ?? '', '1G');
for (int i = 0; i < devicesList.length; i++) { for (int i = 0; i < devicesList.length; i++) {
var response = var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = []; List<StatusModel> statusModelList = [];
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
@ -382,16 +365,15 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
return true; return true;
}); });
} }
emit(UpdateGroupState( emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: allSwitchesOn));
oneGangList: groupOneGangList, allSwitches: allSwitchesOn));
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
} }
} }
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, void _changeFirstWizardSwitch(
Emitter<OneGangState> emit) async { ChangeFirstWizardSwitchStatusEvent event, Emitter<OneGangState> emit) async {
emit(LoadingNewSate(oneGangModel: deviceStatus)); emit(LoadingNewSate(oneGangModel: deviceStatus));
try { try {
bool allSwitchesValue = true; bool allSwitchesValue = true;
@ -404,8 +386,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
} }
}); });
emit(UpdateGroupState( emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: allSwitchesValue));
oneGangList: groupOneGangList, allSwitches: allSwitchesValue));
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
code: 'switch_1', code: 'switch_1',
@ -433,8 +414,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: true)); emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: true));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupOneGangList.map((device) => device.deviceId).toList();
groupOneGangList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
@ -466,8 +446,7 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: false)); emit(UpdateGroupState(oneGangList: groupOneGangList, allSwitches: false));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupOneGangList.map((device) => device.deviceId).toList();
groupOneGangList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(

View File

@ -30,8 +30,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
bool oneTouchGroup = false; bool oneTouchGroup = false;
List<DeviceModel> devicesList = []; List<DeviceModel> devicesList = [];
OneTouchBloc({required this.oneTouchId, required this.switchCode}) OneTouchBloc({required this.oneTouchId, required this.switchCode}) : super(InitialState()) {
: super(InitialState()) {
on<InitialEvent>(_fetchOneTouchStatus); on<InitialEvent>(_fetchOneTouchStatus);
on<OneTouchUpdated>(_oneTouchUpdated); on<OneTouchUpdated>(_oneTouchUpdated);
on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch); on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
@ -54,8 +53,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
on<ChangeStatusEvent>(_changeStatus); on<ChangeStatusEvent>(_changeStatus);
} }
void _fetchOneTouchStatus( void _fetchOneTouchStatus(InitialEvent event, Emitter<OneTouchState> emit) async {
InitialEvent event, Emitter<OneTouchState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(oneTouchId); var response = await DevicesAPI.getDeviceStatus(oneTouchId);
@ -65,7 +63,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
deviceStatus = OneTouchModel.fromJson(statusModelList); deviceStatus = OneTouchModel.fromJson(statusModelList);
emit(UpdateState(oneTouchModel: deviceStatus)); emit(UpdateState(oneTouchModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
@ -74,21 +72,18 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneTouchId');
FirebaseDatabase.instance.ref('device-status/$oneTouchId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = OneTouchModel.fromJson(statusList); deviceStatus = OneTouchModel.fromJson(statusList);
@ -103,8 +98,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
emit(UpdateState(oneTouchModel: deviceStatus)); emit(UpdateState(oneTouchModel: deviceStatus));
} }
void _changeFirstSwitch( void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter<OneTouchState> emit) async {
ChangeFirstSwitchStatusEvent event, Emitter<OneTouchState> emit) async {
emit(LoadingNewSate(oneTouchModel: deviceStatus)); emit(LoadingNewSate(oneTouchModel: deviceStatus));
try { try {
deviceStatus.firstSwitch = !event.value; deviceStatus.firstSwitch = !event.value;
@ -129,20 +123,17 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
} }
void _changeSliding( void _changeSliding(ChangeSlidingSegment event, Emitter<OneTouchState> emit) async {
ChangeSlidingSegment event, Emitter<OneTouchState> emit) async {
emit(ChangeSlidingSegmentState(value: event.value)); emit(ChangeSlidingSegmentState(value: event.value));
} }
void _setCounterValue( void _setCounterValue(SetCounterValue event, Emitter<OneTouchState> emit) async {
SetCounterValue event, Emitter<OneTouchState> emit) async {
emit(LoadingNewSate(oneTouchModel: deviceStatus)); emit(LoadingNewSate(oneTouchModel: deviceStatus));
int seconds = 0; int seconds = 0;
try { try {
seconds = event.duration.inSeconds; seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: oneTouchId, code: event.deviceCode, value: seconds),
deviceId: oneTouchId, code: event.deviceCode, value: seconds),
oneTouchId); oneTouchId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
@ -165,8 +156,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
} }
void _getCounterValue( void _getCounterValue(GetCounterEvent event, Emitter<OneTouchState> emit) async {
GetCounterEvent event, Emitter<OneTouchState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(oneTouchId); var response = await DevicesAPI.getDeviceStatus(oneTouchId);
@ -255,8 +245,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
deviceId: oneTouchId, deviceId: oneTouchId,
); );
List<dynamic> jsonData = response; List<dynamic> jsonData = response;
listSchedule = listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(InitialState()); emit(InitialState());
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -267,13 +256,12 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) { int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null; if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, DateTime dateTimeWithoutSeconds =
dateTime.day, dateTime.hour, dateTime.minute); DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
} }
Future toggleChange( Future toggleChange(ToggleScheduleEvent event, Emitter<OneTouchState> emit) async {
ToggleScheduleEvent event, Emitter<OneTouchState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
final response = await DevicesAPI.changeSchedule( final response = await DevicesAPI.changeSchedule(
@ -292,8 +280,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
} }
Future deleteSchedule( Future deleteSchedule(DeleteScheduleEvent event, Emitter<OneTouchState> emit) async {
DeleteScheduleEvent event, Emitter<OneTouchState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
final response = await DevicesAPI.deleteSchedule( final response = await DevicesAPI.deleteSchedule(
@ -313,8 +300,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
} }
void toggleCreateSchedule( void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<OneTouchState> emit) {
ToggleCreateScheduleEvent event, Emitter<OneTouchState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
createSchedule = !createSchedule; createSchedule = !createSchedule;
selectedDays.clear(); selectedDays.clear();
@ -343,8 +329,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
int selectedTabIndex = 0; int selectedTabIndex = 0;
void toggleSelectedIndex( void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<OneTouchState> emit) {
ToggleSelectedEvent event, Emitter<OneTouchState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
selectedTabIndex = event.index; selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex)); emit(ChangeSlidingSegmentState(value: selectedTabIndex));
@ -353,8 +338,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
List<GroupOneTouchModel> groupOneTouchList = []; List<GroupOneTouchModel> groupOneTouchList = [];
bool allSwitchesOn = true; bool allSwitchesOn = true;
void _fetchOneTouchWizardStatus( void _fetchOneTouchWizardStatus(InitialWizardEvent event, Emitter<OneTouchState> emit) async {
InitialWizardEvent event, Emitter<OneTouchState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
devicesList = []; devicesList = [];
@ -364,8 +348,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', '1GT'); HomeCubit.getInstance().selectedSpace?.id ?? '', '1GT');
for (int i = 0; i < devicesList.length; i++) { for (int i = 0; i < devicesList.length; i++) {
var response = var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = []; List<StatusModel> statusModelList = [];
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
@ -386,16 +369,15 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
return true; return true;
}); });
} }
emit(UpdateGroupState( emit(UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: allSwitchesOn));
oneTouchList: groupOneTouchList, allSwitches: allSwitchesOn));
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
} }
} }
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, void _changeFirstWizardSwitch(
Emitter<OneTouchState> emit) async { ChangeFirstWizardSwitchStatusEvent event, Emitter<OneTouchState> emit) async {
emit(LoadingNewSate(oneTouchModel: deviceStatus)); emit(LoadingNewSate(oneTouchModel: deviceStatus));
try { try {
bool allSwitchesValue = true; bool allSwitchesValue = true;
@ -413,8 +395,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
value: !event.value, value: !event.value,
); );
emit(UpdateGroupState( emit(UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: allSwitchesValue));
oneTouchList: groupOneTouchList, allSwitches: allSwitchesValue));
if (response['success']) { if (response['success']) {
add(InitialEvent(groupScreen: oneTouchGroup)); add(InitialEvent(groupScreen: oneTouchGroup));
} }
@ -432,12 +413,10 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
// Emit the state with updated values // Emit the state with updated values
emit( emit(UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: true));
UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: true));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupOneTouchList.map((device) => device.deviceId).toList();
groupOneTouchList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response1 = await DevicesAPI.deviceBatchController( final response1 = await DevicesAPI.deviceBatchController(
@ -466,12 +445,10 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
} }
// Emit the state with updated values // Emit the state with updated values
emit(UpdateGroupState( emit(UpdateGroupState(oneTouchList: groupOneTouchList, allSwitches: false));
oneTouchList: groupOneTouchList, allSwitches: false));
// Get a list of all device IDs // Get a list of all device IDs
List<String> allDeviceIds = List<String> allDeviceIds = groupOneTouchList.map((device) => device.deviceId).toList();
groupOneTouchList.map((device) => device.deviceId).toList();
// First call for switch_1 // First call for switch_1
final response1 = await DevicesAPI.deviceBatchController( final response1 = await DevicesAPI.deviceBatchController(
@ -495,8 +472,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
String statusSelected = ''; String statusSelected = '';
String optionSelected = ''; String optionSelected = '';
Future<void> _changeStatus( Future<void> _changeStatus(ChangeStatusEvent event, Emitter<OneTouchState> emit) async {
ChangeStatusEvent event, Emitter<OneTouchState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
@ -521,10 +497,7 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
final selectedControl = controlMap[optionSelected]?[statusSelected]; final selectedControl = controlMap[optionSelected]?[statusSelected];
if (selectedControl != null) { if (selectedControl != null) {
await DevicesAPI.controlDevice( await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: oneTouchId, code: optionSelected, value: selectedControl),
deviceId: oneTouchId,
code: optionSelected,
value: selectedControl),
oneTouchId, oneTouchId,
); );
} else { } else {

View File

@ -37,8 +37,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
on<SelectTimeEvent>(selectTimeOfLinePassword); on<SelectTimeEvent>(selectTimeOfLinePassword);
on<SelectTimeOnlinePasswordEvent>(selectTimeOnlinePassword); on<SelectTimeOnlinePasswordEvent>(selectTimeOnlinePassword);
on<DeletePasswordEvent>(deletePassword); on<DeletePasswordEvent>(deletePassword);
on<GenerateAndSavePasswordTimeLimitEvent>( on<GenerateAndSavePasswordTimeLimitEvent>(generateAndSavePasswordTimeLimited);
generateAndSavePasswordTimeLimited);
on<GenerateAndSavePasswordOneTimeEvent>(generateAndSavePasswordOneTime); on<GenerateAndSavePasswordOneTimeEvent>(generateAndSavePasswordOneTime);
on<ToggleDaySelectionEvent>(toggleDaySelection); on<ToggleDaySelectionEvent>(toggleDaySelection);
on<RenamePasswordEvent>(_renamePassword); on<RenamePasswordEvent>(_renamePassword);
@ -60,8 +59,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
List<OfflinePasswordModel>? oneTimePasswords = []; List<OfflinePasswordModel>? oneTimePasswords = [];
List<OfflinePasswordModel>? timeLimitPasswords = []; List<OfflinePasswordModel>? timeLimitPasswords = [];
Future generate7DigitNumber( Future generate7DigitNumber(GeneratePasswordEvent event, Emitter<SmartDoorState> emit) async {
GeneratePasswordEvent event, Emitter<SmartDoorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
passwordController.clear(); passwordController.clear();
Random random = Random(); Random random = Random();
@ -73,8 +71,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
Future generateAndSavePasswordOneTime( Future generateAndSavePasswordOneTime(
GenerateAndSavePasswordOneTimeEvent event, GenerateAndSavePasswordOneTimeEvent event, Emitter<SmartDoorState> emit) async {
Emitter<SmartDoorState> emit) async {
try { try {
if (isSavingPassword) return; if (isSavingPassword) return;
isSavingPassword = true; isSavingPassword = true;
@ -95,8 +92,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
void _fetchSmartDoorStatus( void _fetchSmartDoorStatus(InitialEvent event, Emitter<SmartDoorState> emit) async {
InitialEvent event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
var response = await DevicesAPI.getDeviceStatus(deviceId); var response = await DevicesAPI.getDeviceStatus(deviceId);
@ -106,7 +102,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
deviceStatus = SmartDoorModel.fromJson(statusModelList); deviceStatus = SmartDoorModel.fromJson(statusModelList);
emit(UpdateState(smartDoorModel: deviceStatus)); emit(UpdateState(smartDoorModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(errorMessage: e.toString())); emit(FailedState(errorMessage: e.toString()));
return; return;
@ -115,18 +111,15 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
FirebaseDatabase.instance.ref('device-status/$deviceId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) { stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = SmartDoorModel.fromJson(statusList); deviceStatus = SmartDoorModel.fromJson(statusList);
@ -140,14 +133,11 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
emit(UpdateState(smartDoorModel: deviceStatus)); emit(UpdateState(smartDoorModel: deviceStatus));
} }
void _renamePassword( void _renamePassword(RenamePasswordEvent event, Emitter<SmartDoorState> emit) async {
RenamePasswordEvent event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
await DevicesAPI.renamePass( await DevicesAPI.renamePass(
name: passwordNameController.text, name: passwordNameController.text, doorLockUuid: deviceId, passwordId: passwordId);
doorLockUuid: deviceId,
passwordId: passwordId);
add(InitialOneTimePassword()); add(InitialOneTimePassword());
add(InitialTimeLimitPassword()); add(InitialTimeLimitPassword());
emit(UpdateState(smartDoorModel: deviceStatus)); emit(UpdateState(smartDoorModel: deviceStatus));
@ -157,58 +147,46 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
void getTemporaryPasswords( void getTemporaryPasswords(InitialPasswordsPage event, Emitter<SmartDoorState> emit) async {
InitialPasswordsPage event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
var response = await DevicesAPI.getTemporaryPasswords( var response = await DevicesAPI.getTemporaryPasswords(
deviceId, deviceId,
); );
if (response is List) { if (response is List) {
temporaryPasswords = temporaryPasswords = response.map((item) => TemporaryPassword.fromJson(item)).toList();
response.map((item) => TemporaryPassword.fromJson(item)).toList();
} else if (response is Map && response.containsKey('data')) { } else if (response is Map && response.containsKey('data')) {
temporaryPasswords = (response['data'] as List) temporaryPasswords =
.map((item) => TemporaryPassword.fromJson(item)) (response['data'] as List).map((item) => TemporaryPassword.fromJson(item)).toList();
.toList();
} }
emit(TemporaryPasswordsLoadedState( emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!));
temporaryPassword: temporaryPasswords!));
} catch (e) { } catch (e) {
emit(FailedState(errorMessage: e.toString())); emit(FailedState(errorMessage: e.toString()));
} }
} }
void getOneTimePasswords( void getOneTimePasswords(InitialOneTimePassword event, Emitter<SmartDoorState> emit) async {
InitialOneTimePassword event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
var response = await DevicesAPI.getOneTimePasswords(deviceId); var response = await DevicesAPI.getOneTimePasswords(deviceId);
if (response is List) { if (response is List) {
oneTimePasswords = response oneTimePasswords = response.map((item) => OfflinePasswordModel.fromJson(item)).toList();
.map((item) => OfflinePasswordModel.fromJson(item))
.toList();
} }
emit(TemporaryPasswordsLoadedState( emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!));
temporaryPassword: temporaryPasswords!));
} catch (e) { } catch (e) {
emit(FailedState(errorMessage: e.toString())); emit(FailedState(errorMessage: e.toString()));
} }
} }
void getTimeLimitPasswords( void getTimeLimitPasswords(InitialTimeLimitPassword event, Emitter<SmartDoorState> emit) async {
InitialTimeLimitPassword event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
var response = await DevicesAPI.getTimeLimitPasswords(deviceId); var response = await DevicesAPI.getTimeLimitPasswords(deviceId);
if (response is List) { if (response is List) {
timeLimitPasswords = response timeLimitPasswords = response.map((item) => OfflinePasswordModel.fromJson(item)).toList();
.map((item) => OfflinePasswordModel.fromJson(item))
.toList();
} }
emit(TemporaryPasswordsLoadedState( emit(TemporaryPasswordsLoadedState(temporaryPassword: temporaryPasswords!));
temporaryPassword: temporaryPasswords!));
} catch (e) { } catch (e) {
emit(FailedState(errorMessage: e.toString())); emit(FailedState(errorMessage: e.toString()));
} }
@ -229,8 +207,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
return repeat; return repeat;
} }
bool setStartEndTime( bool setStartEndTime(SetStartEndTimeEvent event, Emitter<SmartDoorState> emit) {
SetStartEndTimeEvent event, Emitter<SmartDoorState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
isStartEndTime = event.val; isStartEndTime = event.val;
emit(IsStartEndState(isStartEndTime: isStartEndTime)); emit(IsStartEndState(isStartEndTime: isStartEndTime));
@ -253,8 +230,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
emit(UpdateState(smartDoorModel: deviceStatus)); emit(UpdateState(smartDoorModel: deviceStatus));
} }
Future<void> selectTimeOfLinePassword( Future<void> selectTimeOfLinePassword(SelectTimeEvent event, Emitter<SmartDoorState> emit) async {
SelectTimeEvent event, Emitter<SmartDoorState> emit) async {
emit(ChangeTimeState()); emit(ChangeTimeState());
final DateTime? picked = await showDatePicker( final DateTime? picked = await showDatePicker(
context: event.context, context: event.context,
@ -284,27 +260,20 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
).millisecondsSinceEpoch ~/ ).millisecondsSinceEpoch ~/
1000; // Divide by 1000 to remove milliseconds 1000; // Divide by 1000 to remove milliseconds
if (event.isEffective) { if (event.isEffective) {
if (expirationTimeTimeStamp != null && if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) {
selectedTimestamp > expirationTimeTimeStamp!) { CustomSnackBar.displaySnackBar('Effective Time cannot be later than Expiration Time.');
CustomSnackBar.displaySnackBar(
'Effective Time cannot be later than Expiration Time.');
} else { } else {
effectiveTime = selectedDateTime effectiveTime =
.toString() selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds
.split('.')
.first; // Remove seconds and milliseconds
effectiveTimeTimeStamp = selectedTimestamp; effectiveTimeTimeStamp = selectedTimestamp;
} }
} else { } else {
if (effectiveTimeTimeStamp != null && if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) {
selectedTimestamp < effectiveTimeTimeStamp!) {
CustomSnackBar.displaySnackBar( CustomSnackBar.displaySnackBar(
'Expiration Time cannot be earlier than Effective Time.'); 'Expiration Time cannot be earlier than Effective Time.');
} else { } else {
expirationTime = selectedDateTime expirationTime =
.toString() selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds
.split('.')
.first; // Remove seconds and milliseconds
expirationTimeTimeStamp = selectedTimestamp; expirationTimeTimeStamp = selectedTimestamp;
} }
} }
@ -360,27 +329,20 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
).millisecondsSinceEpoch ~/ ).millisecondsSinceEpoch ~/
1000; // Divide by 1000 to remove milliseconds 1000; // Divide by 1000 to remove milliseconds
if (event.isEffective) { if (event.isEffective) {
if (expirationTimeTimeStamp != null && if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) {
selectedTimestamp > expirationTimeTimeStamp!) { CustomSnackBar.displaySnackBar('Effective Time cannot be later than Expiration Time.');
CustomSnackBar.displaySnackBar(
'Effective Time cannot be later than Expiration Time.');
} else { } else {
effectiveTime = selectedDateTime effectiveTime =
.toString() selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds
.split('.')
.first; // Remove seconds and milliseconds
effectiveTimeTimeStamp = selectedTimestamp; effectiveTimeTimeStamp = selectedTimestamp;
} }
} else { } else {
if (effectiveTimeTimeStamp != null && if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) {
selectedTimestamp < effectiveTimeTimeStamp!) {
CustomSnackBar.displaySnackBar( CustomSnackBar.displaySnackBar(
'Expiration Time cannot be earlier than Effective Time.'); 'Expiration Time cannot be earlier than Effective Time.');
} else { } else {
expirationTime = selectedDateTime expirationTime =
.toString() selectedDateTime.toString().split('.').first; // Remove seconds and milliseconds
.split('.')
.first; // Remove seconds and milliseconds
expirationTimeTimeStamp = selectedTimestamp; expirationTimeTimeStamp = selectedTimestamp;
} }
} }
@ -389,8 +351,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
Future<void> savePassword( Future<void> savePassword(SavePasswordEvent event, Emitter<SmartDoorState> emit) async {
SavePasswordEvent event, Emitter<SmartDoorState> emit) async {
if (_validateInputs() || isSavingPassword) return; if (_validateInputs() || isSavingPassword) return;
try { try {
isSavingPassword = true; isSavingPassword = true;
@ -420,8 +381,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
Future<void> generateAndSavePasswordTimeLimited( Future<void> generateAndSavePasswordTimeLimited(
GenerateAndSavePasswordTimeLimitEvent event, GenerateAndSavePasswordTimeLimitEvent event, Emitter<SmartDoorState> emit) async {
Emitter<SmartDoorState> emit) async {
if (timeLimitValidate() || isSavingPassword) return; if (timeLimitValidate() || isSavingPassword) return;
try { try {
isSavingPassword = true; isSavingPassword = true;
@ -447,12 +407,10 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
} }
Future<void> deletePassword( Future<void> deletePassword(DeletePasswordEvent event, Emitter<SmartDoorState> emit) async {
DeletePasswordEvent event, Emitter<SmartDoorState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
await DevicesAPI.deletePassword( await DevicesAPI.deletePassword(deviceId: deviceId, passwordId: event.passwordId)
deviceId: deviceId, passwordId: event.passwordId)
.then((value) async { .then((value) async {
add(InitialPasswordsPage()); add(InitialPasswordsPage());
}); });
@ -487,8 +445,7 @@ class SmartDoorBloc extends Bloc<SmartDoorEvent, SmartDoorState> {
} }
if (repeat == true && (endTime == null || startTime == null)) { if (repeat == true && (endTime == null || startTime == null)) {
CustomSnackBar.displaySnackBar( CustomSnackBar.displaySnackBar('Start Time and End time and the days required ');
'Start Time and End time and the days required ');
return true; return true;
} }
return false; return false;

View File

@ -101,7 +101,7 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
} }
deviceStatus = ThreeGangModel.fromJson(statusModelList); deviceStatus = ThreeGangModel.fromJson(statusModelList);
emit(UpdateState(threeGangModel: deviceStatus)); emit(UpdateState(threeGangModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} }
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));

View File

@ -107,7 +107,7 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
} }
deviceStatus = ThreeTouchModel.fromJson(statusModelList); deviceStatus = ThreeTouchModel.fromJson(statusModelList);
emit(UpdateState(threeTouchModel: deviceStatus)); emit(UpdateState(threeTouchModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} }
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));

View File

@ -89,7 +89,7 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
} }
deviceStatus = TwoGangModel.fromJson(statusModelList); deviceStatus = TwoGangModel.fromJson(statusModelList);
emit(UpdateState(twoGangModel: deviceStatus)); emit(UpdateState(twoGangModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;

View File

@ -95,7 +95,7 @@ class TwoTouchBloc extends Bloc<TwoTouchEvent, TwoTouchState> {
} }
deviceStatus = TwoTouchModel.fromJson(statusModelList); deviceStatus = TwoTouchModel.fromJson(statusModelList);
emit(UpdateState(twoTouchModel: deviceStatus)); emit(UpdateState(twoTouchModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;

View File

@ -20,9 +20,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
on<WallSensorUpdatedEvent>(_wallSensorUpdated); on<WallSensorUpdatedEvent>(_wallSensorUpdated);
} }
void _fetchCeilingSensorStatus( void _fetchCeilingSensorStatus(InitialEvent event, Emitter<WallSensorState> emit) async {
InitialEvent event,
Emitter<WallSensorState> emit) async {
emit(LoadingInitialState()); emit(LoadingInitialState());
try { try {
var response = await DevicesAPI.getDeviceStatus(deviceId); var response = await DevicesAPI.getDeviceStatus(deviceId);
@ -32,7 +30,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
} }
deviceStatus = WallSensorModel.fromJson(statusModelList); deviceStatus = WallSensorModel.fromJson(statusModelList);
emit(UpdateState(wallSensorModel: deviceStatus)); emit(UpdateState(wallSensorModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(FailedState(error: e.toString())); emit(FailedState(error: e.toString()));
return; return;
@ -41,18 +39,15 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
FirebaseDatabase.instance.ref('device-status/$deviceId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) { stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = WallSensorModel.fromJson(statusList); deviceStatus = WallSensorModel.fromJson(statusList);
@ -61,19 +56,15 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
} catch (_) {} } catch (_) {}
} }
_wallSensorUpdated( _wallSensorUpdated(WallSensorUpdatedEvent event, Emitter<WallSensorState> emit) {
WallSensorUpdatedEvent event, Emitter<WallSensorState> emit) {
emit(UpdateState(wallSensorModel: deviceStatus)); emit(UpdateState(wallSensorModel: deviceStatus));
} }
void _changeIndicator( void _changeIndicator(ChangeIndicatorEvent event, Emitter<WallSensorState> emit) async {
ChangeIndicatorEvent event, Emitter<WallSensorState> emit) async {
emit(LoadingNewSate(wallSensorModel: deviceStatus)); emit(LoadingNewSate(wallSensorModel: deviceStatus));
try { try {
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: deviceId, code: 'indicator', value: !event.value), deviceId);
deviceId: deviceId, code: 'indicator', value: !event.value),
deviceId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
deviceStatus.indicator = !event.value; deviceStatus.indicator = !event.value;
@ -82,14 +73,11 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
emit(UpdateState(wallSensorModel: deviceStatus)); emit(UpdateState(wallSensorModel: deviceStatus));
} }
void _changeValue( void _changeValue(ChangeValueEvent event, Emitter<WallSensorState> emit) async {
ChangeValueEvent event, Emitter<WallSensorState> emit) async {
emit(LoadingNewSate(wallSensorModel: deviceStatus)); emit(LoadingNewSate(wallSensorModel: deviceStatus));
try { try {
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: deviceId, code: event.code, value: event.value), deviceId);
deviceId: deviceId, code: event.code, value: event.value),
deviceId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
if (event.code == 'far_detection') { if (event.code == 'far_detection') {

View File

@ -35,8 +35,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
List<ScheduleModel> listSchedule = []; List<ScheduleModel> listSchedule = [];
DateTime? selectedTime = DateTime.now(); DateTime? selectedTime = DateTime.now();
WaterHeaterBloc({required this.whId, required this.switchCode}) WaterHeaterBloc({required this.whId, required this.switchCode}) : super(WHInitialState()) {
: super(WHInitialState()) {
on<WaterHeaterInitial>(_fetchWaterHeaterStatus); on<WaterHeaterInitial>(_fetchWaterHeaterStatus);
on<WaterHeaterSwitch>(_changeFirstSwitch); on<WaterHeaterSwitch>(_changeFirstSwitch);
on<SetCounterValue>(_setCounterValue); on<SetCounterValue>(_setCounterValue);
@ -61,8 +60,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
on<WaterHeaterUpdated>(_waterHeaterUpdated); on<WaterHeaterUpdated>(_waterHeaterUpdated);
} }
void _fetchWaterHeaterStatus( void _fetchWaterHeaterStatus(WaterHeaterInitial event, Emitter<WaterHeaterState> emit) async {
WaterHeaterInitial event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState()); emit(WHLoadingState());
try { try {
var response = await DevicesAPI.getDeviceStatus(whId); var response = await DevicesAPI.getDeviceStatus(whId);
@ -74,7 +72,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
statusModelList, statusModelList,
); );
emit(UpdateState(whModel: deviceStatus)); emit(UpdateState(whModel: deviceStatus));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(WHFailedState(errorMessage: e.toString())); emit(WHFailedState(errorMessage: e.toString()));
return; return;
@ -83,21 +81,18 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$whId');
FirebaseDatabase.instance.ref('device-status/$whId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {
statusList statusList.add(StatusModel(code: element['code'], value: element['value']));
.add(StatusModel(code: element['code'], value: element['value']));
}); });
deviceStatus = WHModel.fromJson(statusList); deviceStatus = WHModel.fromJson(statusList);
@ -108,14 +103,12 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} catch (_) {} } catch (_) {}
} }
_waterHeaterUpdated( _waterHeaterUpdated(WaterHeaterUpdated event, Emitter<WaterHeaterState> emit) async {
WaterHeaterUpdated event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState()); emit(WHLoadingState());
emit(UpdateState(whModel: deviceStatus)); emit(UpdateState(whModel: deviceStatus));
} }
void _changeFirstSwitch( void _changeFirstSwitch(WaterHeaterSwitch event, Emitter<WaterHeaterState> emit) async {
WaterHeaterSwitch event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus)); emit(LoadingNewSate(whModel: deviceStatus));
try { try {
deviceStatus.firstSwitch = !event.whSwitch; deviceStatus.firstSwitch = !event.whSwitch;
@ -125,10 +118,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
_timer = Timer(const Duration(milliseconds: 500), () async { _timer = Timer(const Duration(milliseconds: 500), () async {
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: whId, code: 'switch_1', value: deviceStatus.firstSwitch),
deviceId: whId,
code: 'switch_1',
value: deviceStatus.firstSwitch),
whId); whId);
if (!response['success']) { if (!response['success']) {
@ -142,16 +132,13 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
//=====================---------- timer ---------------------------------------- //=====================---------- timer ----------------------------------------
void _setCounterValue( void _setCounterValue(SetCounterValue event, Emitter<WaterHeaterState> emit) async {
SetCounterValue event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus)); emit(LoadingNewSate(whModel: deviceStatus));
int seconds = 0; int seconds = 0;
try { try {
seconds = event.duration.inSeconds; seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice( final response = await DevicesAPI.controlDevice(
DeviceControlModel( DeviceControlModel(deviceId: whId, code: event.deviceCode, value: seconds), whId);
deviceId: whId, code: event.deviceCode, value: seconds),
whId);
if (response['success'] ?? false) { if (response['success'] ?? false) {
if (event.deviceCode == 'countdown_1') { if (event.deviceCode == 'countdown_1') {
@ -173,8 +160,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
} }
void _getCounterValue( void _getCounterValue(GetCounterEvent event, Emitter<WaterHeaterState> emit) async {
GetCounterEvent event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState()); emit(WHLoadingState());
try { try {
var response = await DevicesAPI.getDeviceStatus(whId); var response = await DevicesAPI.getDeviceStatus(whId);
@ -264,8 +250,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
deviceId: whId, deviceId: whId,
); );
List<dynamic> jsonData = response; List<dynamic> jsonData = response;
listSchedule = listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(WHInitialState()); emit(WHInitialState());
} on DioException catch (e) { } on DioException catch (e) {
final errorData = e.response!.data; final errorData = e.response!.data;
@ -276,13 +261,12 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) { int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null; if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month, DateTime dateTimeWithoutSeconds =
dateTime.day, dateTime.hour, dateTime.minute); DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000; return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
} }
Future toggleChange( Future toggleChange(ToggleScheduleEvent event, Emitter<WaterHeaterState> emit) async {
ToggleScheduleEvent event, Emitter<WaterHeaterState> emit) async {
try { try {
emit(WHLoadingState()); emit(WHLoadingState());
final response = await DevicesAPI.changeSchedule( final response = await DevicesAPI.changeSchedule(
@ -300,8 +284,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
} }
Future deleteSchedule( Future deleteSchedule(DeleteScheduleEvent event, Emitter<WaterHeaterState> emit) async {
DeleteScheduleEvent event, Emitter<WaterHeaterState> emit) async {
try { try {
emit(WHLoadingState()); emit(WHLoadingState());
final response = await DevicesAPI.deleteSchedule( final response = await DevicesAPI.deleteSchedule(
@ -320,8 +303,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
} }
void _toggleCreateCirculate( void _toggleCreateCirculate(ToggleCreateCirculate event, Emitter<WaterHeaterState> emit) {
ToggleCreateCirculate event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState()); emit(WHLoadingState());
createCirculate = !createCirculate; createCirculate = !createCirculate;
selectedDays.clear(); selectedDays.clear();
@ -329,15 +311,13 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
emit(UpdateCreateScheduleState(createCirculate)); emit(UpdateCreateScheduleState(createCirculate));
} }
void toggleSelectedIndex( void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<WaterHeaterState> emit) {
ToggleSelectedEvent event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState()); emit(WHLoadingState());
selectedTabIndex = event.index; selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex)); emit(ChangeSlidingSegmentState(value: selectedTabIndex));
} }
void toggleCreateSchedule( void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<WaterHeaterState> emit) {
ToggleCreateScheduleEvent event, Emitter<WaterHeaterState> emit) {
emit(WHLoadingState()); emit(WHLoadingState());
createSchedule = !createSchedule; createSchedule = !createSchedule;
selectedDays.clear(); selectedDays.clear();
@ -386,8 +366,8 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
List<GroupWHModel> groupWaterHeaterList = []; List<GroupWHModel> groupWaterHeaterList = [];
bool allSwitchesOn = true; bool allSwitchesOn = true;
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event, void _changeFirstWizardSwitch(
Emitter<WaterHeaterState> emit) async { ChangeFirstWizardSwitchStatusEvent event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus)); emit(LoadingNewSate(whModel: deviceStatus));
try { try {
bool allSwitchesValue = true; bool allSwitchesValue = true;
@ -399,8 +379,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
allSwitchesValue = false; allSwitchesValue = false;
} }
}); });
emit(UpdateGroupState( emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: allSwitchesValue));
twoGangList: groupWaterHeaterList, allSwitches: allSwitchesValue));
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
code: 'switch_1', code: 'switch_1',
@ -415,8 +394,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
} }
void _fetchWHWizardStatus( void _fetchWHWizardStatus(InitialWizardEvent event, Emitter<WaterHeaterState> emit) async {
InitialWizardEvent event, Emitter<WaterHeaterState> emit) async {
emit(WHLoadingState()); emit(WHLoadingState());
try { try {
devicesList = []; devicesList = [];
@ -426,8 +404,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', 'WH'); HomeCubit.getInstance().selectedSpace?.id ?? '', 'WH');
for (int i = 0; i < devicesList.length; i++) { for (int i = 0; i < devicesList.length; i++) {
var response = var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = []; List<StatusModel> statusModelList = [];
for (var status in response['status']) { for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status)); statusModelList.add(StatusModel.fromJson(status));
@ -449,27 +426,23 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
return true; return true;
}); });
} }
emit(UpdateGroupState( emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: allSwitchesOn));
twoGangList: groupWaterHeaterList, allSwitches: allSwitchesOn));
} catch (e) { } catch (e) {
// emit(FailedState(error: e.toString())); // emit(FailedState(error: e.toString()));
return; return;
} }
} }
void _groupAllOn( void _groupAllOn(GroupAllOnEvent event, Emitter<WaterHeaterState> emit) async {
GroupAllOnEvent event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus)); emit(LoadingNewSate(whModel: deviceStatus));
try { try {
for (int i = 0; i < groupWaterHeaterList.length; i++) { for (int i = 0; i < groupWaterHeaterList.length; i++) {
groupWaterHeaterList[i].firstSwitch = true; groupWaterHeaterList[i].firstSwitch = true;
} }
emit(UpdateGroupState( emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: true));
twoGangList: groupWaterHeaterList, allSwitches: true));
List<String> allDeviceIds = List<String> allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList();
groupWaterHeaterList.map((device) => device.deviceId).toList();
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
code: 'switch_1', code: 'switch_1',
@ -487,18 +460,15 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
} }
} }
void _groupAllOff( void _groupAllOff(GroupAllOffEvent event, Emitter<WaterHeaterState> emit) async {
GroupAllOffEvent event, Emitter<WaterHeaterState> emit) async {
emit(LoadingNewSate(whModel: deviceStatus)); emit(LoadingNewSate(whModel: deviceStatus));
try { try {
for (int i = 0; i < groupWaterHeaterList.length; i++) { for (int i = 0; i < groupWaterHeaterList.length; i++) {
groupWaterHeaterList[i].firstSwitch = false; groupWaterHeaterList[i].firstSwitch = false;
} }
emit(UpdateGroupState( emit(UpdateGroupState(twoGangList: groupWaterHeaterList, allSwitches: false));
twoGangList: groupWaterHeaterList, allSwitches: false));
List<String> allDeviceIds = List<String> allDeviceIds = groupWaterHeaterList.map((device) => device.deviceId).toList();
groupWaterHeaterList.map((device) => device.deviceId).toList();
final response = await DevicesAPI.deviceBatchController( final response = await DevicesAPI.deviceBatchController(
code: 'switch_1', code: 'switch_1',

View File

@ -25,11 +25,9 @@ class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
bool lowBattery = false; bool lowBattery = false;
bool closingReminder = false; bool closingReminder = false;
bool waterAlarm = false; bool waterAlarm = false;
WaterLeakModel deviceStatus = WaterLeakModel deviceStatus = WaterLeakModel(waterContactState: 'normal', batteryPercentage: 0);
WaterLeakModel(waterContactState: 'normal', batteryPercentage: 0);
void _fetchStatus( void _fetchStatus(WaterLeakInitial event, Emitter<WaterLeakState> emit) async {
WaterLeakInitial event, Emitter<WaterLeakState> emit) async {
emit(WaterLeakLoadingState()); emit(WaterLeakLoadingState());
try { try {
var response = await DevicesAPI.getDeviceStatus(WLId); var response = await DevicesAPI.getDeviceStatus(WLId);
@ -43,15 +41,14 @@ class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
emit(UpdateState(waterSensor: deviceStatus)); emit(UpdateState(waterSensor: deviceStatus));
Future.delayed(const Duration(milliseconds: 500)); Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges(); _listenToChanges();
} catch (e) { } catch (e) {
emit(WaterLeakFailedState(errorMessage: e.toString())); emit(WaterLeakFailedState(errorMessage: e.toString()));
return; return;
} }
} }
void _toggleLowBattery( void _toggleLowBattery(ToggleLowBatteryEvent event, Emitter<WaterLeakState> emit) async {
ToggleLowBatteryEvent event, Emitter<WaterLeakState> emit) async {
emit(LoadingNewSate(waterSensor: deviceStatus)); emit(LoadingNewSate(waterSensor: deviceStatus));
try { try {
lowBattery = event.isLowBatteryEnabled; lowBattery = event.isLowBatteryEnabled;
@ -90,8 +87,7 @@ class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
} }
} }
void _toggleWaterLeakAlarm( void _toggleWaterLeakAlarm(ToggleWaterLeakAlarmEvent event, Emitter<WaterLeakState> emit) async {
ToggleWaterLeakAlarmEvent event, Emitter<WaterLeakState> emit) async {
emit(LoadingNewSate(waterSensor: deviceStatus)); emit(LoadingNewSate(waterSensor: deviceStatus));
try { try {
waterAlarm = event.isWaterLeakAlarmEnabled; waterAlarm = event.isWaterLeakAlarmEnabled;
@ -109,11 +105,9 @@ class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
} }
} }
DeviceReport recordGroups = DeviceReport recordGroups = DeviceReport(startTime: '0', endTime: '0', data: []);
DeviceReport(startTime: '0', endTime: '0', data: []);
Future<void> fetchLogsForLastMonth( Future<void> fetchLogsForLastMonth(ReportLogsInitial event, Emitter<WaterLeakState> emit) async {
ReportLogsInitial event, Emitter<WaterLeakState> emit) async {
DateTime now = DateTime.now(); DateTime now = DateTime.now();
DateTime lastMonth = DateTime(now.year, now.month - 1, now.day); DateTime lastMonth = DateTime(now.year, now.month - 1, now.day);
int startTime = lastMonth.millisecondsSinceEpoch; int startTime = lastMonth.millisecondsSinceEpoch;
@ -137,16 +131,14 @@ class WaterLeakBloc extends Bloc<WaterLeakEvent, WaterLeakState> {
_listenToChanges() { _listenToChanges() {
try { try {
DatabaseReference ref = DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$WLId');
FirebaseDatabase.instance.ref('device-status/$WLId');
Stream<DatabaseEvent> stream = ref.onValue; Stream<DatabaseEvent> stream = ref.onValue;
stream.listen((DatabaseEvent event) async { stream.listen((DatabaseEvent event) async {
if (_timer != null) { if (_timer != null) {
await Future.delayed(const Duration(seconds: 2)); await Future.delayed(const Duration(seconds: 2));
} }
Map<dynamic, dynamic> usersMap = Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = []; List<StatusModel> statusList = [];
usersMap['status'].forEach((element) { usersMap['status'].forEach((element) {

View File

@ -5,7 +5,7 @@ description: This is the mobile application project, developed with Flutter for
# pub.dev using `flutter pub publish`. This is preferred for private packages. # pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev publish_to: "none" # Remove this line if you wish to publish to pub.dev
version: 1.0.5+33 version: 1.0.5+34
environment: environment:
sdk: ">=3.0.6 <4.0.0" sdk: ">=3.0.6 <4.0.0"