Compare commits

..

31 Commits

Author SHA1 Message Date
73d28a1800 Refactor Action class to use type annotations for actionExecutor and entityId 2025-04-17 10:41:01 +03:00
5493ca6fb0 Refactor device filtering logic to improve code readability 2025-04-17 10:38:25 +03:00
7005d8ba83 Refactor device filtering logic and improve code readability
- Extracted the logic for filtering implemented devices into a separate method `_getOnlyImplementedDevices`
- Created a set `allowedDevices` to store the allowed device types
- Updated the filtering logic to use the `allowedDevices` set for checking device types
- Removed unnecessary conditions for filtering devices

Fix nullability issues in `Action` model

- Added null checks for `actionExecutor`, `entityId`, `name`, `type`, and `productType` properties in the `fromJson` method of the `Action` model
- Set default values for `actionExecutor` and `entityId` if they are null
- Updated the type casting for `name`, `type`, and `productType` properties to avoid potential nullability issues
2025-04-17 10:16:10 +03:00
1cff69d496 change icon 2025-04-17 09:39:58 +03:00
60df77efad add OneGang product type to routine 2025-04-17 09:32:20 +03:00
ccde857c29 Merge pull request #80 from SyncrowIOT/SP-1398-FE-in-the-wizerd-the-batch-control-title-doesn-t-represent-the-the-accurate-device-name
SP-1398-FE-in-the-wizerd-the-batch-control-title-doesn-t-represent-the-the-accurate-device-name
2025-04-13 16:23:49 +03:00
b2a8086e0e Merge pull request #79 from SyncrowIOT/sp-1268-rework-v2
Sp 1268 rework v2
2025-04-13 16:20:10 +03:00
408e78962c SP-1398 2025-04-13 16:18:49 +03:00
dcdbc02ca0 Adds AppLoadingIndicator widget and replaces CircularProgressIndicator in SceneView. 2025-04-13 15:50:52 +03:00
31025e9176 Refactors SceneView constructor and improves conditional rendering for automation list 2025-04-13 15:49:13 +03:00
8219de6821 Injects SceneBloc using the new factory. 2025-04-13 15:28:44 +03:00
fbdf3817ab Created a factory helper to create a SceneBloc. 2025-04-13 15:25:48 +03:00
17422edd0d sp-1268-rework-v2. 2025-04-13 15:21:20 +03:00
9472390284 Merge pull request #76 from SyncrowIOT/bugifx/empty-subspace-routine-creation
fixed issue on empty subspace
2025-03-28 11:38:14 +04:00
731ba0f3d6 Merge pull request #77 from SyncrowIOT/SP-1268-FE-Implement-UX-Behavior-for-No-Tab-to-Run-Scene-in-Device-Screen
Sp 1268 fe implement ux behavior for no tab to run scene in device screen
2025-03-26 15:24:34 +03:00
56407c6426 indentation and trailing commas. 2025-03-26 13:49:54 +03:00
02d61ca0bb Refactor DevicesViewBody and SceneView to improve widget structure and replace CreateUnitWidget with EmptyDevicesWidget for better handling of empty states. 2025-03-26 13:44:49 +03:00
99ee4b9878 Add EmptyDevicesWidget to display message when no routines are available. 2025-03-26 13:34:07 +03:00
19edd0a275 Added /android/app/.cxx/ to .gitIgnore, because they're auto generated files that dont need to be checked into source control. 2025-03-26 13:14:23 +03:00
ef5e7c3154 fixed issue on empty subspace 2025-03-25 14:15:14 +04:00
80dd0f696f Merge pull request #75 from SyncrowIOT/SP-1245
updated endpoint for automation
2025-03-17 09:34:46 +04:00
a64a41548f updated delete endpoint for automation 2025-03-14 13:02:14 +04:00
0d50aa68fa updated endpoint for update automation 2025-03-14 12:58:12 +04:00
88aac86b10 updated endpoint for getting automation by id 2025-03-14 12:55:33 +04:00
0673548745 changed endpoint for getting automations by space 2025-03-14 12:53:29 +04:00
c2fc8fa0ae changed endpoint for create automation endpoint 2025-03-14 12:40:52 +04:00
cbf10bbf78 Merge pull request #74 from SyncrowIOT/real_time_app
Real time app
2025-03-03 17:34:34 +03:00
d95588ce84 remove unused code 2025-03-03 17:34:15 +03:00
7e2e591d71 remove unused code 2025-03-01 15:19:15 +03:00
2ec81bda9c connect the real time for all devices 2025-03-01 15:08:51 +03:00
3b0f51473c Merge pull request #73 from SyncrowIOT/SP-1190
Sp 1190
2025-02-26 12:20:06 +03:00
35 changed files with 1997 additions and 1083 deletions

1
.gitignore vendored
View File

@ -42,3 +42,4 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
/android/app/.cxx/

View File

