Updated the API Endpoints, API Calls, Data Models and cubits to the lateset changes from the backend

This commit is contained in:
Mohammad Salameh
2024-04-29 10:00:58 +03:00
parent f24953a57c
commit f8358a0877
19 changed files with 255 additions and 199 deletions

View File

@ -18,9 +18,9 @@ part 'home_state.dart';
class HomeCubit extends Cubit<HomeState> { class HomeCubit extends Cubit<HomeState> {
HomeCubit._() : super(HomeInitial()) { HomeCubit._() : super(HomeInitial()) {
if (selectedSpace == null) { if (selectedSpace == null) {
fetchSpaces().then((value) { fetchUnitsByUserId().then((value) {
if (selectedSpace != null) { if (selectedSpace != null) {
fetchRooms(selectedSpace!); fetchRoomsByUnitId(selectedSpace!);
} }
}); });
} }
@ -120,10 +120,10 @@ class HomeCubit extends Cubit<HomeState> {
} }
//////////////////////////////////////// API //////////////////////////////////////// //////////////////////////////////////// API ////////////////////////////////////////
fetchSpaces() async { fetchUnitsByUserId() async {
emitSafe(GetSpacesLoading()); emitSafe(GetSpacesLoading());
try { try {
spaces = await SpacesAPI.getSpaces(); spaces = await SpacesAPI.getUnitsByUserId();
} catch (failure) { } catch (failure) {
emitSafe(GetSpacesError(failure.toString())); emitSafe(GetSpacesError(failure.toString()));
return; return;
@ -132,13 +132,13 @@ class HomeCubit extends Cubit<HomeState> {
if (spaces != null && spaces!.isNotEmpty) { if (spaces != null && spaces!.isNotEmpty) {
selectedSpace = spaces!.first; selectedSpace = spaces!.first;
emitSafe(GetSpacesSuccess(spaces!)); emitSafe(GetSpacesSuccess(spaces!));
fetchRooms(selectedSpace!); // fetchRoomsByUnitId(selectedSpace!);
} else { } else {
emitSafe(GetSpacesError("No spaces found")); emitSafe(GetSpacesError("No spaces found"));
} }
} }
fetchRooms(SpaceModel space) async { fetchRoomsByUnitId(SpaceModel space) async {
emitSafe(GetSpaceRoomsLoading()); emitSafe(GetSpaceRoomsLoading());
try { try {
space.rooms = await SpacesAPI.getRoomsBySpaceId(space.id!); space.rooms = await SpacesAPI.getRoomsBySpaceId(space.id!);

View File

@ -1,11 +1,14 @@
import 'package:syncrow_app/features/devices/model/room_model.dart'; import 'package:syncrow_app/features/devices/model/room_model.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
class SpaceModel { class SpaceModel {
final int? id; final String? id;
final String? name; final String? name;
final SpaceType type;
late List<RoomModel>? rooms; late List<RoomModel>? rooms;
SpaceModel({ SpaceModel({
required this.type,
required this.id, required this.id,
required this.name, required this.name,
required this.rooms, required this.rooms,
@ -21,8 +24,9 @@ class SpaceModel {
factory SpaceModel.fromJson(Map<String, dynamic> json) { factory SpaceModel.fromJson(Map<String, dynamic> json) {
return SpaceModel( return SpaceModel(
id: int.parse(json['homeId']), id: json['uuid'],
name: json['homeName'], name: json['name'],
type: spaceTypesMap[json['type']]!,
rooms: [], rooms: [],
); );
} }

View File

@ -46,7 +46,7 @@ class AuthCubit extends Cubit<AuthState> {
String? passwordValidator(String? value) { String? passwordValidator(String? value) {
if (value != null) { if (value != null) {
if (value.isNotEmpty) { if (value.isNotEmpty) {
if (value.length >= 6) { // if (value.length >= 6) {
return null; return null;
//TODO uncomment this code when the password validation is needed //TODO uncomment this code when the password validation is needed
// if (RegExp( // if (RegExp(
@ -56,9 +56,9 @@ class AuthCubit extends Cubit<AuthState> {
// } else { // } else {
// return 'Password must contain at least one uppercase letter, one lowercase letter, one number and one special character'; // return 'Password must contain at least one uppercase letter, one lowercase letter, one number and one special character';
// } // }
} else { // } else {
return 'Password must be at least 6 characters'; // return 'Password must be at least 6 characters';
} // }
} else { } else {
return 'Please enter your password'; return 'Please enter your password';
} }
@ -106,12 +106,15 @@ class AuthCubit extends Cubit<AuthState> {
return; return;
} }
if (token.accessTokenIsNotEmpty) { if (token.accessTokenIsNotEmpty) {
debugPrint('token: ${token.accessToken}');
FlutterSecureStorage storage = const FlutterSecureStorage(); FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write( await storage.write(
key: Token.loginAccessTokenKey, value: token.accessToken); key: Token.loginAccessTokenKey, value: token.accessToken);
const FlutterSecureStorage().write( const FlutterSecureStorage().write(
key: UserModel.userUuidKey, key: UserModel.userUuidKey,
value: Token.decodeToken(token.accessToken)['uuid'].toString()); value: Token.decodeToken(token.accessToken)['uuid'].toString());
user = UserModel.fromToken(token); user = UserModel.fromToken(token);
emailController.clear(); emailController.clear();
passwordController.clear(); passwordController.clear();

View File

@ -4,7 +4,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/utils/helpers/decode_base64.dart'; import 'package:syncrow_app/utils/helpers/decode_base64.dart';
class Token { class Token {
static const String loginAccessTokenKey = 'access_token'; static const String loginAccessTokenKey = 'accessToken';
static const String loginRefreshTokenKey = 'refreshToken'; static const String loginRefreshTokenKey = 'refreshToken';
final String accessToken; final String accessToken;
@ -56,7 +56,8 @@ class Token {
var storage = const FlutterSecureStorage(); var storage = const FlutterSecureStorage();
storage.write( storage.write(
key: loginAccessTokenKey, value: json[loginAccessTokenKey] ?? ''); key: loginAccessTokenKey, value: json[loginAccessTokenKey] ?? '');
storage.write(
key: loginRefreshTokenKey, value: json[loginRefreshTokenKey] ?? '');
//create token object ? //create token object ?
return Token(json[loginAccessTokenKey] ?? '', return Token(json[loginAccessTokenKey] ?? '',
json[loginRefreshTokenKey] ?? '', '', 0, 0); json[loginRefreshTokenKey] ?? '', '', 0, 0);

View File

@ -25,7 +25,7 @@ part 'devices_state.dart';
class DevicesCubit extends Cubit<DevicesState> { class DevicesCubit extends Cubit<DevicesState> {
DevicesCubit._() : super(DevicesInitial()) { DevicesCubit._() : super(DevicesInitial()) {
if (HomeCubit.getInstance().selectedSpace != null) { if (HomeCubit.getInstance().selectedSpace != null) {
fetchGroups(HomeCubit.getInstance().selectedSpace!.id!); // fetchGroups(HomeCubit.getInstance().selectedSpace!.id!);
for (var room in HomeCubit.getInstance().selectedSpace!.rooms!) { for (var room in HomeCubit.getInstance().selectedSpace!.rooms!) {
fetchDevicesByRoomId(room.id!); fetchDevicesByRoomId(room.id!);
} }
@ -257,7 +257,7 @@ class DevicesCubit extends Cubit<DevicesState> {
emitSafe(DeviceControlSuccess(code: control.code)); emitSafe(DeviceControlSuccess(code: control.code));
//this delay is to give tuya server time to update the status //this delay is to give tuya server time to update the status
Future.delayed(const Duration(milliseconds: 400), () { Future.delayed(const Duration(milliseconds: 400), () {
getDevicesStatues( fetchDevicesStatues(
deviceId, deviceId,
HomeCubit.getInstance() HomeCubit.getInstance()
.selectedSpace! .selectedSpace!
@ -274,7 +274,7 @@ class DevicesCubit extends Cubit<DevicesState> {
} }
} }
fetchGroups(int spaceId) async { fetchGroups(String spaceId) async {
emitSafe(DevicesCategoriesLoading()); emitSafe(DevicesCategoriesLoading());
try { try {
allCategories = await DevicesAPI.fetchGroups(spaceId); allCategories = await DevicesAPI.fetchGroups(spaceId);
@ -289,7 +289,7 @@ class DevicesCubit extends Cubit<DevicesState> {
} }
} }
fetchDevicesByRoomId(int? roomId) async { fetchDevicesByRoomId(String? roomId) async {
if (roomId == null) return; if (roomId == null) return;
emitSafe(GetDevicesLoading()); emitSafe(GetDevicesLoading());
@ -308,23 +308,26 @@ class DevicesCubit extends Cubit<DevicesState> {
//get status for each device //get status for each device
//TODO get devices status per page via page controller instead of getting all devices status at once //TODO get devices status per page via page controller instead of getting all devices status at once
for (var device List<DeviceModel> devices =
in HomeCubit.getInstance().selectedSpace!.rooms![roomIndex].devices!) { HomeCubit.getInstance().selectedSpace!.rooms![roomIndex].devices!;
getDevicesStatues(device.id!, roomIndex); if (devices.isNotEmpty) {
for (var device in devices) {
fetchDevicesStatues(device.uuid!, roomIndex);
}
} }
} }
getDevicesStatues(String deviceId, int roomIndex, {String? code}) async { fetchDevicesStatues(String deviceUuid, int roomIndex, {String? code}) async {
emitSafe(GetDeviceStatusLoading(code: code)); emitSafe(GetDeviceStatusLoading(code: code));
int deviceIndex = HomeCubit.getInstance() int deviceIndex = HomeCubit.getInstance()
.selectedSpace! .selectedSpace!
.rooms![roomIndex] .rooms![roomIndex]
.devices! .devices!
.indexWhere((element) => element.id == deviceId); .indexWhere((element) => element.uuid == deviceUuid);
List<StatusModel> statuses = []; List<StatusModel> statuses = [];
try { try {
var response = await DevicesAPI.getDeviceStatus(deviceId); var response = await DevicesAPI.getDeviceStatus(deviceUuid);
for (var status in response['result']['status']) { for (var status in response['status']) {
statuses.add(StatusModel.fromJson(status)); statuses.add(StatusModel.fromJson(status));
} }
} catch (e) { } catch (e) {

View File

@ -10,8 +10,9 @@ class DeviceControlModel {
}); });
factory DeviceControlModel.fromJson(Map<String, dynamic> json) { factory DeviceControlModel.fromJson(Map<String, dynamic> json) {
print('json: $json');
return DeviceControlModel( return DeviceControlModel(
deviceId: json['deviceId'], deviceId: json['deviceUuid'],
code: json['code'], code: json['code'],
value: json['value'], value: json['value'],
); );
@ -19,7 +20,7 @@ class DeviceControlModel {
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'deviceId': deviceId, 'deviceUuid': deviceId,
'code': code, 'code': code,
'value': value, 'value': value,
}; };

View File

@ -5,25 +5,14 @@ import 'package:syncrow_app/utils/resource_manager/constants.dart';
class DeviceModel { class DeviceModel {
int? activeTime; int? activeTime;
String? category; //unused // String? id;
String? categoryName; //unused
int? createTime; //unused
String? gatewayId; //unused
String? icon; //unused
String? id;
String? ip; //unused
double? lat; //unused
String? localKey; String? localKey;
double? lon; //unused
String? model; String? model;
String? name; String? name;
String? nodeId; //remove String? icon;
bool? isOnline; bool? isOnline;
List<StatusModel> status = []; List<StatusModel> status = [];
String? ownerId; //unused
String? productId; //unused
String? productName; String? productName;
bool? isSub; //unused
String? timeZone; String? timeZone;
int? updateTime; int? updateTime;
String? uuid; String? uuid;
@ -32,108 +21,70 @@ class DeviceModel {
late List<FunctionModel> functions; late List<FunctionModel> functions;
DeviceModel({ DeviceModel({
this.activeTime, this.activeTime,
this.category, // this.id,
this.categoryName,
this.createTime,
this.gatewayId,
this.icon,
this.id,
this.ip,
this.lat,
this.localKey, this.localKey,
this.lon,
this.model, this.model,
this.name, this.name,
this.nodeId,
this.isOnline, this.isOnline,
required this.status, required this.status,
this.ownerId,
this.productId,
this.productName, this.productName,
this.isSub,
this.timeZone, this.timeZone,
this.updateTime, this.updateTime,
this.uuid, this.uuid,
this.productType, this.productType,
this.icon,
}) { }) {
functions = getFunctions(productType!); functions = getFunctions(productType!);
} }
factory DeviceModel.fromJson(Map<String, dynamic> json) { factory DeviceModel.fromJson(Map<String, dynamic> json) {
String icon = ''; String tempIcon = '';
DeviceType type = devicesTypesMap[json['productId']] ?? DeviceType.Other; DeviceType type = devicesTypesMap[json['productType']] ?? DeviceType.Other;
if (type == DeviceType.LightBulb) { if (type == DeviceType.LightBulb) {
icon = Assets.iconsLight; tempIcon = Assets.iconsLight;
} else if (type == DeviceType.CeilingSensor || } else if (type == DeviceType.CeilingSensor ||
type == DeviceType.WallSensor) { type == DeviceType.WallSensor) {
icon = Assets.iconsSensors; tempIcon = Assets.iconsSensors;
} else if (type == DeviceType.AC) { } else if (type == DeviceType.AC) {
icon = Assets.iconsAC; tempIcon = Assets.iconsAC;
} else if (type == DeviceType.DoorLock) { } else if (type == DeviceType.DoorLock) {
icon = Assets.iconsDoorLock; tempIcon = Assets.iconsDoorLock;
} else if (type == DeviceType.Curtain) { } else if (type == DeviceType.Curtain) {
icon = Assets.iconsCurtain; tempIcon = Assets.iconsCurtain;
} else if (type == DeviceType.ThreeGang) { } else if (type == DeviceType.ThreeGang) {
icon = Assets.icons3GangSwitch; tempIcon = Assets.icons3GangSwitch;
} else if (type == DeviceType.Gateway) { } else if (type == DeviceType.Gateway) {
icon = Assets.iconsGateway; tempIcon = Assets.iconsGateway;
} else { } else {
icon = Assets.iconsLogo; tempIcon = Assets.iconsLogo;
} }
return DeviceModel( return DeviceModel(
icon: tempIcon,
activeTime: json['activeTime'], activeTime: json['activeTime'],
category: json['category'], // id: json['id'],
categoryName: json['categoryName'],
createTime: json['createTime'],
gatewayId: json['gatewayId'],
icon: icon,
id: json['id'],
ip: json['ip'],
lat: double.tryParse(json['lat']),
localKey: json['localKey'], localKey: json['localKey'],
lon: double.tryParse(json['lon']),
model: json['model'], model: json['model'],
name: json['name'], name: json['name'],
nodeId: json['nodeId'],
isOnline: json['online'], isOnline: json['online'],
ownerId: json['ownerId'],
productId: json['productId'],
productName: json['productName'], productName: json['productName'],
isSub: json['sub'],
timeZone: json['timeZone'], timeZone: json['timeZone'],
updateTime: json['updateTime'], updateTime: json['updateTime'],
uuid: json['uuid'], uuid: json['uuid'],
productType: type, productType: type,
status: [], status: [],
// json['status']
// .map<StatusModel>((e) => StatusModel.fromJson(e))
// .toList(),
// devicesTypesMap[json['productName']] ?? DeviceType.Other,
); );
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'activeTime': activeTime, 'activeTime': activeTime,
'category': category, // 'id': id,
'categoryName': categoryName,
'createTime': createTime,
'gatewayId': gatewayId,
'icon': icon,
'id': id,
'ip': ip,
'lat': lat,
'localKey': localKey, 'localKey': localKey,
'lon': lon,
'model': model, 'model': model,
'name': name, 'name': name,
'nodeId': nodeId,
'online': isOnline, 'online': isOnline,
'ownerId': ownerId,
'productId': productId,
'productName': productName, 'productName': productName,
'sub': isSub,
'timeZone': timeZone, 'timeZone': timeZone,
'updateTime': updateTime, 'updateTime': updateTime,
'uuid': uuid, 'uuid': uuid,

View File

@ -3,7 +3,7 @@ import 'package:syncrow_app/utils/resource_manager/constants.dart';
class FunctionModel { class FunctionModel {
String? code; String? code;
FunctionType? type; FunctionType? type;
ValueModel? values; dynamic values;
FunctionModel({ FunctionModel({
required this.code, required this.code,

View File

@ -1,14 +1,16 @@
import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
class RoomModel { class RoomModel {
final int? id; final String? id;
final String? name; final String? name;
final SpaceType type;
List<DeviceModel>? devices; List<DeviceModel>? devices;
RoomModel({ RoomModel({
required this.id, required this.id,
required this.name, required this.name,
required this.type,
required this.devices, required this.devices,
}); });
@ -16,6 +18,7 @@ class RoomModel {
return { return {
'id': id, 'id': id,
'name': name, 'name': name,
'type': type,
'devices': devices, 'devices': devices,
}; };
} }
@ -28,9 +31,10 @@ class RoomModel {
} }
} }
return RoomModel( return RoomModel(
id: json['roomId'], id: json['uuid'],
name: json['roomName'], name: json['name'],
devices: devices, type: spaceTypesMap[json['type']]!,
devices: [],
); );
} }
} }

View File

@ -91,10 +91,10 @@ class AcInterfaceTempUnit extends StatelessWidget {
value = double.parse(valueAsString); value = double.parse(valueAsString);
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: acDevice.id, deviceId: acDevice.uuid,
code: 'temp_set', code: 'temp_set',
value: value * 10), value: value * 10),
acDevice.id!); acDevice.uuid!);
} }
}, },
), ),
@ -121,10 +121,10 @@ class AcInterfaceTempUnit extends StatelessWidget {
if (setToTemp > 20) { if (setToTemp > 20) {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: acDevice.id, deviceId: acDevice.uuid,
code: 'temp_set', code: 'temp_set',
value: (setToTemp - 0.5) * 10), value: (setToTemp - 0.5) * 10),
acDevice.id!); acDevice.uuid!);
} }
}, },
child: SvgPicture.asset( child: SvgPicture.asset(
@ -171,10 +171,10 @@ class AcInterfaceTempUnit extends StatelessWidget {
if (setToTemp < 30) { if (setToTemp < 30) {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: acDevice.id, deviceId: acDevice.uuid,
code: 'temp_set', code: 'temp_set',
value: (setToTemp + 0.5) * 10), value: (setToTemp + 0.5) * 10),
acDevice.id!); acDevice.uuid!);
} }
}, },
child: SvgPicture.asset( child: SvgPicture.asset(

View File

@ -42,10 +42,10 @@ class _ACModeControlUnitState extends State<ACModeControlUnit> {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: widget.acDevice.id, deviceId: widget.acDevice.uuid,
code: 'level', code: 'level',
value: reversedFanSpeedsMap[fanSpeed]!), value: reversedFanSpeedsMap[fanSpeed]!),
widget.acDevice.id!); widget.acDevice.uuid!);
}, },
child: DefaultContainer( child: DefaultContainer(
height: 55, height: 55,
@ -68,10 +68,10 @@ class _ACModeControlUnitState extends State<ACModeControlUnit> {
tempMode = tempModesMap[getNextItem(tempModesMap, tempMode)]!; tempMode = tempModesMap[getNextItem(tempModesMap, tempMode)]!;
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: widget.acDevice.id, deviceId: widget.acDevice.uuid,
code: 'mode', code: 'mode',
value: reversedTempModesMap[tempMode]!), value: reversedTempModesMap[tempMode]!),
widget.acDevice.id!); widget.acDevice.uuid!);
}, },
child: DefaultContainer( child: DefaultContainer(
height: 55, height: 55,

View File

@ -150,10 +150,10 @@ class ParameterControlDialogState extends State<ParameterControlDialog> {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: widget.sensor.id, deviceId: widget.sensor.uuid,
code: widget.controlCode, code: widget.controlCode,
value: widget.value), value: widget.value),
widget.sensor.id ?? ''); widget.sensor.uuid ?? '');
}, },
child: Center( child: Center(
child: BodyMedium( child: BodyMedium(

View File

@ -313,11 +313,11 @@ Widget listItem(
if (wallSensor.isOnline ?? false) { if (wallSensor.isOnline ?? false) {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: wallSensor.id, deviceId: wallSensor.uuid,
code: 'indicator', code: 'indicator',
value: value, value: value,
), ),
wallSensor.id ?? ''); wallSensor.uuid ?? '');
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(

View File

@ -34,7 +34,7 @@ class ThreeGangInterfaceBody extends StatelessWidget {
GangSwitch( GangSwitch(
threeGangSwitch: device, threeGangSwitch: device,
control: DeviceControlModel( control: DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
// code: 'switch_1', // code: 'switch_1',
code: device.status[0].code, code: device.status[0].code,
// value: true, // value: true,
@ -60,7 +60,7 @@ class ThreeGangInterfaceBody extends StatelessWidget {
// deviceId: 'bfe10693d4fd263206ocq9', // deviceId: 'bfe10693d4fd263206ocq9',
// code: 'switch_2', // code: 'switch_2',
// value: true, // value: true,
deviceId: device.id, deviceId: device.uuid,
code: device.status[1].code, code: device.status[1].code,
value: device.status[1].value, value: device.status[1].value,
), ),
@ -84,7 +84,7 @@ class ThreeGangInterfaceBody extends StatelessWidget {
// deviceId: 'bfe10693d4fd263206ocq9', // deviceId: 'bfe10693d4fd263206ocq9',
// code: 'switch_3', // code: 'switch_3',
// value: true, // value: true,
deviceId: device.id, deviceId: device.uuid,
code: device.status[2].code, code: device.status[2].code,
value: device.status[2].value, value: device.status[2].value,
), ),
@ -120,27 +120,27 @@ class ThreeGangInterfaceBody extends StatelessWidget {
onTap: () { onTap: () {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_1', code: 'switch_1',
value: true, value: true,
), ),
device.id!, device.uuid!,
); );
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_2', code: 'switch_2',
value: true, value: true,
), ),
device.id!, device.uuid!,
); );
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_3', code: 'switch_3',
value: true, value: true,
), ),
device.id!, device.uuid!,
); );
}, },
child: Stack( child: Stack(
@ -252,27 +252,27 @@ class ThreeGangInterfaceBody extends StatelessWidget {
onTap: () { onTap: () {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_1', code: 'switch_1',
value: false, value: false,
), ),
device.id!, device.uuid!,
); );
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_2', code: 'switch_2',
value: false, value: false,
), ),
device.id!, device.uuid!,
); );
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: 'switch_3', code: 'switch_3',
value: false, value: false,
), ),
device.id!, device.uuid!,
); );
}, },
child: Stack( child: Stack(

View File

@ -26,7 +26,7 @@ class CustomSwitch extends StatelessWidget {
onTap: () { onTap: () {
DevicesCubit.getInstance().deviceControl( DevicesCubit.getInstance().deviceControl(
DeviceControlModel( DeviceControlModel(
deviceId: device.id, deviceId: device.uuid,
code: device.status code: device.status
.firstWhere((status) => status.code == "switch") .firstWhere((status) => status.code == "switch")
.code, .code,
@ -34,7 +34,7 @@ class CustomSwitch extends StatelessWidget {
.firstWhere((status) => status.code == "switch") .firstWhere((status) => status.code == "switch")
.value!, .value!,
), ),
device.id!, device.uuid!,
); );
}, },
child: Container( child: Container(

View File

@ -1,7 +1,9 @@
abstract class ApiEndpoints { abstract class ApiEndpoints {
static const String baseUrl = 'https://syncrow.azurewebsites.net'; static const String baseUrl = 'https://syncrow.azurewebsites.net';
// static const String baseUrl = 'http://100.107.182.63:4001'; //Localhost
////////////////////////////////////// Authentication ///////////////////////////////
// Authentication
static const String signUp = '$baseUrl/authentication/user/signup'; static const String signUp = '$baseUrl/authentication/user/signup';
static const String login = '$baseUrl/authentication/user/login'; static const String login = '$baseUrl/authentication/user/login';
static const String deleteUser = '$baseUrl/authentication/user/delete/{id}'; static const String deleteUser = '$baseUrl/authentication/user/delete/{id}';
@ -10,16 +12,100 @@ abstract class ApiEndpoints {
static const String forgetPassword = static const String forgetPassword =
'$baseUrl/authentication/user/forget-password'; '$baseUrl/authentication/user/forget-password';
// Spaces ////////////////////////////////////// Spaces ///////////////////////////////////////
static const String spaces = '$baseUrl/home';
static const String rooms = '$baseUrl/room';
// Devices ///Community Module
static const String control = '$baseUrl/device/control'; //POST
static const String devicesByRoom = '$baseUrl/device/room'; static const String addCommunity = '$baseUrl/community';
// static const String deviceStatus = '$baseUrl/device/status/'; static const String addCommunityToUser = '$baseUrl/community/user';
static const String deviceStatus = '$baseUrl/device/'; //GET
static const String communityByUuid = '$baseUrl/community/{communityUuid}';
static const String communityChild =
'$baseUrl/community/child/{communityUuid}';
static const String communityUser = '$baseUrl/community/user/{userUuid}';
//PUT
static const String renameCommunity =
'$baseUrl/community/rename/{communityUuid}';
//groups ///Building Module
static const String groups = '$baseUrl/group'; //POST
static const String addBuilding = '$baseUrl/building';
static const String addBuildingToUser = '$baseUrl/building/user';
//GET
static const String buildingByUuid = '$baseUrl/building/{buildingUuid}';
static const String buildingChild = '$baseUrl/building/child/{buildingUuid}';
static const String buildingParent =
'$baseUrl/building/parent/{buildingUuid}';
static const String buildingUser = '$baseUrl/building/user/{userUuid}';
//PUT
static const String renameBuilding =
'$baseUrl/building/rename/{buildingUuid}';
///Floor Module
//POST
static const String addFloor = '$baseUrl/floor';
static const String addFloorToUser = '$baseUrl/floor/user';
//GET
static const String floorByUuid = '$baseUrl/floor/{floorUuid}';
static const String floorChild = '$baseUrl/floor/child/{floorUuid}';
static const String floorParent = '$baseUrl/floor/parent/{floorUuid}';
static const String floorUser = '$baseUrl/floor/user/{userUuid}';
//PUT
static const String renameFloor = '$baseUrl/floor/rename/{floorUuid}';
///Unit Module
//POST
static const String addUnit = '$baseUrl/unit';
static const String addUnitToUser = '$baseUrl/unit/user';
//GET
static const String unitByUuid = '$baseUrl/unit/';
static const String unitChild = '$baseUrl/unit/child/';
static const String unitParent = '$baseUrl/unit/parent/{unitUuid}';
static const String unitUser = '$baseUrl/unit/user/';
//PUT
static const String renameUnit = '$baseUrl/unit/rename/{unitUuid}';
///Room Module
//POST
static const String addRoom = '$baseUrl/room';
static const String addRoomToUser = '$baseUrl/room/user';
//GET
static const String roomByUuid = '$baseUrl/room/{roomUuid}';
static const String roomParent = '$baseUrl/room/parent/{roomUuid}';
static const String roomUser = '$baseUrl/room/user/{userUuid}';
//PUT
static const String renameRoom = '$baseUrl/room/rename/{roomUuid}';
///Group Module
//POST
static const String addGroup = '$baseUrl/group';
static const String controlGroup = '$baseUrl/group/control';
//GET
static const String groupBySpace = '$baseUrl/group/space/{spaceUuid}';
static const String groupByUuid = '$baseUrl/group/{groupUuid}';
//DELETE
static const String deleteGroup = '$baseUrl/group/{groupUuid}';
////////////////////////////////////// Devices ///////////////////////////////////////
///Device Module
//POST
static const String addDeviceToRoom = '$baseUrl/device/room';
static const String addDeviceToGroup = '$baseUrl/device/group';
static const String controlDevice = '$baseUrl/device/control';
//GET
static const String deviceByRoom = '$baseUrl/device/room';
static const String deviceByUuid = '$baseUrl/device/{deviceUuid}';
static const String deviceFunctions =
'$baseUrl/device/{deviceUuid}/functions';
static const String deviceFunctionsStatus =
'$baseUrl/device/{deviceUuid}/functions/status';
///Device Permission Module
//POST
static const String addDevicePermission = '$baseUrl/device-permission/add';
//GET
static const String devicePermissionList = '$baseUrl/device-permission/list';
//PUT
static const String editDevicePermission =
'$baseUrl/device-permission/edit/{userId}';
} }

View File

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:syncrow_app/features/devices/model/device_category_model.dart'; import 'package:syncrow_app/features/devices/model/device_category_model.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart'; import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart'; import 'package:syncrow_app/features/devices/model/device_model.dart';
@ -11,7 +13,7 @@ class DevicesAPI {
DeviceControlModel controlModel) async { DeviceControlModel controlModel) async {
try { try {
final response = await _httpService.post( final response = await _httpService.post(
path: ApiEndpoints.control, path: ApiEndpoints.controlDevice,
body: controlModel.toJson(), body: controlModel.toJson(),
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
@ -24,7 +26,7 @@ class DevicesAPI {
} }
} }
static Future<List<DevicesCategoryModel>> fetchGroups(int spaceId) async { static Future<List<DevicesCategoryModel>> fetchGroups(String spaceId) async {
Map<String, dynamic> params = { Map<String, dynamic> params = {
"homeId": spaceId, "homeId": spaceId,
"pageSize": 100, "pageSize": 100,
@ -32,7 +34,7 @@ class DevicesAPI {
}; };
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.groups, path: ApiEndpoints.groupBySpace.replaceAll("{spaceUuid}", spaceId),
queryParameters: params, queryParameters: params,
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) => expectedResponseModel: (json) =>
@ -43,7 +45,8 @@ class DevicesAPI {
static Future<Map<String, dynamic>> getDeviceStatus(String deviceId) async { static Future<Map<String, dynamic>> getDeviceStatus(String deviceId) async {
final response = await _httpService.get( final response = await _httpService.get(
path: '${ApiEndpoints.deviceStatus}/$deviceId/functions/status', path: ApiEndpoints.deviceFunctionsStatus
.replaceAll('{deviceUuid}', deviceId),
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json; return json;
@ -52,14 +55,20 @@ class DevicesAPI {
return response; return response;
} }
static Future<List<DeviceModel>> getDevicesByRoomId(int roomId) async { static Future<List<DeviceModel>> getDevicesByRoomId(String roomId) async {
// print("Room ID: $roomId");
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.devicesByRoom, path: ApiEndpoints.deviceByRoom,
queryParameters: {"roomId": roomId, "pageSize": 10}, queryParameters: {"roomUuid": roomId},
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
if (json == null || json.isEmpty || json == []) {
print('json: $json');
return <DeviceModel>[];
}
print('json: $json');
List<DeviceModel> devices = []; List<DeviceModel> devices = [];
for (var device in json['devices']) { for (var device in json) {
devices.add(DeviceModel.fromJson(device)); devices.add(DeviceModel.fromJson(device));
} }
return devices; return devices;

View File

@ -8,29 +8,25 @@ import 'package:syncrow_app/services/api/http_service.dart';
class SpacesAPI { class SpacesAPI {
static final HTTPService _httpService = HTTPService(); static final HTTPService _httpService = HTTPService();
static Future<List<SpaceModel>> getSpaces() async { static Future<List<SpaceModel>> getUnitsByUserId() async {
var uuid = var uuid =
await const FlutterSecureStorage().read(key: UserModel.userUuidKey); await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.spaces, path: "${ApiEndpoints.unitUser}$uuid",
queryParameters: {
"userUuid": uuid,
},
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) => SpaceModel.fromJsonList(json), expectedResponseModel: (json) => SpaceModel.fromJsonList(json),
); );
return response; return response;
} }
//get rooms by space id static Future<List<RoomModel>> getRoomsBySpaceId(String unitId) async {
static Future<List<RoomModel>> getRoomsBySpaceId(int spaceId) async {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.rooms, path: "${ApiEndpoints.unitChild}$unitId",
queryParameters: {"homeId": spaceId}, queryParameters: {"page": 1, "pageSize": 10},
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<RoomModel> rooms = []; List<RoomModel> rooms = [];
for (var room in json) { for (var room in json['children']) {
rooms.add(RoomModel.fromJson(room)); rooms.add(RoomModel.fromJson(room));
} }
return rooms; return rooms;

View File

@ -19,6 +19,16 @@ abstract class Constants {
static const String token = ''; static const String token = '';
} }
enum SpaceType { Unit, Building, Floor, Room, Community }
Map<String, SpaceType> spaceTypesMap = {
"unit": SpaceType.Unit,
"building": SpaceType.Building,
"floor": SpaceType.Floor,
"room": SpaceType.Room,
"community": SpaceType.Community,
};
enum DeviceType { enum DeviceType {
AC, AC,
LightBulb, LightBulb,
@ -32,26 +42,10 @@ enum DeviceType {
Other, Other,
} }
// Map<String, DeviceType> devicesTypesMap = {
// "AC": DeviceType.AC,
// "LB": DeviceType.LightBulb,
// "DL": DeviceType.DoorLock,
// "WC": DeviceType.Curtain,
// "WB": DeviceType.Blind,
// "3G": DeviceType.ThreeGang,
// "GW": DeviceType.Gateway,
// "CPS": DeviceType.CeilingSensor,
// "WPS": DeviceType.WallSensor,
// "Other": DeviceType.Other,
// };
//AC wzdcrqh0
// GW wp8ticoo2bhumwgb
// CPS d3ci7gcn
// DL awu7anehyu5q1iu8
// WPS awarhusb
// 3G 1a6vgvyi
enum FunctionType { Boolean, Enum, Integer, Raw, String } enum FunctionType { Boolean, Enum, Integer, Raw, String }
enum ValueACRange { LOW, MIDDLE, HIGH, AUTO }
Map<String, FunctionType> functionTypesMap = { Map<String, FunctionType> functionTypesMap = {
"Boolean": FunctionType.Boolean, "Boolean": FunctionType.Boolean,
"Enum": FunctionType.Enum, "Enum": FunctionType.Enum,
@ -60,12 +54,12 @@ Map<String, FunctionType> functionTypesMap = {
"String": FunctionType.String, "String": FunctionType.String,
}; };
Map<String, DeviceType> devicesTypesMap = { Map<String, DeviceType> devicesTypesMap = {
"wzdcrqh0": DeviceType.AC, "AC": DeviceType.AC,
"wp8ticoo2bhumwgb": DeviceType.Gateway, "GW": DeviceType.Gateway,
"d3ci7gcn": DeviceType.CeilingSensor, "CPS": DeviceType.CeilingSensor,
"awu7anehyu5q1iu8": DeviceType.DoorLock, "DL": DeviceType.DoorLock,
"awarhusb": DeviceType.WallSensor, "WPS": DeviceType.WallSensor,
"1a6vgvyi": DeviceType.ThreeGang, "3G": DeviceType.ThreeGang,
}; };
Map<DeviceType, List<FunctionModel>> devicesFunctionsMap = { Map<DeviceType, List<FunctionModel>> devicesFunctionsMap = {
DeviceType.AC: [ DeviceType.AC: [
@ -77,18 +71,22 @@ Map<DeviceType, List<FunctionModel>> devicesFunctionsMap = {
code: 'mode', code: 'mode',
type: functionTypesMap['Enum'], type: functionTypesMap['Enum'],
values: ValueModel.fromJson({ values: ValueModel.fromJson({
"range": ["cold", "hot", "wind"] // "range": ["cold", "hot", "wind"]
})), })),
FunctionModel( FunctionModel(
code: 'temp_set', code: 'temp_set',
type: functionTypesMap['Integer'], type: functionTypesMap['Integer'],
values: ValueModel.fromJson( values: ValueModel.fromJson(
{"unit": "", "min": 200, "max": 300, "scale": 1, "step": 5})), {
// "unit": {"min": 200, "max": 300, "scale": 1, "step": 5},
},
),
),
FunctionModel( FunctionModel(
code: 'level', code: 'level',
type: functionTypesMap['Enum'], type: functionTypesMap['Enum'],
values: ValueModel.fromJson({ values: ValueModel.fromJson({
"range": ["low", "middle", "high", "auto"] // "range": ["low", "middle", "high", "auto"]
})), })),
FunctionModel( FunctionModel(
code: 'child_lock', code: 'child_lock',