@ -1,4 +1,5 @@
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/curtain_bloc/curtain_event.dart';
@ -31,6 +32,7 @@ class CurtainBloc extends Bloc<CurtainEvent, CurtainState> {
on<InitialWizardEvent>(_fetchWizardStatus);
on<GroupAllOffEvent>(_groupAllOff);
on<GroupAllOnEvent>(_groupAllOn);
on<UpdateCurtainEvent>(_updateCurtain);
}
Future<void> _onOpenCurtain(
@ -162,7 +164,10 @@ class CurtainBloc extends Bloc<CurtainEvent, CurtainState> {
void _fetchStatus(InitCurtain event, Emitter<CurtainState> emit) async {
try {
emit(CurtainLoadingState());
_listenToChanges(curtainId);
var response = await DevicesAPI.getDeviceStatus(curtainId);
List<StatusModel> statusModelList = [];
for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status));
@ -170,7 +175,6 @@ class CurtainBloc extends Bloc<CurtainEvent, CurtainState> {
openPercentage = double.tryParse(statusModelList[1].value.toString())!;
curtainWidth = 270 - (openPercentage / 100) * curtainOpeningSpace;
blindHeight = 310 - (openPercentage / 100) * blindOpeningSpace;
// _listenToChanges();
emit(CurtainsOpening(
curtainWidth: curtainWidth,
blindHeight: blindHeight,
@ -181,38 +185,76 @@ class CurtainBloc extends Bloc<CurtainEvent, CurtainState> {
return;
}
}
// Real-time Database
// StreamSubscription<DatabaseEvent>? _streamSubscription;
// Timer? _timer;
// void _listenToChanges() {
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges(curtainId) {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$curtainId');
Stream<DatabaseEvent> stream = ref.onValue;
_streamSubscription = stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
openPercentage = double.tryParse(statusList[1].value.toString())!;
curtainWidth = 270 - (openPercentage / 100) * curtainOpeningSpace;
blindHeight = 310 - (openPercentage / 100) * blindOpeningSpace;
add(UpdateCurtainEvent());
});
} catch (_) {}
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
// _listenToChanges(curtainId) {
// try {
// _streamSubscription?.cancel();
// print('curtainId=$curtainId');
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$curtainId');
// Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = CurtainModel.fromJson(statusList);
// if (!isClosed) {}
// List<StatusModel> statusModelList = [];
// for (var status in usersMap['status']) {
// statusModelList.add(StatusModel.fromJson(status));
// print('statusModelList==${statusModelList}');
// }
// openPercentage = double.tryParse(statusModelList[1].value.toString())!;
// curtainWidth = 270 - (openPercentage / 100) * curtainOpeningSpace;
// blindHeight = 310 - (openPercentage / 100) * blindOpeningSpace;
// add(UpdateCurtainEvent());
// });
// } catch (_) {}
// }
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
_updateCurtain(UpdateCurtainEvent event, Emitter<CurtainState> emit) {
curtainWidth = 270 - (openPercentage / 100) * curtainOpeningSpace;
blindHeight = 310 - (openPercentage / 100) * blindOpeningSpace;
emit(CurtainsOpening(
curtainWidth: curtainWidth,
blindHeight: blindHeight,
openPercentage: openPercentage,
));
}
List<GroupCurtainModel> groupList = [];
bool allSwitchesOn = true;

View File

@ -33,6 +33,7 @@ class InitCurtain extends CurtainEvent {}
class PauseCurtain extends CurtainEvent {}
class useCurtainEvent extends CurtainEvent {}
class InitialWizardEvent extends CurtainEvent {}
class UpdateCurtainEvent extends CurtainEvent {}
class ChangeFirstWizardSwitchStatusEvent extends CurtainEvent {

View File

@ -169,18 +169,19 @@ class DeviceManagerBloc extends Bloc<DeviceManagerEvent, DeviceManagerState> {
}
}
_getOnlyImplementedDevices(List<DeviceModel> devices) {
List<DeviceModel> implementedDevices = [];
for (int i = 0; i < devices.length; i++) {
if (devices[i].productType == DeviceType.AC ||
devices[i].productType == DeviceType.DoorLock ||
devices[i].productType == DeviceType.Gateway ||
devices[i].productType == DeviceType.WallSensor ||
devices[i].productType == DeviceType.CeilingSensor ||
devices[i].productType == DeviceType.ThreeGang) {
implementedDevices.add(devices[i]);
}
}
return implementedDevices;
List<DeviceModel> _getOnlyImplementedDevices(List<DeviceModel> devices) {
const allowedDeviceTypes = {
DeviceType.AC,
DeviceType.DoorLock,
DeviceType.Gateway,
DeviceType.WallSensor,
DeviceType.CeilingSensor,
DeviceType.ThreeGang,
DeviceType.OneGang,
};
return devices
.where((device) => allowedDeviceTypes.contains(device.productType))
.toList();
}
}

View File

@ -86,7 +86,7 @@ class DevicesCubit extends Cubit<DevicesState> {
}
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
//print('object-----${usersMap['status']}');
// print('object-----${usersMap['status']}');
List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList
@ -463,7 +463,15 @@ class DevicesCubit extends Cubit<DevicesState> {
projectId: project?.uuid ?? TempConst.projectIdDev);
allDevices = devices;
for (var deviceId in allDevices) {
if (deviceId.type == "3G" || deviceId.type == "AC") {
if (deviceId.type == "3G" ||
deviceId.type == "2G" ||
deviceId.type == "1G" ||
deviceId.type == "3GT" ||
deviceId.type == "2GT" ||
deviceId.type == "1GT" ||
deviceId.type == "WH" ||
deviceId.type == "CUR" ||
deviceId.type == "AC") {
_listenToChanges(deviceId.uuid);
}
}
@ -561,7 +569,6 @@ class DevicesCubit extends Cubit<DevicesState> {
}
}
Future<void> towGangToggle(
DeviceControlModel control, String deviceUuid) async {
emit(SwitchControlLoading(code: control.code));
@ -653,7 +660,6 @@ class DevicesCubit extends Cubit<DevicesState> {
code: 'switch_1', value: toggledValue, deviceId: deviceUuid);
final response =
await DevicesAPI.controlDevice(controlRequest, deviceUuid);
print(response);
if (response['result'] != true) {
throw Exception('Failed to toggle switch_1');
}

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/door_sensor_bloc/door_sensor_event.dart';
import 'package:syncrow_app/features/devices/bloc/door_sensor_bloc/door_sensor_state.dart';
@ -40,7 +41,7 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
);
emit(UpdateState(doorSensor: deviceStatus));
Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges();
_listenToChanges();
} catch (e) {
emit(DoorSensorFailedState(errorMessage: e.toString()));
return;
@ -136,41 +137,42 @@ class DoorSensorBloc extends Bloc<DoorSensorEvent, DoorSensorState> {
String errorMessage = errorData['message'];
}
}
// real-time database
// Timer? _timer;
// StreamSubscription<DatabaseEvent>? _streamSubscription;
// void _listenToChanges() {
// try {
// _streamSubscription?.cancel();
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$DSId');
// Stream<DatabaseEvent> stream = ref.onValue;
Timer? _timer;
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges() {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$DSId');
Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = DoorSensorModel.fromJson(statusList);
// if (!isClosed) {
// add(
// DoorSensorSwitch(switchD: deviceStatus.doorContactState),
// );
// }
// });
// } catch (_) {}
// }
_streamSubscription = stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 2));
}
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
deviceStatus = DoorSensorModel.fromJson(statusList);
if (!isClosed) {
add(
DoorSensorSwitch(switchD: deviceStatus.doorContactState),
);
}
});
} catch (_) {}
}
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
}

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/garage_door_bloc/garage_door_event.dart';
@ -41,6 +42,8 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
on<ChangeFirstWizardSwitchStatusEvent>(_changeFirstWizardSwitch);
on<ToggleAlarmEvent>(_toggleAlarmEvent);
on<DeleteScheduleEvent>(deleteSchedule);
on<UpdateStateEvent>(_updateState);
}
void _onClose(OnClose event, Emitter<GarageDoorSensorState> emit) {
_timer?.cancel();
@ -79,7 +82,7 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
toggleDoor = deviceStatus.switch1;
emit(UpdateState(garageSensor: deviceStatus));
Future.delayed(const Duration(milliseconds: 500));
// _listenToChanges();
_listenToChanges();
} catch (e) {
emit(GarageDoorFailedState(errorMessage: e.toString()));
return;
@ -179,39 +182,57 @@ class GarageDoorBloc extends Bloc<GarageDoorEvent, GarageDoorSensorState> {
}
// Real-time db
// StreamSubscription<DatabaseEvent>? _streamSubscription;
// void _listenToChanges() {
// try {
// _streamSubscription?.cancel();
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$GDId');
// Stream<DatabaseEvent> stream = ref.onValue;
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges() {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$GDId');
Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = GarageDoorModel.fromJson(statusList);
// // if (!isClosed) {
// // add(ToggleSelectedEvent());
// // }
// });
// } catch (_) {}
// }
_streamSubscription = stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 1));
}
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
if (event.snapshot.value != null) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList.add(
StatusModel(code: element['code'], value: element['value']));
});
deviceStatus.tr_timecon = statusList
.firstWhere((status) => status.code == "tr_timecon",
orElse: () => StatusModel(code: "tr_timecon", value: 0))
.value as int;
deviceStatus.switch1 = statusList
.firstWhere((status) => status.code == "switch_1",
orElse: () => StatusModel(code: "switch_1", value: false))
.value as bool;
secondSelected = deviceStatus.tr_timecon;
toggleDoor = deviceStatus.switch1;
add(UpdateStateEvent());
}
});
} catch (_) {}
}
Future<void> _updateState(
UpdateStateEvent event, Emitter<GarageDoorSensorState> emit) async {
emit(GarageDoorLoadingState());
emit(UpdateState(garageSensor: deviceStatus));
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
List<Map<String, String>> days = [
{"day": "Sun", "key": "Sun"},

View File

@ -109,6 +109,8 @@ class GetScheduleEvent extends GarageDoorEvent {}
class ScheduleSaveapp extends GarageDoorEvent {}
class UpdateStateEvent extends GarageDoorEvent {}
class ToggleScheduleEvent extends GarageDoorEvent {
final String id;
final bool toggle;

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/one_gang_bloc/one_gang_state.dart';
@ -60,48 +61,46 @@ class OneGangBloc extends Bloc<OneGangEvent, OneGangState> {
}
deviceStatus = OneGangModel.fromJson(statusModelList);
emit(UpdateState(oneGangModel: deviceStatus));
// _listenToChanges();
_listenToChanges(oneGangId);
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
}
// Real-time db
// StreamSubscription<DatabaseEvent>? _streamSubscription;
// void _listenToChanges() {
// try {
// _streamSubscription?.cancel();
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$oneGangId');
// Stream<DatabaseEvent> stream = ref.onValue;
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges(String id) {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$id');
Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = OneGangModel.fromJson(statusList);
// if (!isClosed) {
// add(OneGangUpdated());
// }
// });
// } catch (_) {}
// }
_streamSubscription = stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
deviceStatus = OneGangModel.fromJson(statusList);
add(OneGangUpdated());
});
} catch (_) {}
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
_oneGangUpdated(OneGangUpdated event, Emitter<OneGangState> emit) {
emit(LoadingInitialState());
emit(UpdateState(oneGangModel: deviceStatus));
}

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
@ -63,39 +64,54 @@ class OneTouchBloc extends Bloc<OneTouchEvent, OneTouchState> {
statusModelList.add(StatusModel.fromJson(status));
}
deviceStatus = OneTouchModel.fromJson(statusModelList);
_listenToChanges(oneTouchId);
emit(UpdateState(oneTouchModel: deviceStatus));
// _listenToChanges();
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
}
// Real-time db
// _listenToChanges() {
// try {
// DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$oneTouchId');
// Stream<DatabaseEvent> stream = ref.onValue;
// stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges(String id) {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$id');
Stream<DatabaseEvent> stream = ref.onValue;
// usersMap['status'].forEach((element) {
// statusList.add(StatusModel(code: element['code'], value: element['value']));
// });
_streamSubscription = stream.listen((DatabaseEvent event) {
if (event.snapshot.value != null) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
// deviceStatus = OneTouchModel.fromJson(statusList);
// if (!isClosed) {
// add(OneTouchUpdated());
// }
// });
// } catch (_) {}
// }
usersMap['status'].forEach((element) {
statusList.add(
StatusModel(code: element['code'], value: element['value']));
});
var switchStatus = statusList.firstWhere(
(status) => status.code == "switch_1",
orElse: () => StatusModel(code: "switch_1", value: false));
deviceStatus.firstSwitch = switchStatus.value as bool;
add(OneTouchUpdated());
}
});
} catch (_) {
}
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
_oneTouchUpdated(OneTouchUpdated event, Emitter<OneTouchState> emit) {
emit(LoadingNewSate(oneTouchModel: deviceStatus));
emit(UpdateState(oneTouchModel: deviceStatus));
}

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/three_touch_bloc/three_touch_event.dart';
@ -37,7 +38,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
List<GroupThreeTouchModel> groupThreeTouchList = [];
bool allSwitchesOn = true;
ThreeTouchBloc({required this.threeTouchId, required this.switchCode}) : super(InitialState()) {
ThreeTouchBloc({required this.threeTouchId, required this.switchCode})
: super(InitialState()) {
on<InitialEvent>(_fetchThreeTouchStatus);
on<ThreeTouchUpdated>(_threeTouchUpdated);
on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
@ -62,7 +64,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
on<ChangeStatusEvent>(_changeStatus);
}
void _fetchThreeTouchStatus(InitialEvent event, Emitter<ThreeTouchState> emit) async {
void _fetchThreeTouchStatus(
InitialEvent event, Emitter<ThreeTouchState> emit) async {
emit(LoadingInitialState());
try {
threeTouchGroup = event.groupScreen;
@ -74,7 +77,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', '3GT');
for (int i = 0; i < devicesList.length; i++) {
var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
var response =
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = [];
for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status));
@ -91,13 +95,16 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
if (groupThreeTouchList.isNotEmpty) {
groupThreeTouchList.firstWhere((element) {
if (!element.firstSwitch || !element.secondSwitch || !element.thirdSwitch) {
if (!element.firstSwitch ||
!element.secondSwitch ||
!element.thirdSwitch) {
allSwitchesOn = false;
}
return true;
});
}
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: allSwitchesOn));
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList, allSwitches: allSwitchesOn));
} else {
var response = await DevicesAPI.getDeviceStatus(threeTouchId);
List<StatusModel> statusModelList = [];
@ -106,7 +113,7 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
deviceStatus = ThreeTouchModel.fromJson(statusModelList);
emit(UpdateState(threeTouchModel: deviceStatus));
// _listenToChanges();
_listenToChanges();
}
} catch (e) {
emit(FailedState(error: e.toString()));
@ -114,35 +121,39 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
// _listenToChanges() {
// try {
// DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$threeTouchId');
// Stream<DatabaseEvent> stream = ref.onValue;
_listenToChanges() {
try {
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$threeTouchId');
Stream<DatabaseEvent> stream = ref.onValue;
// stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 2));
}
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList.add(StatusModel(code: element['code'], value: element['value']));
// });
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
// deviceStatus = ThreeTouchModel.fromJson(statusList);
// if (!isClosed) {
// add(ThreeTouchUpdated());
// }
// });
// } catch (_) {}
// }
deviceStatus = ThreeTouchModel.fromJson(statusList);
if (!isClosed) {
add(ThreeTouchUpdated());
}
});
} catch (_) {}
}
_threeTouchUpdated(ThreeTouchUpdated event, Emitter<ThreeTouchState> emit) {
emit(UpdateState(threeTouchModel: deviceStatus));
}
void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter<ThreeTouchState> emit) async {
void _changeFirstSwitch(
ChangeFirstSwitchStatusEvent event, Emitter<ThreeTouchState> emit) async {
emit(LoadingNewSate(threeTouchModel: deviceStatus));
try {
if (threeTouchGroup) {
@ -151,11 +162,15 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
if (element.deviceId == event.deviceId) {
element.firstSwitch = !event.value;
}
if (!element.firstSwitch || !element.secondSwitch || !element.thirdSwitch) {
if (!element.firstSwitch ||
!element.secondSwitch ||
!element.thirdSwitch) {
allSwitchesValue = false;
}
});
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: allSwitchesValue));
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList,
allSwitches: allSwitchesValue));
} else {
deviceStatus.firstSwitch = !event.value;
emit(UpdateState(threeTouchModel: deviceStatus));
@ -182,8 +197,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void _changeSecondSwitch(
ChangeSecondSwitchStatusEvent event, Emitter<ThreeTouchState> emit) async {
void _changeSecondSwitch(ChangeSecondSwitchStatusEvent event,
Emitter<ThreeTouchState> emit) async {
emit(LoadingNewSate(threeTouchModel: deviceStatus));
try {
if (threeTouchGroup) {
@ -192,11 +207,15 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
if (element.deviceId == event.deviceId) {
element.secondSwitch = !event.value;
}
if (!element.firstSwitch || !element.secondSwitch || !element.thirdSwitch) {
if (!element.firstSwitch ||
!element.secondSwitch ||
!element.thirdSwitch) {
allSwitchesValue = false;
}
});
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: allSwitchesValue));
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList,
allSwitches: allSwitchesValue));
} else {
deviceStatus.secondSwitch = !event.value;
emit(UpdateState(threeTouchModel: deviceStatus));
@ -222,7 +241,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void _changeThirdSwitch(ChangeThirdSwitchStatusEvent event, Emitter<ThreeTouchState> emit) async {
void _changeThirdSwitch(
ChangeThirdSwitchStatusEvent event, Emitter<ThreeTouchState> emit) async {
emit(LoadingNewSate(threeTouchModel: deviceStatus));
try {
if (threeTouchGroup) {
@ -231,11 +251,15 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
if (element.deviceId == event.deviceId) {
element.thirdSwitch = !event.value;
}
if (!element.firstSwitch || !element.secondSwitch || !element.thirdSwitch) {
if (!element.firstSwitch ||
!element.secondSwitch ||
!element.thirdSwitch) {
allSwitchesValue = false;
}
});
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: allSwitchesValue));
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList,
allSwitches: allSwitchesValue));
} else {
deviceStatus.thirdSwitch = !event.value;
emit(UpdateState(threeTouchModel: deviceStatus));
@ -274,15 +298,21 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
final response = await Future.wait([
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_1', value: deviceStatus.firstSwitch),
deviceId: threeTouchId,
code: 'switch_1',
value: deviceStatus.firstSwitch),
threeTouchId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_2', value: deviceStatus.secondSwitch),
deviceId: threeTouchId,
code: 'switch_2',
value: deviceStatus.secondSwitch),
threeTouchId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_3', value: deviceStatus.thirdSwitch),
deviceId: threeTouchId,
code: 'switch_3',
value: deviceStatus.thirdSwitch),
threeTouchId),
]);
@ -308,15 +338,21 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
final response = await Future.wait([
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_1', value: deviceStatus.firstSwitch),
deviceId: threeTouchId,
code: 'switch_1',
value: deviceStatus.firstSwitch),
threeTouchId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_2', value: deviceStatus.secondSwitch),
deviceId: threeTouchId,
code: 'switch_2',
value: deviceStatus.secondSwitch),
threeTouchId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: threeTouchId, code: 'switch_3', value: deviceStatus.thirdSwitch),
deviceId: threeTouchId,
code: 'switch_3',
value: deviceStatus.thirdSwitch),
threeTouchId),
]);
@ -338,8 +374,10 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
groupThreeTouchList[i].secondSwitch = true;
groupThreeTouchList[i].thirdSwitch = true;
}
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: true));
List<String> allDeviceIds = groupThreeTouchList.map((device) => device.deviceId).toList();
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList, allSwitches: true));
List<String> allDeviceIds =
groupThreeTouchList.map((device) => device.deviceId).toList();
final response1 = await DevicesAPI.deviceBatchController(
code: 'switch_1',
devicesUuid: allDeviceIds,
@ -368,7 +406,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void _groupAllOff(GroupAllOffEvent event, Emitter<ThreeTouchState> emit) async {
void _groupAllOff(
GroupAllOffEvent event, Emitter<ThreeTouchState> emit) async {
emit(LoadingNewSate(threeTouchModel: deviceStatus));
try {
for (int i = 0; i < groupThreeTouchList.length; i++) {
@ -376,8 +415,10 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
groupThreeTouchList[i].secondSwitch = false;
groupThreeTouchList[i].thirdSwitch = false;
}
List<String> allDeviceIds = groupThreeTouchList.map((device) => device.deviceId).toList();
emit(UpdateGroupState(threeTouchList: groupThreeTouchList, allSwitches: false));
List<String> allDeviceIds =
groupThreeTouchList.map((device) => device.deviceId).toList();
emit(UpdateGroupState(
threeTouchList: groupThreeTouchList, allSwitches: false));
final response1 = await DevicesAPI.deviceBatchController(
code: 'switch_1',
devicesUuid: allDeviceIds,
@ -406,17 +447,20 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void _changeSliding(ChangeSlidingSegment event, Emitter<ThreeTouchState> emit) async {
void _changeSliding(
ChangeSlidingSegment event, Emitter<ThreeTouchState> emit) async {
emit(ChangeSlidingSegmentState(value: event.value));
}
void _setCounterValue(SetCounterValue event, Emitter<ThreeTouchState> emit) async {
void _setCounterValue(
SetCounterValue event, Emitter<ThreeTouchState> emit) async {
emit(LoadingNewSate(threeTouchModel: deviceStatus));
int seconds = 0;
try {
seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: threeTouchId, code: event.deviceCode, value: seconds),
DeviceControlModel(
deviceId: threeTouchId, code: event.deviceCode, value: seconds),
threeTouchId);
if (response['success'] ?? false) {
@ -443,7 +487,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void _getCounterValue(GetCounterEvent event, Emitter<ThreeTouchState> emit) async {
void _getCounterValue(
GetCounterEvent event, Emitter<ThreeTouchState> emit) async {
emit(LoadingInitialState());
try {
var response = await DevicesAPI.getDeviceStatus(threeTouchId);
@ -553,7 +598,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
deviceId: threeTouchId,
);
List<dynamic> jsonData = response;
listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
listSchedule =
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(InitialState());
} on DioException catch (e) {
final errorData = e.response!.data;
@ -564,12 +610,13 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds =
DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month,
dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
}
Future toggleChange(ToggleScheduleEvent event, Emitter<ThreeTouchState> emit) async {
Future toggleChange(
ToggleScheduleEvent event, Emitter<ThreeTouchState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.changeSchedule(
@ -588,7 +635,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
Future deleteSchedule(DeleteScheduleEvent event, Emitter<ThreeTouchState> emit) async {
Future deleteSchedule(
DeleteScheduleEvent event, Emitter<ThreeTouchState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.deleteSchedule(
@ -608,13 +656,15 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
}
}
void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<ThreeTouchState> emit) {
void toggleSelectedIndex(
ToggleSelectedEvent event, Emitter<ThreeTouchState> emit) {
emit(LoadingInitialState());
selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex));
}
void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<ThreeTouchState> emit) {
void toggleCreateSchedule(
ToggleCreateScheduleEvent event, Emitter<ThreeTouchState> emit) {
emit(LoadingInitialState());
createSchedule = !createSchedule;
selectedDays.clear();
@ -632,7 +682,8 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
String statusSelected = '';
String optionSelected = '';
Future<void> _changeStatus(ChangeStatusEvent event, Emitter<ThreeTouchState> emit) async {
Future<void> _changeStatus(
ChangeStatusEvent event, Emitter<ThreeTouchState> emit) async {
try {
emit(LoadingInitialState());
final Map<String, Map<String, String>> controlMap = {
@ -666,11 +717,15 @@ class ThreeTouchBloc extends Bloc<ThreeTouchEvent, ThreeTouchState> {
final selectedControl = controlMap[optionSelected]?[statusSelected];
if (selectedControl != null) {
await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: threeTouchId, code: optionSelected, value: selectedControl),
DeviceControlModel(
deviceId: threeTouchId,
code: optionSelected,
value: selectedControl),
threeTouchId,
);
} else {
emit(const FailedState(error: 'Invalid statusSelected or optionSelected'));
emit(const FailedState(
error: 'Invalid statusSelected or optionSelected'));
}
} on DioException catch (e) {
final errorData = e.response!.data;

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/two_gang_bloc/two_gang_event.dart';
@ -34,7 +35,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
bool createSchedule = false;
List<ScheduleModel> listSchedule = [];
TwoGangBloc({required this.twoGangId, required this.switchCode}) : super(InitialState()) {
TwoGangBloc({required this.twoGangId, required this.switchCode})
: super(InitialState()) {
on<InitialEvent>(_fetchTwoGangStatus);
on<TwoGangUpdated>(_twoGangUpdated);
on<ChangeFirstSwitchStatusEvent>(_changeFirstSwitch);
@ -64,13 +66,15 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
int selectedTabIndex = 0;
void toggleSelectedIndex(ToggleSelectedEvent event, Emitter<TwoGangState> emit) {
void toggleSelectedIndex(
ToggleSelectedEvent event, Emitter<TwoGangState> emit) {
emit(LoadingInitialState());
selectedTabIndex = event.index;
emit(ChangeSlidingSegmentState(value: selectedTabIndex));
}
void toggleCreateSchedule(ToggleCreateScheduleEvent event, Emitter<TwoGangState> emit) {
void toggleCreateSchedule(
ToggleCreateScheduleEvent event, Emitter<TwoGangState> emit) {
emit(LoadingInitialState());
createSchedule = !createSchedule;
selectedDays.clear();
@ -78,7 +82,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
emit(UpdateCreateScheduleState(createSchedule));
}
void _fetchTwoGangStatus(InitialEvent event, Emitter<TwoGangState> emit) async {
void _fetchTwoGangStatus(
InitialEvent event, Emitter<TwoGangState> emit) async {
emit(LoadingInitialState());
try {
var response = await DevicesAPI.getDeviceStatus(twoGangId);
@ -88,42 +93,50 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
deviceStatus = TwoGangModel.fromJson(statusModelList);
emit(UpdateState(twoGangModel: deviceStatus));
// _listenToChanges();
_listenToChanges(twoGangId);
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
}
// _listenToChanges() {
// try {
// DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$twoGangId');
// Stream<DatabaseEvent> stream = ref.onValue;
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges(String id) {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$id');
Stream<DatabaseEvent> stream = ref.onValue;
_streamSubscription = stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
// stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
deviceStatus = TwoGangModel.fromJson(statusList);
add(TwoGangUpdated());
});
} catch (_) {}
}
// usersMap['status'].forEach((element) {
// statusList.add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = TwoGangModel.fromJson(statusList);
// if (!isClosed) {
// add(TwoGangUpdated());
// }
// });
// } catch (_) {}
// }
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
_twoGangUpdated(TwoGangUpdated event, Emitter<TwoGangState> emit) {
emit(LoadingNewSate(twoGangModel: deviceStatus));
emit(UpdateState(twoGangModel: deviceStatus));
}
void _changeFirstSwitch(ChangeFirstSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
void _changeFirstSwitch(
ChangeFirstSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
emit(LoadingNewSate(twoGangModel: deviceStatus));
try {
deviceStatus.firstSwitch = !event.value;
@ -134,7 +147,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
_timer = Timer(const Duration(milliseconds: 100), () async {
final response = await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: twoGangId, code: 'switch_1', value: !event.value),
DeviceControlModel(
deviceId: twoGangId, code: 'switch_1', value: !event.value),
twoGangId);
if (!response['success']) {
@ -146,7 +160,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
void _changeSecondSwitch(ChangeSecondSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
void _changeSecondSwitch(
ChangeSecondSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
emit(LoadingNewSate(twoGangModel: deviceStatus));
try {
deviceStatus.secondSwitch = !event.value;
@ -156,7 +171,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
_timer = Timer(const Duration(milliseconds: 100), () async {
final response = await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: twoGangId, code: 'switch_2', value: !event.value),
DeviceControlModel(
deviceId: twoGangId, code: 'switch_2', value: !event.value),
twoGangId);
if (!response['success']) {
@ -179,11 +195,15 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
final response = await Future.wait([
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch),
deviceId: twoGangId,
code: 'switch_1',
value: deviceStatus.firstSwitch),
twoGangId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch),
deviceId: twoGangId,
code: 'switch_2',
value: deviceStatus.secondSwitch),
twoGangId),
]);
@ -206,11 +226,15 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
final response = await Future.wait([
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: twoGangId, code: 'switch_1', value: deviceStatus.firstSwitch),
deviceId: twoGangId,
code: 'switch_1',
value: deviceStatus.firstSwitch),
twoGangId),
DevicesAPI.controlDevice(
DeviceControlModel(
deviceId: twoGangId, code: 'switch_2', value: deviceStatus.secondSwitch),
deviceId: twoGangId,
code: 'switch_2',
value: deviceStatus.secondSwitch),
twoGangId),
]);
if (response.every((element) => !element['success'])) {
@ -231,7 +255,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
groupTwoGangList[i].secondSwitch = true;
}
emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: true));
List<String> allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList();
List<String> allDeviceIds =
groupTwoGangList.map((device) => device.deviceId).toList();
final response1 = await DevicesAPI.deviceBatchController(
code: 'switch_1',
@ -266,7 +291,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: false));
List<String> allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList();
List<String> allDeviceIds =
groupTwoGangList.map((device) => device.deviceId).toList();
final response1 = await DevicesAPI.deviceBatchController(
code: 'switch_1',
@ -291,17 +317,20 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
void _changeSliding(ChangeSlidingSegment event, Emitter<TwoGangState> emit) async {
void _changeSliding(
ChangeSlidingSegment event, Emitter<TwoGangState> emit) async {
emit(ChangeSlidingSegmentState(value: event.value));
}
void _setCounterValue(SetCounterValue event, Emitter<TwoGangState> emit) async {
void _setCounterValue(
SetCounterValue event, Emitter<TwoGangState> emit) async {
emit(LoadingNewSate(twoGangModel: deviceStatus));
int seconds = 0;
try {
seconds = event.duration.inSeconds;
final response = await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: twoGangId, code: event.deviceCode, value: seconds),
DeviceControlModel(
deviceId: twoGangId, code: event.deviceCode, value: seconds),
twoGangId);
if (response['success'] ?? false) {
@ -326,7 +355,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
void _getCounterValue(GetCounterEvent event, Emitter<TwoGangState> emit) async {
void _getCounterValue(
GetCounterEvent event, Emitter<TwoGangState> emit) async {
emit(LoadingInitialState());
try {
add(GetScheduleEvent());
@ -434,7 +464,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
deviceId: twoGangId,
);
List<dynamic> jsonData = response;
listSchedule = jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
listSchedule =
jsonData.map((item) => ScheduleModel.fromJson(item)).toList();
emit(InitialState());
} on DioException catch (e) {
final errorData = e.response!.data;
@ -445,12 +476,13 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
int? getTimeStampWithoutSeconds(DateTime? dateTime) {
if (dateTime == null) return null;
DateTime dateTimeWithoutSeconds =
DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute);
DateTime dateTimeWithoutSeconds = DateTime(dateTime.year, dateTime.month,
dateTime.day, dateTime.hour, dateTime.minute);
return dateTimeWithoutSeconds.millisecondsSinceEpoch ~/ 1000;
}
Future toggleRepeat(ToggleScheduleEvent event, Emitter<TwoGangState> emit) async {
Future toggleRepeat(
ToggleScheduleEvent event, Emitter<TwoGangState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.changeSchedule(
@ -469,7 +501,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
Future deleteSchedule(DeleteScheduleEvent event, Emitter<TwoGangState> emit) async {
Future deleteSchedule(
DeleteScheduleEvent event, Emitter<TwoGangState> emit) async {
try {
emit(LoadingInitialState());
final response = await DevicesAPI.deleteSchedule(
@ -489,7 +522,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
void _fetchTwoGangWizardStatus(InitialWizardEvent event, Emitter<TwoGangState> emit) async {
void _fetchTwoGangWizardStatus(
InitialWizardEvent event, Emitter<TwoGangState> emit) async {
emit(LoadingInitialState());
try {
devicesList = [];
@ -499,7 +533,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
HomeCubit.getInstance().selectedSpace?.id ?? '', '2G');
for (int i = 0; i < devicesList.length; i++) {
var response = await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
var response =
await DevicesAPI.getDeviceStatus(devicesList[i].uuid ?? '');
List<StatusModel> statusModelList = [];
for (var status in response['status']) {
statusModelList.add(StatusModel.fromJson(status));
@ -522,15 +557,16 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
return true;
});
}
emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesOn));
emit(UpdateGroupState(
twoGangList: groupTwoGangList, allSwitches: allSwitchesOn));
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
}
void _changeFirstWizardSwitch(
ChangeFirstWizardSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
void _changeFirstWizardSwitch(ChangeFirstWizardSwitchStatusEvent event,
Emitter<TwoGangState> emit) async {
emit(LoadingNewSate(twoGangModel: deviceStatus));
try {
bool allSwitchesValue = true;
@ -543,9 +579,11 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
});
emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));
emit(UpdateGroupState(
twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));
List<String> allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList();
List<String> allDeviceIds =
groupTwoGangList.map((device) => device.deviceId).toList();
final response = await DevicesAPI.deviceBatchController(
code: 'switch_1',
devicesUuid: allDeviceIds,
@ -560,8 +598,8 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
}
}
void _changeSecondWizardSwitch(
ChangeSecondWizardSwitchStatusEvent event, Emitter<TwoGangState> emit) async {
void _changeSecondWizardSwitch(ChangeSecondWizardSwitchStatusEvent event,
Emitter<TwoGangState> emit) async {
emit(LoadingNewSate(twoGangModel: deviceStatus));
try {
bool allSwitchesValue = true;
@ -573,9 +611,11 @@ class TwoGangBloc extends Bloc<TwoGangEvent, TwoGangState> {
allSwitchesValue = false;
}
});
List<String> allDeviceIds = groupTwoGangList.map((device) => device.deviceId).toList();
List<String> allDeviceIds =
groupTwoGangList.map((device) => device.deviceId).toList();
emit(UpdateGroupState(twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));
emit(UpdateGroupState(
twoGangList: groupTwoGangList, allSwitches: allSwitchesValue));
final response = await DevicesAPI.deviceBatchController(
code: 'switch_2',

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/two_touch_bloc/two_touch_event.dart';
@ -98,52 +99,61 @@ class TwoTouchBloc extends Bloc<TwoTouchEvent, TwoTouchState> {
}
deviceStatus = TwoTouchModel.fromJson(statusModelList);
emit(UpdateState(twoTouchModel: deviceStatus));
// _listenToChanges();
_listenToChanges();
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
}
// StreamSubscription<DatabaseEvent>? _streamSubscription;
StreamSubscription<DatabaseEvent>? _streamSubscription;
// void _listenToChanges() {
// try {
// _streamSubscription?.cancel();
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$twoTouchId');
// Stream<DatabaseEvent> stream = ref.onValue;
void _listenToChanges() {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$twoTouchId');
Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// print('=========${usersMap['status']}');
// deviceStatus = TwoTouchModel.fromJson(statusList);
// if (!isClosed) {
// add(TwoTouchUpdated());
// }
// });
// } catch (_) {}
// }
_streamSubscription = stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 1));
}
if (event.snapshot.value != null) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
usersMap['status'].forEach((element) {
statusList.add(
StatusModel(code: element['code'], value: element['value']));
});
var switch1Status = statusList.firstWhere(
(status) => status.code == "switch_1",
orElse: () => StatusModel(code: "switch_1", value: false));
var switch2Status = statusList.firstWhere(
(status) => status.code == "switch_2",
orElse: () => StatusModel(code: "switch_2", value: false));
deviceStatus.firstSwitch = switch1Status.value as bool;
deviceStatus.secondSwitch = switch2Status.value as bool;
add(TwoTouchUpdated());
}
});
} catch (_) {
}
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
_twoTouchUpdated(TwoTouchUpdated event, Emitter<TwoTouchState> emit) {
emit(LoadingInitialState());
emit(UpdateState(twoTouchModel: deviceStatus));
}

View File

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
@ -73,7 +74,7 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
statusModelList,
);
emit(UpdateState(whModel: deviceStatus));
// _listenToChanges();
_listenToChanges();
} catch (e) {
emit(WHFailedState(errorMessage: e.toString()));
return;
@ -81,41 +82,39 @@ class WaterHeaterBloc extends Bloc<WaterHeaterEvent, WaterHeaterState> {
}
//real-time db
// StreamSubscription<DatabaseEvent>? _streamSubscription;
// void _listenToChanges() {
// try {
// _streamSubscription?.cancel();
// DatabaseReference ref =
// FirebaseDatabase.instance.ref('device-status/$whId');
// Stream<DatabaseEvent> stream = ref.onValue;
// _streamSubscription = stream.listen((DatabaseEvent event) async {
// if (_timer != null) {
// await Future.delayed(const Duration(seconds: 2));
// }
// Map<dynamic, dynamic> usersMap =
// event.snapshot.value as Map<dynamic, dynamic>;
// List<StatusModel> statusList = [];
// usersMap['status'].forEach((element) {
// statusList
// .add(StatusModel(code: element['code'], value: element['value']));
// });
// deviceStatus = WHModel.fromJson(statusList);
// if (!isClosed) {
// add(WaterHeaterUpdated());
// }
// });
// } catch (_) {}
// }
// @override
// Future<void> close() async {
// _streamSubscription?.cancel();
// _streamSubscription = null;
// return super.close();
// }
StreamSubscription<DatabaseEvent>? _streamSubscription;
void _listenToChanges() {
try {
_streamSubscription?.cancel();
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$whId');
Stream<DatabaseEvent> stream = ref.onValue;
_streamSubscription = stream.listen((DatabaseEvent event) async {
if (_timer != null) {
await Future.delayed(const Duration(seconds: 2));
}
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<StatusModel> statusList = [];
usersMap['status'].forEach((element) {
statusList
.add(StatusModel(code: element['code'], value: element['value']));
});
deviceStatus = WHModel.fromJson(statusList);
if (!isClosed) {
add(WaterHeaterUpdated());
}
});
} catch (_) {}
}
@override
Future<void> close() async {
_streamSubscription?.cancel();
_streamSubscription = null;
return super.close();
}
_waterHeaterUpdated(
WaterHeaterUpdated event, Emitter<WaterHeaterState> emit) async {

View File

@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:syncrow_app/features/devices/bloc/devices_cubit.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/devices_cubit.dart';
import 'package:syncrow_app/features/devices/view/widgets/all_devices.dart';
import 'package:syncrow_app/features/devices/view/widgets/room_page.dart';
import 'package:syncrow_app/features/devices/view/widgets/rooms_slider.dart';
@ -15,7 +15,7 @@ import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/strings_manager.dart';
class DevicesViewBody extends StatelessWidget {
const DevicesViewBody({Key? key}) : super(key: key);
const DevicesViewBody({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<HomeCubit, HomeState>(
@ -80,10 +80,7 @@ class DevicesViewBody extends StatelessWidget {
),
],
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.1,
child: const SceneView(pageType: true),
),
const SceneView(pageType: true),
const SizedBox(height: 20),
const RoomsSlider(),
const SizedBox(height: 10),

View File

@ -8,8 +8,7 @@ import 'package:syncrow_app/features/shared_widgets/devices_default_switch.dart'
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart';
class GarageList extends StatelessWidget {
const GarageList(
{super.key, required this.garageList, required this.allSwitches});
const GarageList({super.key, required this.garageList, required this.allSwitches});
final List<GroupGarageModel> garageList;
final bool allSwitches;
@ -23,43 +22,42 @@ class GarageList extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 10),
const BodySmall(text: 'All Lights'),
const BodySmall(text: 'All Garages'),
const SizedBox(height: 5),
DevicesDefaultSwitch(
off: 'OFF',
on: 'ON',
off: 'Close',
on: 'Open',
switchValue: allSwitches,
action: () {
BlocProvider.of<GarageDoorBloc>(context)
.add(GroupAllOnEvent());
},
secondAction: () {
BlocProvider.of<GarageDoorBloc>(context)
.add(GroupAllOffEvent());
},
action: () => BlocProvider.of<GarageDoorBloc>(context).add(
GroupAllOnEvent(),
),
secondAction: () => BlocProvider.of<GarageDoorBloc>(context).add(
GroupAllOffEvent(),
),
),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.all(0),
padding: EdgeInsetsDirectional.zero,
itemCount: garageList.length,
itemBuilder: (context, index) {
final garageDoor = garageList[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 10),
BodySmall(text: garageList[index].deviceName),
BodySmall(text: garageDoor.deviceName),
const SizedBox(height: 5),
DevicesDefaultSwitch(
off: 'OFF',
on: 'ON',
switchValue: garageList[index].firstSwitch,
action: () {
BlocProvider.of<GarageDoorBloc>(context).add(
ChangeFirstWizardSwitchStatusEvent(
value: garageList[index].firstSwitch,
deviceId: garageList[index].deviceId));
},
off: 'Close',
on: 'Open',
switchValue: garageDoor.firstSwitch,
action: () => BlocProvider.of<GarageDoorBloc>(context).add(
ChangeFirstWizardSwitchStatusEvent(
value: garageDoor.firstSwitch,
deviceId: garageDoor.deviceId,
),
),
),
],
);

View File

@ -20,8 +20,9 @@ class OneGangScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => OneGangBloc(switchCode: 'switch_1', oneGangId: device?.uuid ?? '')
..add(const InitialEvent(groupScreen: false)),
create: (context) =>
OneGangBloc(switchCode: 'switch_1', oneGangId: device?.uuid ?? '')
..add(const InitialEvent(groupScreen: false)),
child: BlocBuilder<OneGangBloc, OneGangState>(
builder: (context, state) {
OneGangModel oneGangModel = OneGangModel(
@ -36,13 +37,15 @@ class OneGangScreen extends StatelessWidget {
}
return state is LoadingInitialState
? const Center(
child:
DefaultContainer(width: 50, height: 50, child: CircularProgressIndicator()),
child: DefaultContainer(
width: 50,
height: 50,
child: CircularProgressIndicator()),
)
: RefreshIndicator(
onRefresh: () async {
BlocProvider.of<OneGangBloc>(context)
.add(InitialEvent(groupScreen: device != null ? false : true));
BlocProvider.of<OneGangBloc>(context).add(InitialEvent(
groupScreen: device != null ? false : true));
},
child: ListView(
children: [
@ -55,7 +58,8 @@ class OneGangScreen extends StatelessWidget {
const Expanded(child: SizedBox.shrink()),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisAlignment:
MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
@ -64,9 +68,10 @@ class OneGangScreen extends StatelessWidget {
threeGangSwitch: device!,
value: oneGangModel.firstSwitch,
action: () {
BlocProvider.of<OneGangBloc>(context).add(
ChangeFirstSwitchStatusEvent(
value: oneGangModel.firstSwitch));
BlocProvider.of<OneGangBloc>(context)
.add(ChangeFirstSwitchStatusEvent(
value: oneGangModel
.firstSwitch));
},
),
const SizedBox(height: 20),
@ -74,7 +79,8 @@ class OneGangScreen extends StatelessWidget {
width: 70,
child: BodySmall(
text: " Entrance Light",
fontColor: ColorsManager.textPrimaryColor,
fontColor:
ColorsManager.textPrimaryColor,
textAlign: TextAlign.center,
),
),
@ -94,20 +100,24 @@ class OneGangScreen extends StatelessWidget {
Card(
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
borderRadius:
BorderRadius.circular(100),
),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
pageBuilder:
(context, animation1, animation2) =>
TimerScheduleScreen(
switchCode: 'switch_1',
device: device!,
deviceCode: 'countdown_1',
)));
pageBuilder: (context,
animation1,
animation2) =>
TimerScheduleScreen(
switchCode:
'switch_1',
device: device!,
deviceCode:
'countdown_1',
)));
},
child: Stack(
alignment: Alignment.center,
@ -117,7 +127,9 @@ class OneGangScreen extends StatelessWidget {
height: 60,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(100),
borderRadius:
BorderRadius.circular(
100),
),
),
Container(
@ -125,12 +137,15 @@ class OneGangScreen extends StatelessWidget {
height: 40,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(100),
borderRadius:
BorderRadius.circular(
100),
),
child: Center(
child: Icon(
Icons.access_time,
color: ColorsManager.primaryColorWithOpacity,
color: ColorsManager
.primaryColorWithOpacity,
size: 25,
),
),

View File

@ -8,7 +8,11 @@ import 'package:syncrow_app/features/shared_widgets/devices_default_switch.dart'
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart';
class WHList extends StatelessWidget {
const WHList({super.key, required this.whList, required this.allSwitches});
const WHList({
required this.whList,
required this.allSwitches,
super.key,
});
final List<GroupWHModel> whList;
final bool allSwitches;
@ -22,43 +26,42 @@ class WHList extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 10),
const BodySmall(text: 'All Lights'),
const BodySmall(text: 'All Water Heaters'),
const SizedBox(height: 5),
DevicesDefaultSwitch(
off: 'OFF',
on: 'ON',
switchValue: allSwitches,
action: () {
BlocProvider.of<WaterHeaterBloc>(context)
.add(GroupAllOnEvent());
},
secondAction: () {
BlocProvider.of<WaterHeaterBloc>(context)
.add(GroupAllOffEvent());
},
action: () => context.read<WaterHeaterBloc>().add(
GroupAllOnEvent(),
),
secondAction: () => context.read<WaterHeaterBloc>().add(
GroupAllOffEvent(),
),
),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.all(0),
padding: EdgeInsetsDirectional.zero,
itemCount: whList.length,
itemBuilder: (context, index) {
final waterHeater = whList[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 10),
BodySmall(text: whList[index].deviceName),
BodySmall(text: waterHeater.deviceName),
const SizedBox(height: 5),
DevicesDefaultSwitch(
off: 'OFF',
on: 'ON',
switchValue: whList[index].firstSwitch,
action: () {
BlocProvider.of<WaterHeaterBloc>(context).add(
switchValue: waterHeater.firstSwitch,
action: () => context.read<WaterHeaterBloc>().add(
ChangeFirstWizardSwitchStatusEvent(
value: whList[index].firstSwitch,
deviceId: whList[index].deviceId));
},
value: waterHeater.firstSwitch,
deviceId: waterHeater.deviceId,
),
),
),
],
);

View File

@ -1,6 +1,8 @@
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/auth/model/project_model.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/scene/bloc/effective_period/effect_period_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/effective_period/effect_period_event.dart';
@ -348,15 +350,18 @@ class CreateSceneBloc extends Bloc<CreateSceneEvent, CreateSceneState>
emit(CreateSceneLoading());
try {
dynamic response;
Project? project = HomeCubit.getInstance().project;
if (event.createSceneModel != null) {
response = event.updateScene
? await SceneApi.updateScene(event.createSceneModel!, event.sceneId)
: await SceneApi.createScene(event.createSceneModel!);
} else if (event.createAutomationModel != null) {
response = event.updateScene
? await SceneApi.updateAutomation(
event.createAutomationModel!, event.sceneId)
: await SceneApi.createAutomation(event.createAutomationModel!);
? await SceneApi.updateAutomation(event.createAutomationModel!,
event.sceneId, project?.uuid ?? '')
: await SceneApi.createAutomation(
event.createAutomationModel!, project?.uuid ?? '');
}
if (response['success'] == true) {
@ -421,6 +426,8 @@ class CreateSceneBloc extends Bloc<CreateSceneEvent, CreateSceneState>
emit(CreateSceneLoading());
try {
Project? project = HomeCubit.getInstance().project;
tasksList.clear();
tempTasksList.clear();
selectedValues.clear();
@ -436,7 +443,8 @@ class CreateSceneBloc extends Bloc<CreateSceneEvent, CreateSceneState>
conditionRule = 'or';
final response = event.isAutomation
? await SceneApi.getAutomationDetails(event.sceneId)
? await SceneApi.getAutomationDetails(
event.sceneId, project?.uuid ?? '')
: await SceneApi.getSceneDetails(event.sceneId);
if (response.id.isNotEmpty) {
if (event.isAutomation) {
@ -605,10 +613,14 @@ class CreateSceneBloc extends Bloc<CreateSceneEvent, CreateSceneState>
emit(DeleteSceneLoading());
try {
Project? project = HomeCubit.getInstance().project;
final response =
sceneType.name == CreateSceneEnum.deviceStatusChanges.name
? await SceneApi.deleteAutomation(
automationId: event.sceneId, unitUuid: event.unitUuid)
automationId: event.sceneId,
unitUuid: event.unitUuid,
projectId: project?.uuid ?? '')
: await SceneApi.deleteScene(
sceneId: event.sceneId,
);

View File

@ -46,8 +46,11 @@ class SceneBloc extends Bloc<SceneEvent, SceneState> {
emit(SceneLoading());
try {
Project? project = HomeCubit.getInstance().project;
if (event.unitId.isNotEmpty) {
automationList = await SceneApi.getAutomationByUnitId(event.unitId);
automationList = await SceneApi.getAutomationByUnitId(
event.unitId, event.communityId, project?.uuid ?? '');
emit(SceneLoaded(scenes, automationList));
} else {
emit(const SceneError(message: 'Unit ID is empty'));
@ -96,11 +99,17 @@ class SceneBloc extends Bloc<SceneEvent, SceneState> {
));
try {
Project? project = HomeCubit.getInstance().project;
final success = await SceneApi.updateAutomationStatus(
event.automationId, event.automationStatusUpdate);
event.automationId,
event.automationStatusUpdate,
project?.uuid ?? '');
if (success) {
automationList = await SceneApi.getAutomationByUnitId(
event.automationStatusUpdate.spaceUuid);
event.automationStatusUpdate.spaceUuid,
event.communityId,
project?.uuid ?? '');
newLoadingStates[event.automationId] = false;
emit(SceneLoaded(
currentState.scenes,

View File

@ -22,11 +22,13 @@ class LoadScenes extends SceneEvent {
class LoadAutomation extends SceneEvent {
final String unitId;
final String communityId;
const LoadAutomation(this.unitId);
const LoadAutomation(this.unitId, this.communityId);
@override
List<Object> get props => [unitId];
List<Object> get props => [unitId, communityId];
}
class SceneTrigger extends SceneEvent {
@ -43,8 +45,9 @@ class SceneTrigger extends SceneEvent {
class UpdateAutomationStatus extends SceneEvent {
final String automationId;
final AutomationStatusUpdate automationStatusUpdate;
final String communityId;
const UpdateAutomationStatus({required this.automationStatusUpdate, required this.automationId});
const UpdateAutomationStatus({required this.automationStatusUpdate, required this.automationId, required this.communityId});
@override
List<Object> get props => [automationStatusUpdate];

View File

@ -0,0 +1,78 @@
import 'package:syncrow_app/features/scene/enum/operation_dialog_type.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';
import 'package:syncrow_app/generated/assets.dart';
class OneGangHelperFunctions {
static List<SceneStaticFunction> oneGangHelperFunctions(
String deviceId, String deviceName, functionValue) {
return [
SceneStaticFunction(
deviceId: deviceId,
deviceName: deviceName,
icon: Assets.assetsAcPower,
operationName: 'Light Switch',
code: 'switch_1',
functionValue: functionValue,
operationDialogType: OperationDialogType.onOff,
operationalValues: [
SceneOperationalValue(
icon: Assets.assetsAcPower, description: "ON", value: true),
SceneOperationalValue(
icon: Assets.assetsAcPowerOFF, description: "OFF", value: false),
],
),
SceneStaticFunction(
deviceId: deviceId,
deviceName: deviceName,
icon: Assets.assetsLightCountdown,
operationName: 'Light CountDown',
code: 'countdown_1',
functionValue: functionValue,
operationDialogType: OperationDialogType.countdown,
operationalValues: [
SceneOperationalValue(icon: '', value: 0),
],
),
];
}
static List<SceneStaticFunction> oneGangAutomationFunctions(
String deviceId, String deviceName, functionValue) {
return [
SceneStaticFunction(
deviceId: deviceId,
deviceName: deviceName,
icon: Assets.assetsAcPower,
operationName: 'Light Switch',
code: 'switch_1',
functionValue: functionValue,
operationDialogType: OperationDialogType.onOff,
operationalValues: [
SceneOperationalValue(
icon: Assets.assetsAcPower, description: "ON", value: true),
SceneOperationalValue(
icon: Assets.assetsAcPowerOFF, description: "OFF", value: false),
],
),
SceneStaticFunction(
deviceId: deviceId,
deviceName: deviceName,
icon: Assets.assetsLightCountdown,
operationName: 'Light CountDown',
code: 'countdown_1',
functionValue: functionValue,
operationDialogType: OperationDialogType.integerSteps,
operationalValues: [
SceneOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: 43200,
stepValue: 1,
),
],
),
];
}
}

View File

@ -0,0 +1,48 @@
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/app_layout/model/community_model.dart';
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/scene/bloc/scene_bloc/scene_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/scene_bloc/scene_event.dart';
abstract final class SceneBlocFactory {
static SceneBloc create({
required bool pageType,
required HomeCubit homeCubit,
}) {
final selectedSpace = homeCubit.selectedSpace;
final defaultSpace = SpaceModel(
id: '-1',
name: '',
community: Community(
uuid: '-1',
name: '',
),
);
final spaceId = selectedSpace?.id ?? defaultSpace.id;
final space = selectedSpace ?? defaultSpace;
final communityUuid =
selectedSpace?.community.uuid ?? defaultSpace.community.uuid;
final sceneBloc = SceneBloc();
sceneBloc.add(
LoadScenes(
spaceId,
space,
showInDevice: pageType,
),
);
if (!pageType) {
sceneBloc.add(
LoadAutomation(
spaceId,
communityUuid,
),
);
}
return sceneBloc;
}
}

View File

@ -6,6 +6,7 @@ import 'package:syncrow_app/features/scene/helper/functions_per_device/ac_functi
import 'package:syncrow_app/features/scene/helper/functions_per_device/door_lock_functions.dart';
import 'package:syncrow_app/features/scene/helper/functions_per_device/gateway_functions.dart';
import 'package:syncrow_app/features/scene/helper/functions_per_device/human_presence_functions.dart';
import 'package:syncrow_app/features/scene/helper/functions_per_device/one_gang_functions.dart';
import 'package:syncrow_app/features/scene/helper/functions_per_device/presence_sensor.dart';
import 'package:syncrow_app/features/scene/helper/functions_per_device/three_gang_functions.dart';
import 'package:syncrow_app/features/scene/model/scene_details_model.dart';
@ -14,8 +15,9 @@ import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
mixin SceneOperationsDataHelper {
final Map<DeviceType, Function(List<FunctionModel>, String, String, dynamic, bool)> _functionMap =
{
final Map<DeviceType,
Function(List<FunctionModel>, String, String, dynamic, bool)>
_functionMap = {
DeviceType.LightBulb: lightBulbFunctions,
DeviceType.CeilingSensor: ceilingSensorFunctions,
DeviceType.WallSensor: wallSensorFunctions,
@ -24,6 +26,7 @@ mixin SceneOperationsDataHelper {
DeviceType.Curtain: curtainFunctions,
DeviceType.ThreeGang: threeGangFunctions,
DeviceType.Gateway: gatewayFunctions,
DeviceType.OneGang: oneGangFunctions,
};
final Map<DeviceType, String> _titleMap = {
@ -35,7 +38,24 @@ mixin SceneOperationsDataHelper {
DeviceType.Curtain: 'Curtain Functions',
DeviceType.ThreeGang: '3G Light Switch Functions',
DeviceType.Gateway: 'Gateway Functions',
DeviceType.OneGang: '1G Light Switch Conditions',
};
static String _productTypeCache = '';
//one gang functions
static List<SceneStaticFunction> oneGangFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return OneGangHelperFunctions.oneGangAutomationFunctions(
deviceId, deviceName, functionValue);
}
return OneGangHelperFunctions.oneGangHelperFunctions(
deviceId, deviceName, functionValue);
}
List<SceneStaticFunction> getFunctionsWithIcons({
DeviceType? type,
@ -45,16 +65,22 @@ mixin SceneOperationsDataHelper {
required bool isAutomation,
}) {
final functionValue = null;
return _functionMap[type]?.call(functions, deviceId, deviceName, functionValue, isAutomation) ??
lightBulbFunctions(functions, deviceId, deviceName, functionValue, isAutomation);
return _functionMap[type]?.call(
functions, deviceId, deviceName, functionValue, isAutomation) ??
lightBulbFunctions(
functions, deviceId, deviceName, functionValue, isAutomation);
}
String getTitle({DeviceType? type}) {
return _titleMap[type] ?? '';
}
static List<SceneStaticFunction> ceilingSensorFunctions(List<FunctionModel> functions,
String deviceId, String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> ceilingSensorFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return PresenceSensorHelperFunctions.automationPresenceSensorFunctions(
deviceId, deviceName, functionValue);
@ -63,22 +89,35 @@ mixin SceneOperationsDataHelper {
deviceId, deviceName, functionValue);
}
static List<SceneStaticFunction> curtainFunctions(List<FunctionModel> functions, String deviceId,
String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> curtainFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
return [];
}
static List<SceneStaticFunction> doorLockFunctions(List<FunctionModel> functions, String deviceId,
String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> doorLockFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return DoorLockHelperFunctions.doorLockAutomationFunctions(
deviceId, deviceName, functionValue);
}
return DoorLockHelperFunctions.doorLockTapToRunFunctions(deviceId, deviceName, functionValue);
return DoorLockHelperFunctions.doorLockTapToRunFunctions(
deviceId, deviceName, functionValue);
}
static List<SceneStaticFunction> wallSensorFunctions(List<FunctionModel> functions,
String deviceId, String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> wallSensorFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return HumanPresenceHelperFunctions.automationHumanPresenceFunctions(
deviceId, deviceName, functionValue);
@ -87,31 +126,51 @@ mixin SceneOperationsDataHelper {
deviceId, deviceName, functionValue);
}
static List<SceneStaticFunction> lightBulbFunctions(List<FunctionModel> functions,
String deviceId, String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> lightBulbFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
return [];
}
static List<SceneStaticFunction> gatewayFunctions(List<FunctionModel> functions, String deviceId,
String deviceName, dynamic functionValue, bool isAutomation) {
return GatewayHelperFunctions.tabToRunGatewayFunctions(deviceId, deviceName, functionValue);
static List<SceneStaticFunction> gatewayFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
return GatewayHelperFunctions.tabToRunGatewayFunctions(
deviceId, deviceName, functionValue);
}
static List<SceneStaticFunction> threeGangFunctions(List<FunctionModel> functions,
String deviceId, String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> threeGangFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return ThreeGangHelperFunctions.threeGangAutomationFunctions(
deviceId, deviceName, functionValue);
}
return ThreeGangHelperFunctions.threeGangHelperFunctions(deviceId, deviceName, functionValue);
return ThreeGangHelperFunctions.threeGangHelperFunctions(
deviceId, deviceName, functionValue);
}
static List<SceneStaticFunction> acFunctions(List<FunctionModel> functions, String deviceId,
String deviceName, dynamic functionValue, bool isAutomation) {
static List<SceneStaticFunction> acFunctions(
List<FunctionModel> functions,
String deviceId,
String deviceName,
dynamic functionValue,
bool isAutomation) {
if (isAutomation) {
return ACFunctionsHelper.automationAcFunctions(deviceId, deviceName, functionValue);
return ACFunctionsHelper.automationAcFunctions(
deviceId, deviceName, functionValue);
}
return ACFunctionsHelper.tabToRunAcFunctions(deviceId, deviceName, functionValue);
return ACFunctionsHelper.tabToRunAcFunctions(
deviceId, deviceName, functionValue);
}
List<SceneStaticFunction> getTaskListFunctionsFromApi({
@ -149,8 +208,12 @@ mixin SceneOperationsDataHelper {
SceneStaticFunction(
deviceId: action.entityId,
deviceName: action.name.toString(),
deviceIcon: action.type == 'automation' ? Assets.player : Assets.handClickIcon,
icon: action.type == 'automation' ? Assets.player : Assets.handClickIcon,
deviceIcon: action.type == 'automation'
? Assets.player
: Assets.handClickIcon,
icon: action.type == 'automation'
? Assets.player
: Assets.handClickIcon,
operationName: action.type.toString(),
operationDialogType: OperationDialogType.onOff,
functionValue: action.actionExecutor,
@ -170,7 +233,8 @@ mixin SceneOperationsDataHelper {
),
);
} else {
functions.add(_mapExecutorPropertyToSceneFunction(action, isAutomation));
functions
.add(_mapExecutorPropertyToSceneFunction(action, isAutomation));
}
}
@ -206,7 +270,9 @@ mixin SceneOperationsDataHelper {
}) {
final executorProperty = action.executorProperty;
final Map<String, SceneStaticFunction Function(Action, bool, String?, String?)> functionMap = {
final Map<String,
SceneStaticFunction Function(Action, bool, String?, String?)>
functionMap = {
'sensitivity': _createSensitivityFunction,
'normal_open_switch': _createNormalOpenSwitchFunction,
'unlock_fingerprint': _createUnlockFingerprintFunction,
@ -282,14 +348,16 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createSensitivityFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createSensitivityFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Presence Sensor',
Assets.assetsIconsSensors,
'Sensitivity',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.listOfOptions,
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.listOfOptions,
isAutomation ? _createIntegerStepsOptions() : _createSensitivityOptions(),
isAutomation,
comparator,
@ -297,8 +365,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createNormalOpenSwitchFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createNormalOpenSwitchFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -351,8 +419,8 @@ mixin SceneOperationsDataHelper {
];
}
SceneStaticFunction _createUnlockFingerprintFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockFingerprintFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -366,8 +434,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createUnlockPasswordFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockPasswordFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -381,8 +449,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createUnlockCardFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockCardFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -396,8 +464,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createAlarmLockFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createAlarmLockFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -411,8 +479,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createUnlockRequestFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockRequestFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -426,8 +494,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createResidualElectricityFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createResidualElectricityFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -441,8 +509,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createReverseLockFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createReverseLockFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -456,8 +524,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createUnlockAppFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockAppFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -471,8 +539,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createHijackFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createHijackFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -486,8 +554,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createDoorbellFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createDoorbellFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -501,8 +569,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createUnlockTemporaryFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createUnlockTemporaryFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'WIFI LOCK PRO',
@ -516,8 +584,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createFarDetectionFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createFarDetectionFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -531,8 +599,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createMotionSensitivityFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createMotionSensitivityFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -546,8 +614,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createMotionlessSensitivityFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createMotionlessSensitivityFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -561,8 +629,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createIndicatorFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createIndicatorFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -576,8 +644,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createPresenceTimeFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createPresenceTimeFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -591,8 +659,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createPresenceStateFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createPresenceStateFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -606,14 +674,16 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createDisCurrentFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createDisCurrentFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
Assets.assetsIconsSensors,
'Current Distance',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.countdown,
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.countdown,
_createCurrentDistanceOptions(),
isAutomation,
comparator,
@ -621,8 +691,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createIlluminanceValueFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createIlluminanceValueFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -636,8 +706,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createCheckingResultFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createCheckingResultFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Human Presence Sensor',
@ -651,8 +721,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createSwitchFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createSwitchFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
@ -666,23 +736,27 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createTempSetFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createTempSetFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
Assets.assetsIconsAC,
'Set Temperature',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.temperature,
isAutomation ? _createAutomationTemperatureOptions() : _createTemperatureOptions(),
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.temperature,
isAutomation
? _createAutomationTemperatureOptions()
: _createTemperatureOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
}
SceneStaticFunction _createTempCurrentFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createTempCurrentFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
@ -696,8 +770,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createModeFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createModeFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
@ -711,8 +785,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createLevelFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createLevelFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
@ -726,8 +800,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createChildLockFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createChildLockFunction(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Smart AC Thermostat - Grey - Model A',
@ -741,23 +815,38 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createSwitch1Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 1 Switch',
OperationDialogType.onOff,
_createOnOffOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
SceneStaticFunction _createSwitch1Function(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
switch (action.productType) {
case "3G":
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 1 Switch',
OperationDialogType.onOff,
_createOnOffOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
default:
return _createSceneFunction(
action,
'1 Gang Button Switch L-L',
Assets.oneGang,
'Light Switch',
OperationDialogType.onOff,
_createOnOffOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
}
}
SceneStaticFunction _createSwitch2Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createSwitch2Function(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
@ -771,8 +860,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createSwitch3Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createSwitch3Function(Action action, bool isAutomation,
String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
@ -786,53 +875,84 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createCountdown1Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 1 CountDown',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.countdown,
isAutomation ? _createAutomationCountDownOptions() : _createCountdownOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
SceneStaticFunction _createCountdown1Function(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
switch (action.productType) {
case "3G":
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 1 CountDown',
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.countdown,
isAutomation
? _createAutomationCountDownOptions()
: _createCountdownOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
default:
return _createSceneFunction(
action,
'1 Gang Button Switch L-L',
Assets.oneGang,
'Light CountDown',
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.countdown,
isAutomation
? _createAutomationCountDownOptions()
: _createCountdownOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
}
}
SceneStaticFunction _createCountdown2Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createCountdown2Function(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 2 CountDown',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.countdown,
isAutomation ? _createAutomationCountDownOptions() : _createCountdownOptions(),
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.countdown,
isAutomation
? _createAutomationCountDownOptions()
: _createCountdownOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
}
SceneStaticFunction _createCountdown3Function(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createCountdown3Function(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'3 Gang Button Switch L-L',
Assets.assetsIcons3GangSwitch,
'Light 3 CountDown',
isAutomation ? OperationDialogType.integerSteps : OperationDialogType.countdown,
isAutomation ? _createAutomationCountDownOptions() : _createCountdownOptions(),
isAutomation
? OperationDialogType.integerSteps
: OperationDialogType.countdown,
isAutomation
? _createAutomationCountDownOptions()
: _createCountdownOptions(),
isAutomation,
comparator,
uniqueCustomId,
);
}
SceneStaticFunction _createSwitchAlarmSoundFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createSwitchAlarmSoundFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Gateway',
@ -846,8 +966,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createMasterStateFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createMasterStateFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Gateway',
@ -861,8 +981,8 @@ mixin SceneOperationsDataHelper {
);
}
SceneStaticFunction _createFactoryResetFunction(
Action action, bool isAutomation, String? comparator, String? uniqueCustomId) {
SceneStaticFunction _createFactoryResetFunction(Action action,
bool isAutomation, String? comparator, String? uniqueCustomId) {
return _createSceneFunction(
action,
'Gateway',
@ -1180,8 +1300,12 @@ mixin SceneOperationsDataHelper {
uniqueCustomId: taskItem.uniqueCustomId,
deviceId: taskItem.deviceId,
deviceName: taskItem.deviceName.toString(),
deviceIcon: taskItem.operationName == 'automation' ? Assets.player : Assets.handClickIcon,
icon: taskItem.operationName == 'automation' ? Assets.player : Assets.handClickIcon,
deviceIcon: taskItem.operationName == 'automation'
? Assets.player
: Assets.handClickIcon,
icon: taskItem.operationName == 'automation'
? Assets.player
: Assets.handClickIcon,
operationName: taskItem.operationName,
operationDialogType: OperationDialogType.onOff,
functionValue: taskItem.functionValue == 'rule_enable' ? true : false,

View File

@ -74,6 +74,7 @@ class Action {
ExecutorProperty? executorProperty;
String? name;
String? type;
String? productType;
Action({
required this.actionExecutor,
@ -81,6 +82,7 @@ class Action {
this.executorProperty,
this.name,
this.type,
this.productType,
});
String toRawJson() => json.encode(toJson());
@ -88,10 +90,11 @@ class Action {
static Action? fromJson(Map<String, dynamic> json) {
if (json['name'] != null && json['type'] != null) {
return Action(
actionExecutor: json["actionExecutor"],
entityId: json["entityId"],
name: json['name'],
type: json['type'],
actionExecutor: json["actionExecutor"] as String,
entityId: json["entityId"] as String,
name: json['name'] as String?,
type: json['type'] as String?,
productType: json['productType'] as String?,
);
}
if (json["executorProperty"] == null) {
@ -99,9 +102,10 @@ class Action {
}
return Action(
actionExecutor: json["actionExecutor"],
entityId: json["entityId"],
actionExecutor: json["actionExecutor"] as String,
entityId: json["entityId"] as String,
executorProperty: ExecutorProperty.fromJson(json["executorProperty"]),
productType: json['productType'] as String?,
);
}

View File

@ -29,25 +29,38 @@ class _SceneRoomsTabBarDevicesViewState
@override
void initState() {
selectedSpace = HomeCubit.getInstance().selectedSpace!;
rooms = List.from(HomeCubit.getInstance().selectedSpace?.subspaces ?? []);
if (rooms != null) {
if (rooms![0].id != '-1') {
rooms?.insert(
0,
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
selectedSpace = HomeCubit.getInstance().selectedSpace!;
rooms = List.from(selectedSpace.subspaces ?? []);
if (rooms != null && rooms!.isNotEmpty) {
if (rooms![0].id != '-1') {
rooms?.insert(
0,
SubSpaceModel(
name: 'All Devices',
devices: context.read<DevicesCubit>().allDevices,
id: '-1',
),
);
}
} else {
rooms = [
SubSpaceModel(
name: 'All Devices',
devices: context.read<DevicesCubit>().allDevices,
id: '-1',
),
);
)
];
}
}
_tabController =
TabController(length: rooms!.length, vsync: this, initialIndex: 0);
_tabController.addListener(_handleTabSwitched);
super.initState();
_tabController = TabController(length: rooms!.length, vsync: this);
_tabController.addListener(_handleTabSwitched);
setState(() {});
});
}
void _handleTabSwitched() {

View File

@ -1,75 +1,45 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/app_layout/model/community_model.dart';
import 'package:syncrow_app/features/app_layout/model/space_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/scene_listview.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/scene_bloc/scene_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/scene_bloc/scene_event.dart';
import 'package:syncrow_app/features/scene/bloc/smart_scene/smart_scene_select_dart_bloc.dart';
import 'package:syncrow_app/features/scene/helper/scene_bloc_factory.dart';
import 'package:syncrow_app/features/scene/widgets/empty_devices_widget.dart';
import 'package:syncrow_app/features/scene/widgets/scene_view_widget/scene_grid_view.dart';
import 'package:syncrow_app/features/scene/widgets/scene_view_widget/scene_header.dart';
import 'package:syncrow_app/features/shared_widgets/create_unit.dart';
import 'package:syncrow_app/features/shared_widgets/app_loading_indicator.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
class SceneView extends StatelessWidget {
const SceneView({
this.pageType = false,
super.key,
});
final bool pageType;
const SceneView({super.key, this.pageType = false});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (BuildContext context) {
if (pageType) {
return SceneBloc()
..add(LoadScenes(
HomeCubit.getInstance().selectedSpace?.id ?? '',
HomeCubit.getInstance().selectedSpace ??
SpaceModel(
id: '-1',
name: '',
community: Community(
uuid: '-1',
name: '',
)),
showInDevice: pageType));
} else {
return SceneBloc()
..add(LoadScenes(
HomeCubit.getInstance().selectedSpace?.id ?? '',
HomeCubit.getInstance().selectedSpace ??
SpaceModel(
id: '-1',
name: '',
community: Community(
uuid: '-1',
name: '',
)),
showInDevice: pageType))
..add(LoadAutomation(HomeCubit.getInstance().selectedSpace?.id ?? ''));
}
},
create: (context) => SceneBlocFactory.create(
pageType: pageType,
homeCubit: HomeCubit.getInstance(),
),
child: BlocBuilder<CreateSceneBloc, CreateSceneState>(
builder: (context, state) {
final selectedSpace = HomeCubit.getInstance().selectedSpace;
if (state is DeleteSceneSuccess) {
if (state.success) {
BlocProvider.of<SceneBloc>(context).add(LoadScenes(
HomeCubit.getInstance().selectedSpace!.id, HomeCubit.getInstance().selectedSpace!,
showInDevice: pageType));
BlocProvider.of<SceneBloc>(context)
.add(LoadAutomation(HomeCubit.getInstance().selectedSpace!.id));
}
if (state.success) _loadScenesAndAutomations(context, selectedSpace);
}
if (state is CreateSceneWithTasks) {
if (state.success == true) {
BlocProvider.of<SceneBloc>(context).add(LoadScenes(
HomeCubit.getInstance().selectedSpace!.id, HomeCubit.getInstance().selectedSpace!,
showInDevice: pageType));
BlocProvider.of<SceneBloc>(context)
.add(LoadAutomation(HomeCubit.getInstance().selectedSpace!.id));
if (state.success) {
_loadScenesAndAutomations(context, selectedSpace);
context.read<SmartSceneSelectBloc>().add(const SmartSceneClearEvent());
}
}
@ -77,23 +47,24 @@ class SceneView extends StatelessWidget {
listener: (context, state) {
if (state is SceneTriggerSuccess) {
context.showCustomSnackbar(
message: 'Scene ${state.sceneName} triggered successfully!');
message: 'Scene ${state.sceneName} triggered successfully!',
);
}
},
child: HomeCubit.getInstance().spaces?.isEmpty ?? true
? const CreateUnitWidget()
child: HomeCubit.getInstance().spaces.isEmpty
? const EmptyDevicesWidget()
: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (pageType == false) const SceneHeader(),
if (pageType == false) const SizedBox(height: 8),
if (!pageType) ...[
const SceneHeader(),
const SizedBox(height: 8),
],
BlocBuilder<SceneBloc, SceneState>(
builder: (context, state) {
if (state is SceneLoading) {
return const Center(
child: CircularProgressIndicator(),
);
return const AppLoadingIndicator();
}
if (state is SceneError) {
return Center(
@ -103,80 +74,83 @@ class SceneView extends StatelessWidget {
if (state is SceneLoaded) {
final scenes = state.scenes;
final automationList = state.automationList;
if (scenes.isEmpty) return const EmptyDevicesWidget();
return pageType
? Expanded(
child: SceneListview(
scenes: scenes,
loadingSceneId: state.loadingSceneId,
))
: Expanded(
child: ListView(
if (pageType) {
return SizedBox(
height: context.height * 0.1,
child: SceneListview(
scenes: scenes,
loadingSceneId: state.loadingSceneId,
),
);
}
return Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: Expanded(
child: ListView(
children: [
ExpansionTile(
tilePadding: const EdgeInsets.symmetric(
horizontal: 6,
),
initiallyExpanded: true,
iconColor: ColorsManager.grayColor,
title: const BodyMedium(
text: 'Tap to run routines',
),
children: [
Theme(
data: ThemeData()
.copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
tilePadding: const EdgeInsets.symmetric(horizontal: 6),
initiallyExpanded: true,
iconColor: ColorsManager.grayColor,
title: const BodyMedium(text: 'Tap to run routines'),
children: [
scenes.isNotEmpty
? SceneGrid(
scenes: scenes,
loadingSceneId: state.loadingSceneId,
disablePlayButton: false,
loadingStates:
state.loadingStates, // Add this line
)
: const Center(
child: BodyMedium(
text: 'No scenes have been added yet',
),
),
const SizedBox(
height: 10,
),
],
if (scenes.isNotEmpty)
SceneGrid(
scenes: scenes,
loadingSceneId: state.loadingSceneId,
disablePlayButton: false,
loadingStates: state.loadingStates,
)
else
const Center(
child: BodyMedium(
text: 'No scenes have been added yet',
),
),
),
Theme(
data: ThemeData()
.copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
initiallyExpanded: true,
iconColor: ColorsManager.grayColor,
tilePadding: const EdgeInsets.symmetric(horizontal: 6),
title: const BodyMedium(text: 'Automation'),
children: [
automationList.isNotEmpty
? SceneGrid(
scenes: automationList,
loadingSceneId: state.loadingSceneId,
disablePlayButton: true,
loadingStates:
state.loadingStates, // Add this line
)
: const Center(
child: BodyMedium(
text: 'No automations have been added yet',
),
),
const SizedBox(
height: 10,
),
],
),
),
const SizedBox(
height: 15,
),
const SizedBox(height: 10),
],
),
);
ExpansionTile(
initiallyExpanded: true,
iconColor: ColorsManager.grayColor,
tilePadding: const EdgeInsets.symmetric(
horizontal: 6,
),
title: const BodyMedium(text: 'Automation'),
children: [
if (automationList.isNotEmpty)
SceneGrid(
scenes: automationList,
loadingSceneId: state.loadingSceneId,
disablePlayButton: true,
loadingStates: state.loadingStates,
)
else
const Center(
child: BodyMedium(
text:
'No automations have been added yet',
),
),
const SizedBox(height: 10),
],
),
const SizedBox(height: 15),
],
),
),
);
}
return const SizedBox();
return const SizedBox.shrink();
},
),
],
@ -186,4 +160,21 @@ class SceneView extends StatelessWidget {
),
);
}
void _loadScenesAndAutomations(BuildContext context, SpaceModel? selectedSpace) {
BlocProvider.of<SceneBloc>(context)
..add(
LoadScenes(
selectedSpace!.id,
selectedSpace,
showInDevice: pageType,
),
)
..add(
LoadAutomation(
selectedSpace.id,
selectedSpace.community.uuid,
),
);
}
}

View File

@ -25,7 +25,7 @@ class DeleteRoutineButton extends StatelessWidget {
BlocProvider.of<SceneBloc>(context).add(LoadScenes(
HomeCubit.getInstance().selectedSpace!.id, HomeCubit.getInstance().selectedSpace!));
BlocProvider.of<SceneBloc>(context)
.add(LoadAutomation(HomeCubit.getInstance().selectedSpace!.id));
.add(LoadAutomation(HomeCubit.getInstance().selectedSpace!.id,HomeCubit.getInstance().selectedSpace!.community.uuid));
}
}
},

View File

@ -0,0 +1,22 @@
import 'package:flutter/material.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
class EmptyDevicesWidget extends StatelessWidget {
const EmptyDevicesWidget({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 48),
child: Text(
"No routines.\nEnable 'Show on Home Screen' to add routines",
textAlign: TextAlign.center,
style: TextStyle(
color: ColorsManager.grayColor,
fontWeight: FontWeight.w400,
fontSize: 12,
),
),
);
}
}

View File

@ -132,6 +132,10 @@ class SceneItem extends StatelessWidget {
spaceUuid: HomeCubit.getInstance()
.selectedSpace!
.id),
communityId: HomeCubit.getInstance()
.selectedSpace!
.community
.uuid,
automationId: scene.id));
},
),

View File

@ -22,7 +22,7 @@ class SmartEnableAutomation extends StatelessWidget {
child: BlocBuilder<SceneBloc, SceneState>(
bloc: context.read<SceneBloc>()
..add(
LoadAutomation(HomeCubit.getInstance().selectedSpace?.id ?? '')),
LoadAutomation(HomeCubit.getInstance().selectedSpace?.id ?? '',HomeCubit.getInstance().selectedSpace?.community.uuid ?? '')),
builder: (context, state) {
if (state is SceneLoading) {
return const Align(

View File

@ -0,0 +1,12 @@
import 'package:flutter/material.dart';
class AppLoadingIndicator extends StatelessWidget {
const AppLoadingIndicator({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: CircularProgressIndicator.adaptive(),
);
}
}

View File

@ -144,7 +144,7 @@ abstract class ApiEndpoints {
/// POST
static const String createScene = '/scene/tap-to-run';
static const String triggerScene = '/scene/tap-to-run/{sceneId}/trigger';
static const String createAutomation = '/automation';
static const String createAutomation = '/projects/{projectId}/automations';
/// GET
static const String getUnitScenes =
@ -153,23 +153,23 @@ abstract class ApiEndpoints {
static const String getScene = '/scene/tap-to-run/{sceneId}';
static const String getIconScene = '/scene/icon';
static const String getUnitAutomation = '/automation/{unitUuid}';
static const String getUnitAutomation = '/projects/{projectId}/communities/{communityId}/spaces/{unitUuid}/automations';
static const String getAutomationDetails =
'/automation/details/{automationId}';
'/projects/{projectId}/automations/{automationId}';
/// PUT
static const String updateScene = '/scene/tap-to-run/{sceneId}';
static const String updateAutomation = '/automation/{automationId}';
static const String updateAutomation = '/projects/{projectId}/automations/{automationId}';
static const String updateAutomationStatus =
'/automation/status/{automationId}';
'/projects/{projectId}/automations/{automationId}';
/// DELETE
static const String deleteScene = '/scene/tap-to-run/{sceneId}';
static const String deleteAutomation = '/automation/{automationId}';
static const String deleteAutomation = '/projects/{projectId}/automations/{automationId}';
//////////////////////Door Lock //////////////////////
//online

View File

@ -6,7 +6,6 @@ import 'package:syncrow_app/features/scene/model/scenes_model.dart';
import 'package:syncrow_app/features/scene/model/update_automation.dart';
import 'package:syncrow_app/services/api/api_links_endpoints.dart';
import 'package:syncrow_app/services/api/http_service.dart';
import 'package:syncrow_app/utils/constants/temp_const.dart';
class SceneApi {
static final HTTPService _httpService = HTTPService();
@ -31,10 +30,11 @@ class SceneApi {
// create automation
static Future<Map<String, dynamic>> createAutomation(
CreateAutomationModel createAutomationModel) async {
CreateAutomationModel createAutomationModel, String projectId) async {
try {
final response = await _httpService.post(
path: ApiEndpoints.createAutomation,
path:
ApiEndpoints.createAutomation.replaceAll('{projectId}', projectId),
body: createAutomationModel.toMap(),
showServerMessage: false,
expectedResponseModel: (json) {
@ -78,10 +78,17 @@ class SceneApi {
//getAutomation
static Future<List<ScenesModel>> getAutomationByUnitId(String unitId) async {
static Future<List<ScenesModel>> getAutomationByUnitId(
String unitId,
String communityId,
String projectId,
) async {
try {
final response = await _httpService.get(
path: ApiEndpoints.getUnitAutomation.replaceAll('{unitUuid}', unitId),
path: ApiEndpoints.getUnitAutomation
.replaceAll('{unitUuid}', unitId)
.replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', projectId),
showServerMessage: false,
expectedResponseModel: (json) {
List<ScenesModel> scenes = [];
@ -112,11 +119,12 @@ class SceneApi {
//automation details
static Future<SceneDetailsModel> getAutomationDetails(
String automationId) async {
String automationId, String projectId) async {
try {
final response = await _httpService.get(
path: ApiEndpoints.getAutomationDetails
.replaceAll('{automationId}', automationId),
.replaceAll('{automationId}', automationId)
.replaceAll('{projectId}', projectId),
showServerMessage: false,
expectedResponseModel: (json) => SceneDetailsModel.fromJson(json),
);
@ -128,11 +136,12 @@ class SceneApi {
//updateAutomationStatus
static Future<bool> updateAutomationStatus(String automationId,
AutomationStatusUpdate createAutomationEnable) async {
AutomationStatusUpdate createAutomationEnable, String projectId) async {
try {
final response = await _httpService.put(
final response = await _httpService.patch(
path: ApiEndpoints.updateAutomationStatus
.replaceAll('{automationId}', automationId),
.replaceAll('{automationId}', automationId)
.replaceAll('{projectId}', projectId),
body: createAutomationEnable.toMap(),
expectedResponseModel: (json) => json['success'],
);
@ -194,12 +203,13 @@ class SceneApi {
}
//update automation
static updateAutomation(
CreateAutomationModel createAutomationModel, String automationId) async {
static updateAutomation(CreateAutomationModel createAutomationModel,
String automationId, String projectId) async {
try {
final response = await _httpService.put(
path: ApiEndpoints.updateAutomation
.replaceAll('{automationId}', automationId),
.replaceAll('{automationId}', automationId)
.replaceAll('{projectId}', projectId),
body: createAutomationModel
.toJson(automationId.isNotEmpty == true ? automationId : null),
expectedResponseModel: (json) {
@ -229,11 +239,14 @@ class SceneApi {
// delete automation
static Future<bool> deleteAutomation(
{required String unitUuid, required String automationId}) async {
{required String unitUuid,
required String automationId,
required String projectId}) async {
try {
final response = await _httpService.delete(
path: ApiEndpoints.deleteAutomation
.replaceAll('{automationId}', automationId),
.replaceAll('{automationId}', automationId)
.replaceAll('{projectId}', projectId),
showServerMessage: false,
expectedResponseModel: (json) => json['statusCode'] == 200,
);