Compare commits

..

46 Commits

Author SHA1 Message Date
976d6e385a duplicated space 2025-04-27 11:12:03 +04:00
ff07e7509d fixed the issue in aligning child space 2025-04-26 16:04:41 +04:00
17a582ab99 Merge pull request #157 from SyncrowIOT/SP-1415 2025-04-25 10:50:06 +04:00
09fb604acc added filtering 2025-04-25 10:49:25 +04:00
2068df173d Merge pull request #155 from SyncrowIOT/SP-1441-rework-FE-On-routine-creation-page-When-the-user-drags-a-card-that-has-signs-and-selects-a-sign-without-a-number-then-confirms-the-value-appears-to-be-Null
Sp 1441 rework fe on routine creation page when the user drags a card that has signs and selects a sign without a number then confirms the value appears to be null
2025-04-24 16:25:39 +03:00
bfc2a381d2 Merge pull request #156 from SyncrowIOT/SP-1464-FE-implement-Batch-Control-Dialog
Sp 1464 fe implement batch control dialog
2025-04-24 16:25:17 +03:00
778257644d reduced debounce duration. 2025-04-24 15:13:10 +03:00
c8e540e938 Remove unnecessary event dispatch in FlushMountedPresenceSensorBlocFactory creation 2025-04-24 14:29:18 +03:00
ba20998067 disabled realtime on batch control. 2025-04-24 14:21:38 +03:00
75b0b24543 Add Flush Mounted Presence Sensor support and update event handling 2025-04-24 14:13:13 +03:00
c03b8f290c refactor function tap handlers to use RoutineTapFunctionHelper for improved code reuse and readability, and to remove code duplication. 2025-04-24 10:25:41 +03:00
2c684a9495 SP-1441 rework. 2025-04-23 16:58:50 +03:00
fbc45b465f Merge pull request #153 from SyncrowIOT/SP-1344-FE-Real-Time-Issues-Ceiling-Sensor-AC-and-Garage-Door-Sensor
Refactor widget lifecycle methods for temperature control and presenc…
2025-04-23 16:29:36 +03:00
c9c939c59f Merge pull request #154 from SyncrowIOT/Add-Flush-Mounted-Presence-Sensor-Single-Control
Add flush mounted presence sensor single control
2025-04-23 16:21:17 +03:00
e1a2465130 Fix deviceId assignment in FlushMountedPresenceSensorBlocFactory and update _listenToChanges method for async handling 2025-04-23 13:11:25 +03:00
86164e746a Refactor FlushMountedPresenceSensorBloc creation to use factory method and streamline dependency injection 2025-04-23 12:15:50 +03:00
4a5176cf22 Refactor presence update data handling for improved precision and scaling 2025-04-23 12:11:13 +03:00
2bb7a6950a Refactor debounce duration handling in BatchControlDevicesService and ControlDeviceService 2025-04-23 10:52:08 +03:00
46860619a0 Add bloc dependency to pubspec.yaml 2025-04-23 10:48:24 +03:00
d1bb7b129f Refactor widget lifecycle methods for temperature control and presence sensor 2025-04-23 10:46:56 +03:00
7adce3b94c Refactor _onFlushMountedPresenceSensorFetchBatchStatusEvent to use final for response variable 2025-04-23 10:44:44 +03:00
91f93d4395 Refactor FlushMountedPresenceSensorBloc to streamline device control logic and remove redundant code 2025-04-23 10:44:11 +03:00
42d6b64e58 Refactor FlushMountedPresenceSensorBloc to replace _runDeBouncer with _controlDevice for handling device control logic 2025-04-23 10:32:49 +03:00
b11d4186fb Add BatchControlDevicesService integration to FlushMountedPresenceSensorBloc and ControlView 2025-04-23 10:31:26 +03:00
24130be665 organized instances in bloc. 2025-04-23 10:26:55 +03:00
8c960bd5f1 created BatchControlDevicesService interface. 2025-04-23 10:26:17 +03:00
fb8ccdf0a6 Add FlushMountedPresenceSensorControlView for managing presence sensor settings 2025-04-23 10:24:38 +03:00
1975a1b6f4 created FlushMountedPresenceSensorBloc, events, and states for device management. 2025-04-23 10:24:14 +03:00
367d6717e7 Refactor PresenceUpdateData widget to support decimal values. 2025-04-23 10:23:28 +03:00
8c637e40ff Created FlushMountedPresenceSensorModel model. 2025-04-23 10:23:00 +03:00
05b3180510 Created ControlDeviceService interface and its remote and debounced implementation. 2025-04-23 10:22:41 +03:00
177a4711fe Synced main_dev and main_staging with main.dart 2025-04-22 03:39:27 +03:00
d7a37c6519 Removed flavor from Flutter run and build commands 2025-04-22 03:01:43 +03:00
b901791079 Update Flutter run and build commands, and added main_staging file 2025-04-22 02:33:50 +03:00
5d16555748 Merge pull request #151 from SyncrowIOT/SP-1447-FE-Invalid-Time-Limit-24h-Exceeding-Backend-Max-of-12h
SP-1447.
2025-04-21 18:59:57 +03:00
bd15f30b8a Merge pull request #150 from SyncrowIOT/SP-1440-FE-On-routine-creation-edit-Page-When-saving-a-routine-the-confirmation-pop-up-is-not-identical-to-design
Sp 1440 fe on routine creation edit page when saving a routine the confirmation pop up is not identical to design
2025-04-21 18:59:37 +03:00
5f2684bdf4 Merge pull request #152 from SyncrowIOT/SP-702-WEB-Username-Caching-After-Logout-Requires-Screen-Refresh
Sp 702 web username caching after logout requires screen refresh
2025-04-21 18:58:57 +03:00
d8afb562eb SP-1447, set the limit of gangs countdown to be 12 hours instead of 24 hours. 2025-04-21 12:07:21 +03:00
67a164e6d2 modified divider color to match figma design. 2025-04-21 10:59:09 +03:00
cf20bdcd42 SP-1440 2025-04-21 10:57:46 +03:00
84264391d9 progress towards matching the design of save routine dialog. 2025-04-17 16:14:26 +03:00
2e4f904d3a style: improve code formatting and readability in SaveRoutineHelper 2025-04-17 14:39:33 +03:00
c46cfb48a8 refactor: extract IF and THEN sections into separate methods for better readability 2025-04-17 14:38:04 +03:00
a0dd128557 matched design of Function and action in SaveRoutineHelper.showSaveRoutineDialog 2025-04-17 14:30:30 +03:00
34fa426163 submitting password field in login logs the user in. 2025-04-17 14:17:43 +03:00
1407c173b0 tapping bugfix. 2025-04-17 13:28:00 +03:00
38 changed files with 1978 additions and 482 deletions

View File

@ -31,7 +31,7 @@ jobs:
run: flutter pub get run: flutter pub get
- name: Build Flutter Web App - name: Build Flutter Web App
run: flutter build web --release --dart-define=FLAVOR=production run: flutter build web --web-renderer canvaskit -t lib/main.dart
- name: Build And Deploy - name: Build And Deploy
id: builddeploy id: builddeploy

View File

@ -31,7 +31,7 @@ jobs:
run: flutter pub get run: flutter pub get
- name: Build Flutter Web App - name: Build Flutter Web App
run: flutter build web --release --dart-define=FLAVOR=development run: flutter build web --web-renderer canvaskit -t lib/main_dev.dart
- name: Build And Deploy - name: Build And Deploy
id: builddeploy id: builddeploy

33
.vscode/launch.json vendored
View File

@ -10,11 +10,12 @@
"type": "dart", "type": "dart",
"args": [ "args": [
"-d",
"--dart-define", "chrome",
"--web-port",
"FLAVOR=development" "3000",
"-t",
"lib/main_dev.dart",
], ],
"flutterMode": "debug" "flutterMode": "debug"
@ -28,11 +29,12 @@
"type": "dart", "type": "dart",
"args": [ "args": [
"-d",
"--dart-define", "chrome",
"--web-port",
"FLAVOR=staging" "3000",
"-t",
"lib/main_staging.dart",
], ],
"flutterMode": "debug" "flutterMode": "debug"
@ -46,11 +48,12 @@
"type": "dart", "type": "dart",
"args": [ "args": [
"-d",
"--dart-define", "chrome",
"--web-port",
"FLAVOR=production" "3000",
"-t",
"lib/main.dart",
], ],
"flutterMode": "debug" "flutterMode": "debug"

View File

@ -16,7 +16,12 @@ samples, guidance on mobile development, and a full API reference.
## USEFUL COMMANDS ## USEFUL COMMANDS
Run on chrome: flutter run -d chrome --dart-define=FLAVOR='ENV_NAME' - Building for the Web
- CanvasKit
- `flutter build web --web-renderer canvaskit -t lib/main_dev.dart --output=build/web_dev` - build for DEVELOPMENT.
- `flutter build web --web-renderer canvaskit -t lib/main_staging.dart --output=build/web_stg` - build for STAGING.
- `flutter build web --web-renderer canvaskit -t lib/main.dart --output=build/web` - build for PRODUCTION.
- run command: `flutter run -d chrome --target=lib/main_dev.dart`
Build: flutter build web --release --dart-define=FLAVOR='ENV_NAME'

View File

@ -16,12 +16,12 @@ import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.da
import 'package:syncrow_web/services/locator.dart'; import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.dart'; import 'package:syncrow_web/utils/app_routes.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/navigation_service.dart';
import 'package:syncrow_web/utils/theme/theme.dart'; import 'package:syncrow_web/utils/theme/theme.dart';
Future<void> main() async { Future<void> main() async {
try { try {
const environment = const environment = String.fromEnvironment('FLAVOR', defaultValue: 'development');
String.fromEnvironment('FLAVOR', defaultValue: 'development');
await dotenv.load(fileName: '.env.$environment'); await dotenv.load(fileName: '.env.$environment');
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp( await Firebase.initializeApp(
@ -33,9 +33,7 @@ Future<void> main() async {
} }
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
MyApp({ MyApp({super.key});
super.key,
});
final GoRouter _router = GoRouter( final GoRouter _router = GoRouter(
initialLocation: RoutesConst.auth, initialLocation: RoutesConst.auth,
@ -59,8 +57,7 @@ class MyApp extends StatelessWidget {
BlocProvider<CreateRoutineBloc>( BlocProvider<CreateRoutineBloc>(
create: (context) => CreateRoutineBloc(), create: (context) => CreateRoutineBloc(),
), ),
BlocProvider( BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())),
create: (context) => HomeBloc()..add(const FetchUserInfo())),
BlocProvider<VisitorPasswordBloc>( BlocProvider<VisitorPasswordBloc>(
create: (context) => VisitorPasswordBloc(), create: (context) => VisitorPasswordBloc(),
), ),
@ -81,6 +78,8 @@ class MyApp extends StatelessWidget {
PointerDeviceKind.unknown, PointerDeviceKind.unknown,
}, },
), ),
key: NavigationService.navigatorKey,
// scaffoldMessengerKey: NavigationService.snackbarKey,
theme: myTheme, theme: myTheme,
routerConfig: _router, routerConfig: _router,
)); ));

87
lib/main_staging.dart Normal file
View File

@ -0,0 +1,87 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/firebase_options_prod.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_event.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/navigation_service.dart';
import 'package:syncrow_web/utils/theme/theme.dart';
Future<void> main() async {
try {
const environment = String.fromEnvironment('FLAVOR', defaultValue: 'staging');
await dotenv.load(fileName: '.env.$environment');
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptionsStaging.currentPlatform,
);
initialSetup();
} catch (_) {}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
final GoRouter _router = GoRouter(
initialLocation: RoutesConst.auth,
routes: AppRoutes.getRoutes(),
redirect: (context, state) async {
String checkToken = await AuthBloc.getTokenAndValidate();
final loggedIn = checkToken == 'Success';
final goingToLogin = state.uri.toString() == RoutesConst.auth;
if (!loggedIn && !goingToLogin) return RoutesConst.auth;
if (loggedIn && goingToLogin) return RoutesConst.home;
return null;
},
);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<CreateRoutineBloc>(
create: (context) => CreateRoutineBloc(),
),
BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())),
BlocProvider<VisitorPasswordBloc>(
create: (context) => VisitorPasswordBloc(),
),
BlocProvider<RoutineBloc>(
create: (context) => RoutineBloc(),
),
BlocProvider<SpaceTreeBloc>(
create: (context) => SpaceTreeBloc()..add(InitialEvent()),
),
],
child: MaterialApp.router(
debugShowCheckedModeBanner: false,
scrollBehavior: const MaterialScrollBehavior().copyWith(
dragDevices: {
PointerDeviceKind.mouse,
PointerDeviceKind.touch,
PointerDeviceKind.stylus,
PointerDeviceKind.unknown,
},
),
key: NavigationService.navigatorKey,
// scaffoldMessengerKey: NavigationService.snackbarKey,
theme: myTheme,
routerConfig: _router,
));
}
}

View File

@ -55,12 +55,12 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
final isSmallScreen = isSmallScreenSize(context); final isSmallScreen = isSmallScreenSize(context);
final isMediumScreen = isMediumScreenSize(context); final isMediumScreen = isMediumScreenSize(context);
Size size = MediaQuery.of(context).size; Size size = MediaQuery.of(context).size;
late ScrollController _scrollController; late ScrollController scrollController;
_scrollController = ScrollController(); scrollController = ScrollController();
void _scrollToCenter() { void scrollToCenter() {
final double middlePosition = _scrollController.position.maxScrollExtent / 2; final double middlePosition = scrollController.position.maxScrollExtent / 2;
_scrollController.animateTo( scrollController.animateTo(
middlePosition, middlePosition,
duration: const Duration(seconds: 1), duration: const Duration(seconds: 1),
curve: Curves.easeInOut, curve: Curves.easeInOut,
@ -68,7 +68,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
} }
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToCenter(); scrollToCenter();
}); });
return Stack( return Stack(
@ -76,7 +76,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
FirstLayer( FirstLayer(
second: Center( second: Center(
child: ListView( child: ListView(
controller: _scrollController, controller: scrollController,
shrinkWrap: true, shrinkWrap: true,
children: [ children: [
Container( Container(
@ -199,7 +199,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
width: size.width * 0.9, width: size.width * 0.9,
child: DropdownButtonHideUnderline( child: DropdownButtonHideUnderline(
child: DropdownButton2<String>( child: DropdownButton2<String>(
style: TextStyle(color: Colors.black), style: const TextStyle(color: Colors.black),
isExpanded: true, isExpanded: true,
hint: Text( hint: Text(
'Select your region/country', 'Select your region/country',
@ -336,6 +336,16 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
obscureText: loginBloc.obscureText, obscureText: loginBloc.obscureText,
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
controller: loginBloc.loginPasswordController, controller: loginBloc.loginPasswordController,
onFieldSubmitted: (value) {
if (loginBloc.loginFormKey.currentState!.validate()) {
loginBloc.add(LoginButtonPressed(
username: loginBloc.loginEmailController.text,
password: value,
));
} else {
loginBloc.add(ChangeValidateEvent());
}
},
decoration: textBoxDecoration()!.copyWith( decoration: textBoxDecoration()!.copyWith(
hintText: 'At least 8 characters', hintText: 'At least 8 characters',
hintStyle: Theme.of(context) hintStyle: Theme.of(context)
@ -393,7 +403,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
Transform.scale( Transform.scale(
scale: 1.2, scale: 1.2,
child: Checkbox( child: Checkbox(
fillColor: MaterialStateProperty.all<Color>(Colors.white), fillColor: WidgetStateProperty.all<Color>(Colors.white),
activeColor: Colors.white, activeColor: Colors.white,
value: loginBloc.isChecked, value: loginBloc.isChecked,
checkColor: Colors.black, checkColor: Colors.black,

View File

@ -60,7 +60,15 @@ class _CurrentTempState extends State<CurrentTemp> {
); );
}); });
} }
@override
void didUpdateWidget(CurrentTemp oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.tempSet != widget.tempSet) {
setState(() {
_adjustedValue = _initialAdjustedValue(widget.tempSet);
});
}
}
@override @override
void dispose() { void dispose() {
_debounce?.cancel(); _debounce?.cancel();

View File

@ -9,6 +9,8 @@ import 'package:syncrow_web/pages/device_managment/curtain/view/curtain_batch_st
import 'package:syncrow_web/pages/device_managment/curtain/view/curtain_status_view.dart'; import 'package:syncrow_web/pages/device_managment/curtain/view/curtain_status_view.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart'; import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_control_view.dart'; import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_control_view.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_control_view.dart'; import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_control_view.dart';
import 'package:syncrow_web/pages/device_managment/gateway/view/gateway_batch_control.dart'; import 'package:syncrow_web/pages/device_managment/gateway/view/gateway_batch_control.dart';
@ -104,6 +106,9 @@ mixin RouteControlsBasedCode {
); );
case 'SOS': case 'SOS':
return SosDeviceControlsView(device: device); return SosDeviceControlsView(device: device);
case 'NCPS':
return FlushMountedPresenceSensorControlView(device: device);
default: default:
return const SizedBox(); return const SizedBox();
} }
@ -194,6 +199,10 @@ mixin RouteControlsBasedCode {
return SOSBatchControlView( return SOSBatchControlView(
deviceIds: devices.where((e) => (e.productType == 'SOS')).map((e) => e.uuid!).toList(), deviceIds: devices.where((e) => (e.productType == 'SOS')).map((e) => e.uuid!).toList(),
); );
case 'NCPS':
return FlushMountedPresenceSensorBatchControlView(
devicesIds: devices.where((e) => (e.productType == 'NCPS')).map((e) => e.uuid!).toList(),
);
default: default:
return const SizedBox(); return const SizedBox();
} }

View File

@ -16,7 +16,8 @@ import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dar
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart'; import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLayout { class CeilingSensorControlsView extends StatelessWidget
with HelperResponsiveLayout {
const CeilingSensorControlsView({super.key, required this.device}); const CeilingSensorControlsView({super.key, required this.device});
final AllDevicesModel device; final AllDevicesModel device;
@ -31,29 +32,35 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
..add(CeilingInitialEvent(device.uuid ?? '')), ..add(CeilingInitialEvent(device.uuid ?? '')),
child: BlocBuilder<CeilingSensorBloc, CeilingSensorState>( child: BlocBuilder<CeilingSensorBloc, CeilingSensorState>(
builder: (context, state) { builder: (context, state) {
if (state is CeilingLoadingInitialState || state is CeilingReportsLoadingState) { if (state is CeilingLoadingInitialState ||
state is CeilingReportsLoadingState) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} else if (state is CeilingUpdateState) { } else if (state is CeilingUpdateState) {
return _buildGridView( return _buildGridView(context, state.ceilingSensorModel,
context, state.ceilingSensorModel, isExtraLarge, isLarge, isMedium); isExtraLarge, isLarge, isMedium);
} else if (state is CeilingReportsState) { } else if (state is CeilingReportsState) {
return ReportsTable( return ReportsTable(
report: state.deviceReport, report: state.deviceReport,
onRowTap: (index) {}, onRowTap: (index) {},
onClose: () { onClose: () {
context.read<CeilingSensorBloc>().add(BackToCeilingGridViewEvent()); context
.read<CeilingSensorBloc>()
.add(BackToCeilingGridViewEvent());
}, },
); );
} else if (state is ShowCeilingDescriptionState) { } else if (state is ShowCeilingDescriptionState) {
return DescriptionView( return DescriptionView(
description: state.description, description: state.description,
onClose: () { onClose: () {
context.read<CeilingSensorBloc>().add(BackToCeilingGridViewEvent()); context
.read<CeilingSensorBloc>()
.add(BackToCeilingGridViewEvent());
}, },
); );
} else if (state is CeilingReportsFailedState) { } else if (state is CeilingReportsFailedState) {
final model = context.read<CeilingSensorBloc>().deviceStatus; final model = context.read<CeilingSensorBloc>().deviceStatus;
return _buildGridView(context, model, isExtraLarge, isLarge, isMedium); return _buildGridView(
context, model, isExtraLarge, isLarge, isMedium);
} }
return const Center(child: Text('Error fetching status')); return const Center(child: Text('Error fetching status'));
}, },
@ -61,8 +68,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
); );
} }
Widget _buildGridView(BuildContext context, CeilingSensorModel model, bool isExtraLarge, Widget _buildGridView(BuildContext context, CeilingSensorModel model,
bool isLarge, bool isMedium) { bool isExtraLarge, bool isLarge, bool isMedium) {
return GridView( return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50), padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true, shrinkWrap: true,
@ -143,8 +150,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
), ),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
context.read<CeilingSensorBloc>().add( context.read<CeilingSensorBloc>().add(GetCeilingDeviceReportsEvent(
GetCeilingDeviceReportsEvent(code: 'presence_state', deviceUuid: device.uuid!)); code: 'presence_state', deviceUuid: device.uuid!));
}, },
child: const PresenceStaticWidget( child: const PresenceStaticWidget(
icon: Assets.illuminanceRecordIcon, icon: Assets.illuminanceRecordIcon,
@ -153,9 +160,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
), ),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
context context.read<CeilingSensorBloc>().add(GetCeilingDeviceReportsEvent(
.read<CeilingSensorBloc>() code: '', deviceUuid: device.uuid!));
.add(GetCeilingDeviceReportsEvent(code: '', deviceUuid: device.uuid!));
}, },
child: const PresenceStaticWidget( child: const PresenceStaticWidget(
icon: Assets.helpDescriptionIcon, icon: Assets.helpDescriptionIcon,

View File

@ -0,0 +1,250 @@
import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/services/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';
part 'flush_mounted_presence_sensor_event.dart';
part 'flush_mounted_presence_sensor_state.dart';
class FlushMountedPresenceSensorBloc
extends Bloc<FlushMountedPresenceSensorEvent, FlushMountedPresenceSensorState> {
final String deviceId;
final ControlDeviceService controlDeviceService;
final BatchControlDevicesService batchControlDevicesService;
late FlushMountedPresenceSensorModel deviceStatus;
FlushMountedPresenceSensorBloc({
required this.deviceId,
required this.controlDeviceService,
required this.batchControlDevicesService,
}) : super(FlushMountedPresenceSensorInitialState()) {
on<FlushMountedPresenceSensorFetchStatusEvent>(
_onFlushMountedPresenceSensorFetchStatusEvent,
);
on<FlushMountedPresenceSensorFetchBatchStatusEvent>(
_onFlushMountedPresenceSensorFetchBatchStatusEvent);
on<FlushMountedPresenceSensorChangeValueEvent>(
_onFlushMountedPresenceSensorChangeValueEvent,
);
on<FlushMountedPresenceSensorBatchControlEvent>(
_onFlushMountedPresenceSensorBatchControlEvent,
);
on<FlushMountedPresenceSensorGetDeviceReportsEvent>(
_onFlushMountedPresenceSensorGetDeviceReportsEvent);
on<FlushMountedPresenceSensorShowDescriptionEvent>(
_onFlushMountedPresenceSensorShowDescriptionEvent,
);
on<FlushMountedPresenceSensorBackToGridViewEvent>(
_onFlushMountedPresenceSensorBackToGridViewEvent,
);
on<FlushMountedPresenceSensorFactoryResetEvent>(
_onFlushMountedPresenceSensorFactoryResetEvent,
);
on<FlushMountedPresenceSensorStatusUpdatedEvent>(
_onFlushMountedPresenceSensorStatusUpdatedEvent,
);
}
void _onFlushMountedPresenceSensorFetchStatusEvent(
FlushMountedPresenceSensorFetchStatusEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingInitialState());
try {
final response = await DevicesManagementApi().getDeviceStatus(deviceId);
deviceStatus = FlushMountedPresenceSensorModel.fromJson(response.status);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
_listenToChanges(deviceId);
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
return;
}
}
Future<void> _onFlushMountedPresenceSensorFetchBatchStatusEvent(
FlushMountedPresenceSensorFetchBatchStatusEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingInitialState());
try {
final response = await DevicesManagementApi().getBatchStatus(event.devicesIds);
deviceStatus = FlushMountedPresenceSensorModel.fromJson(response.status);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
}
}
void _listenToChanges(String deviceId) {
try {
final ref = FirebaseDatabase.instance.ref(
'device-status/$deviceId',
);
ref.onValue.listen((event) {
final eventsMap = event.snapshot.value as Map<dynamic, dynamic>;
List<Status> statusList = [];
eventsMap['status'].forEach((element) {
statusList.add(
Status(code: element['code'], value: element['value']),
);
});
deviceStatus = FlushMountedPresenceSensorModel.fromJson(statusList);
if (!isClosed) {
add(FlushMountedPresenceSensorStatusUpdatedEvent(deviceStatus));
}
});
} catch (_) {
log(
'Error listening to changes',
name: 'FlushMountedPresenceSensorBloc._listenToChanges',
);
}
}
void _onFlushMountedPresenceSensorChangeValueEvent(
FlushMountedPresenceSensorChangeValueEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
_updateDeviceFunctionFromCode(event.code, event.value);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
try {
await controlDeviceService.controlDevice(
deviceUuid: deviceId,
status: Status(code: event.code, value: event.value),
);
} catch (_) {
await _reloadDeviceStatus();
}
}
Future<void> _onFlushMountedPresenceSensorBatchControlEvent(
FlushMountedPresenceSensorBatchControlEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
_updateDeviceFunctionFromCode(event.code, event.value);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
try {
await batchControlDevicesService.batchControlDevices(
uuids: event.deviceIds,
code: event.code,
value: event.value,
);
} catch (_) {
await _reloadDeviceStatus();
}
}
void _updateDeviceFunctionFromCode(String code, int value) {
switch (code) {
case FlushMountedPresenceSensorModel.codeFarDetection:
deviceStatus.farDetection = value;
break;
case FlushMountedPresenceSensorModel.codeSensitivity:
deviceStatus.sensitivity = value;
break;
case FlushMountedPresenceSensorModel.codeNoneDelay:
deviceStatus.noneDelay = value;
break;
case FlushMountedPresenceSensorModel.codePresenceDelay:
deviceStatus.presenceDelay = value;
break;
case FlushMountedPresenceSensorModel.codeNearDetection:
deviceStatus.nearDetection = value;
break;
case FlushMountedPresenceSensorModel.codeOccurDistReduce:
deviceStatus.occurDistReduce = value;
break;
case FlushMountedPresenceSensorModel.codeSensiReduce:
deviceStatus.sensiReduce = value;
break;
default:
return;
}
}
Future<void> _reloadDeviceStatus() async {
await Future.delayed(const Duration(milliseconds: 500), () {
add(FlushMountedPresenceSensorFetchStatusEvent());
});
}
Future<void> _onFlushMountedPresenceSensorGetDeviceReportsEvent(
FlushMountedPresenceSensorGetDeviceReportsEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorDeviceReportsLoadingState());
try {
await DevicesManagementApi.getDeviceReports(deviceId, event.code)
.then((value) {
emit(FlushMountedPresenceSensorDeviceReportsState(
deviceReport: value, code: event.code));
});
} catch (e) {
emit(FlushMountedPresenceSensorDeviceReportsFailedState(error: e.toString()));
return;
}
}
void _onFlushMountedPresenceSensorShowDescriptionEvent(
FlushMountedPresenceSensorShowDescriptionEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
emit(FlushMountedPresenceSensorShowDescriptionState(
description: event.description));
}
void _onFlushMountedPresenceSensorBackToGridViewEvent(
FlushMountedPresenceSensorBackToGridViewEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
Future<void> _onFlushMountedPresenceSensorFactoryResetEvent(
FlushMountedPresenceSensorFactoryResetEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
try {
final response = await DevicesManagementApi().factoryReset(
event.factoryReset,
event.deviceId,
);
if (!response) {
emit(
const FlushMountedPresenceSensorFailedState(
error: 'Something went wrong with factory reset, please try again',
),
);
} else {
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
}
}
void _onFlushMountedPresenceSensorStatusUpdatedEvent(
FlushMountedPresenceSensorStatusUpdatedEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
deviceStatus = event.model;
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
}

View File

@ -0,0 +1,94 @@
part of 'flush_mounted_presence_sensor_bloc.dart';
sealed class FlushMountedPresenceSensorEvent extends Equatable {
const FlushMountedPresenceSensorEvent();
@override
List<Object> get props => [];
}
class FlushMountedPresenceSensorFetchStatusEvent
extends FlushMountedPresenceSensorEvent {}
class FlushMountedPresenceSensorStatusUpdatedEvent
extends FlushMountedPresenceSensorEvent {
const FlushMountedPresenceSensorStatusUpdatedEvent(this.model);
final FlushMountedPresenceSensorModel model;
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorChangeValueEvent
extends FlushMountedPresenceSensorEvent {
final int value;
final String code;
final bool isBatchControl;
const FlushMountedPresenceSensorChangeValueEvent({
required this.value,
required this.code,
this.isBatchControl = false,
});
@override
List<Object> get props => [value, code];
}
class FlushMountedPresenceSensorFetchBatchStatusEvent
extends FlushMountedPresenceSensorEvent {
final List<String> devicesIds;
const FlushMountedPresenceSensorFetchBatchStatusEvent(this.devicesIds);
@override
List<Object> get props => [devicesIds];
}
class FlushMountedPresenceSensorGetDeviceReportsEvent
extends FlushMountedPresenceSensorEvent {
final String deviceUuid;
final String code;
const FlushMountedPresenceSensorGetDeviceReportsEvent({
required this.deviceUuid,
required this.code,
});
@override
List<Object> get props => [deviceUuid, code];
}
class FlushMountedPresenceSensorShowDescriptionEvent
extends FlushMountedPresenceSensorEvent {
final String description;
const FlushMountedPresenceSensorShowDescriptionEvent({required this.description});
}
class FlushMountedPresenceSensorBackToGridViewEvent
extends FlushMountedPresenceSensorEvent {}
class FlushMountedPresenceSensorBatchControlEvent
extends FlushMountedPresenceSensorEvent {
final List<String> deviceIds;
final String code;
final dynamic value;
const FlushMountedPresenceSensorBatchControlEvent({
required this.deviceIds,
required this.code,
required this.value,
});
@override
List<Object> get props => [deviceIds, code, value];
}
class FlushMountedPresenceSensorFactoryResetEvent
extends FlushMountedPresenceSensorEvent {
final String deviceId;
final FactoryResetModel factoryReset;
const FlushMountedPresenceSensorFactoryResetEvent({
required this.deviceId,
required this.factoryReset,
});
}

View File

@ -0,0 +1,76 @@
part of 'flush_mounted_presence_sensor_bloc.dart';
sealed class FlushMountedPresenceSensorState extends Equatable {
const FlushMountedPresenceSensorState();
@override
List<Object> get props => [];
}
class FlushMountedPresenceSensorInitialState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorLoadingInitialState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorUpdateState extends FlushMountedPresenceSensorState {
final FlushMountedPresenceSensorModel model;
const FlushMountedPresenceSensorUpdateState({required this.model});
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorLoadingNewSate
extends FlushMountedPresenceSensorState {
final FlushMountedPresenceSensorModel model;
const FlushMountedPresenceSensorLoadingNewSate({required this.model});
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorFailedState extends FlushMountedPresenceSensorState {
final String error;
const FlushMountedPresenceSensorFailedState({required this.error});
@override
List<Object> get props => [error];
}
class FlushMountedPresenceSensorDeviceReportsLoadingState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorDeviceReportsState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorDeviceReportsState({
required this.deviceReport,
required this.code,
});
final DeviceReport deviceReport;
final String code;
@override
List<Object> get props => [deviceReport, code];
}
class FlushMountedPresenceSensorDeviceReportsFailedState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorDeviceReportsFailedState({required this.error});
final String error;
@override
List<Object> get props => [error];
}
class FlushMountedPresenceSensorShowDescriptionState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorShowDescriptionState({required this.description});
final String description;
@override
List<Object> get props => [description];
}

View File

@ -0,0 +1,21 @@
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/services/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
abstract final class FlushMountedPresenceSensorBlocFactory {
const FlushMountedPresenceSensorBlocFactory._();
static FlushMountedPresenceSensorBloc create({
required String deviceId,
}) {
return FlushMountedPresenceSensorBloc(
deviceId: deviceId,
controlDeviceService: DebouncedControlDeviceService(
decoratee: RemoteControlDeviceService(),
),
batchControlDevicesService: DebouncedBatchControlDevicesService(
decoratee: RemoteBatchControlDevicesService(),
),
);
}
}

View File

@ -0,0 +1,99 @@
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
class FlushMountedPresenceSensorModel {
FlushMountedPresenceSensorModel({
required this.presenceState,
required this.farDetection,
required this.illuminance,
required this.sensitivity,
required this.occurDistReduce,
required this.noneDelay,
required this.presenceDelay,
required this.nearDetection,
required this.sensiReduce,
required this.checkingResult,
});
static const String codePresenceState = 'presence_state';
static const String codeSensitivity = 'sensitivity';
static const String codeNearDetection = 'near_detection';
static const String codeFarDetection = 'far_detection';
static const String codeCheckingResult = 'checking_result';
static const String codePresenceDelay = 'presence_delay';
static const String codeNoneDelay = 'none_delay';
static const String codeOccurDistReduce = 'occur_dist_reduce';
static const String codeIlluminance = 'illum_value';
static const String codeSensiReduce = 'sensi_reduce';
String presenceState;
int sensitivity;
int nearDetection;
int farDetection;
String checkingResult;
int presenceDelay;
int noneDelay;
int occurDistReduce;
int illuminance;
int sensiReduce;
factory FlushMountedPresenceSensorModel.fromJson(List<Status> jsonList) {
String presenceState = 'none';
int sensitivity = 0;
int nearDetection = 0;
int farDetection = 0;
String checkingResult = 'none';
int presenceDelay = 0;
int noneDelay = 0;
int occurDistReduce = 0;
int illuminance = 0;
int sensiReduce = 0;
for (var status in jsonList) {
switch (status.code) {
case codePresenceState:
presenceState = status.value ?? 'presence';
break;
case codeSensitivity:
sensitivity = status.value ?? 0;
break;
case codeNearDetection:
nearDetection = status.value ?? 0;
break;
case codeFarDetection:
farDetection = status.value ?? 0;
break;
case codeCheckingResult:
checkingResult = status.value ?? 'check_success';
break;
case codePresenceDelay:
presenceDelay = status.value ?? 0;
break;
case codeNoneDelay:
noneDelay = status.value ?? 0;
break;
case codeOccurDistReduce:
occurDistReduce = status.value ?? 0;
break;
case codeIlluminance:
illuminance = status.value ?? 0;
break;
case codeSensiReduce:
sensiReduce = status.value ?? 0;
break;
}
}
return FlushMountedPresenceSensorModel(
presenceState: presenceState,
sensitivity: sensitivity,
nearDetection: nearDetection,
farDetection: farDetection,
checkingResult: checkingResult,
presenceDelay: presenceDelay,
noneDelay: noneDelay,
occurDistReduce: occurDistReduce,
illuminance: illuminance,
sensiReduce: sensiReduce,
);
}
}

View File

@ -0,0 +1,183 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_reset.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class FlushMountedPresenceSensorBatchControlView extends StatelessWidget
with HelperResponsiveLayout {
const FlushMountedPresenceSensorBatchControlView({
required this.devicesIds,
super.key,
});
final List<String> devicesIds;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => FlushMountedPresenceSensorBlocFactory.create(
deviceId: devicesIds.first,
)..add(FlushMountedPresenceSensorFetchBatchStatusEvent(devicesIds)),
child: BlocBuilder<FlushMountedPresenceSensorBloc,
FlushMountedPresenceSensorState>(
builder: (context, state) {
if (state is FlushMountedPresenceSensorLoadingInitialState ||
state is FlushMountedPresenceSensorDeviceReportsLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FlushMountedPresenceSensorUpdateState) {
return _buildGridView(context, state.model);
}
return const Center(child: Text('Error fetching status'));
},
),
);
}
Widget _buildGridView(
BuildContext context,
FlushMountedPresenceSensorModel model,
) {
final isExtraLarge = isExtraLargeScreenSize(context);
final isLarge = isLargeScreenSize(context);
final isMedium = isMediumScreenSize(context);
return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: isLarge || isExtraLarge
? 3
: isMedium
? 2
: 1,
mainAxisExtent: 140,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
children: [
PresenceUpdateData(
value: model.sensitivity.toDouble(),
title: 'Sensitivity:',
minValue: 0,
maxValue: 9,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeSensitivity,
value: value,
),
),
),
PresenceUpdateData(
value: (model.nearDetection / 100).toDouble(),
title: 'Nearest Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeNearDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.farDetection / 100).toDouble(),
title: 'Max Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeFarDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: model.presenceDelay.toDouble(),
title: 'Trigger Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codePresenceDelay,
value: value,
),
),
),
PresenceUpdateData(
value: model.occurDistReduce.toDouble(),
title: 'Indent Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeOccurDistReduce,
value: value,
),
),
),
PresenceUpdateData(
value: (model.sensiReduce.toDouble()),
title: 'Target Confirm Time:',
description: 's',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeSensiReduce,
value: value,
),
),
),
PresenceUpdateData(
value: ((model.noneDelay / 10).toDouble()),
description: 's',
title: 'Disappe Delay:',
minValue: 20,
maxValue: 300,
steps: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeNoneDelay,
value: (value * 10).round(),
),
),
),
FactoryResetWidget(
callFactoryReset: () {
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorFactoryResetEvent(
deviceId: devicesIds.first,
factoryReset: FactoryResetModel(devicesUuid: devicesIds),
),
);
},
),
],
);
}
}

View File

@ -0,0 +1,217 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_display_data.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_status.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/description_view.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class FlushMountedPresenceSensorControlView extends StatelessWidget
with HelperResponsiveLayout {
const FlushMountedPresenceSensorControlView({super.key, required this.device});
final AllDevicesModel device;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => FlushMountedPresenceSensorBlocFactory.create(
deviceId: device.uuid ?? '-1',
)..add(FlushMountedPresenceSensorFetchStatusEvent()),
child: BlocBuilder<FlushMountedPresenceSensorBloc,
FlushMountedPresenceSensorState>(
builder: (context, state) {
if (state is FlushMountedPresenceSensorLoadingInitialState ||
state is FlushMountedPresenceSensorDeviceReportsLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FlushMountedPresenceSensorUpdateState) {
return _buildGridView(context, state.model);
} else if (state is FlushMountedPresenceSensorDeviceReportsState) {
return ReportsTable(
report: state.deviceReport,
thirdColumnTitle:
state.code == 'illuminance_value' ? "Value" : 'Status',
thirdColumnDescription:
state.code == 'illuminance_value' ? "Lux" : null,
onRowTap: (index) {},
onClose: () {
context
.read<FlushMountedPresenceSensorBloc>()
.add(FlushMountedPresenceSensorBackToGridViewEvent());
},
);
} else if (state is FlushMountedPresenceSensorShowDescriptionState) {
return DescriptionView(
description: state.description,
onClose: () {
context
.read<FlushMountedPresenceSensorBloc>()
.add(FlushMountedPresenceSensorBackToGridViewEvent());
},
);
} else if (state is FlushMountedPresenceSensorDeviceReportsFailedState) {
final model =
context.read<FlushMountedPresenceSensorBloc>().deviceStatus;
return _buildGridView(context, model);
}
return const Center(
child: Text('Error fetching status', textAlign: TextAlign.center),
);
},
),
);
}
Widget _buildGridView(
BuildContext context,
FlushMountedPresenceSensorModel model,
) {
final isExtraLarge = isExtraLargeScreenSize(context);
final isLarge = isLargeScreenSize(context);
final isMedium = isMediumScreenSize(context);
return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: isLarge || isExtraLarge
? 3
: isMedium
? 2
: 1,
mainAxisExtent: 140,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
children: [
PresenceState(
value: model.presenceState,
),
PresenceDisplayValue(
value: model.illuminance.toString(),
postfix: 'Lux',
description: 'Illuminance Value',
),
PresenceUpdateData(
value: model.sensitivity.toDouble(),
title: 'Sensitivity:',
minValue: 0,
maxValue: 9,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeSensitivity,
value: value,
),
),
),
PresenceUpdateData(
value: (model.nearDetection / 100).toDouble(),
title: 'Nearest Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeNearDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.farDetection / 100).toDouble(),
title: 'Max Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeFarDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.presenceDelay.toDouble()),
title: 'Trigger Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codePresenceDelay,
value: value,
),
),
),
PresenceUpdateData(
value: (model.occurDistReduce.toDouble()),
title: 'Indent Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeOccurDistReduce,
value: value,
),
),
),
PresenceUpdateData(
value: (model.sensiReduce.toDouble()),
title: 'Target Confirm Time:',
description: 's',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeSensiReduce,
value: value,
),
),
),
PresenceUpdateData(
value: ((model.noneDelay / 10).toDouble()),
description: 's',
title: 'Disappe Delay:',
minValue: 20,
maxValue: 300,
steps: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeNoneDelay,
value: (value * 10).round(),
),
),
),
GestureDetector(
onTap: () => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorGetDeviceReportsEvent(
code: 'presence_state',
deviceUuid: device.uuid!,
),
),
child: const PresenceStaticWidget(
icon: Assets.presenceRecordIcon,
description: 'Presence Record',
),
),
],
);
}
}

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart'; import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart';
import 'package:syncrow_web/pages/device_managment/shared/increament_decreament.dart'; import 'package:syncrow_web/pages/device_managment/shared/increament_decreament.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class PresenceUpdateData extends StatefulWidget { class PresenceUpdateData extends StatefulWidget {
const PresenceUpdateData({ const PresenceUpdateData({
@ -13,6 +14,7 @@ class PresenceUpdateData extends StatefulWidget {
required this.maxValue, required this.maxValue,
required this.steps, required this.steps,
this.description, this.description,
this.valuesPercision = 0,
}); });
final String title; final String title;
@ -22,6 +24,7 @@ class PresenceUpdateData extends StatefulWidget {
final double steps; final double steps;
final Function action; final Function action;
final String? description; final String? description;
final int valuesPercision;
@override @override
State<PresenceUpdateData> createState() => _CurrentTempState(); State<PresenceUpdateData> createState() => _CurrentTempState();
@ -45,7 +48,7 @@ class _CurrentTempState extends State<PresenceUpdateData> {
} }
void _onValueChanged(double newValue) { void _onValueChanged(double newValue) {
widget.action(newValue.toInt()); widget.action(newValue);
} }
@override @override
@ -62,11 +65,14 @@ class _CurrentTempState extends State<PresenceUpdateData> {
children: [ children: [
Text( Text(
widget.title, widget.title,
style: Theme.of(context).textTheme.bodySmall!.copyWith( style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 10), color: ColorsManager.blackColor,
fontWeight: FontWeight.w400,
fontSize: 10,
),
), ),
IncrementDecrementWidget( IncrementDecrementWidget(
value: widget.value.toString(), value: widget.value.toStringAsFixed(widget.valuesPercision),
description: widget.description ?? '', description: widget.description ?? '',
descriptionColor: ColorsManager.blackColor, descriptionColor: ColorsManager.blackColor,
onIncrement: () { onIncrement: () {

View File

@ -84,6 +84,16 @@ class _PresenceUpdateDataState extends State<PresenceNoBodyTime> {
} }
} }
@override
void didUpdateWidget(PresenceNoBodyTime oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.value != widget.value) {
setState(() {
_currentValue = widget.value;
});
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return DeviceControlsContainer( return DeviceControlsContainer(

View File

@ -21,6 +21,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
on<ShowDescriptionEvent>(_showDescription); on<ShowDescriptionEvent>(_showDescription);
on<BackToGridViewEvent>(_backToGridView); on<BackToGridViewEvent>(_backToGridView);
on<WallSensorFactoryResetEvent>(_onFactoryReset); on<WallSensorFactoryResetEvent>(_onFactoryReset);
on<WallSensorRealtimeUpdateEvent>(_onRealtimeUpdate);
} }
void _fetchWallSensorStatus( void _fetchWallSensorStatus(
@ -30,7 +31,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
var response = await DevicesManagementApi().getDeviceStatus(deviceId); var response = await DevicesManagementApi().getDeviceStatus(deviceId);
deviceStatus = WallSensorModel.fromJson(response.status); deviceStatus = WallSensorModel.fromJson(response.status);
emit(WallSensorUpdateState(wallSensorModel: deviceStatus)); emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
_listenToChanges(emit, deviceId); _listenToChanges(deviceId);
} catch (e) { } catch (e) {
emit(WallSensorFailedState(error: e.toString())); emit(WallSensorFailedState(error: e.toString()));
return; return;
@ -52,27 +53,26 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
} }
} }
_listenToChanges(Emitter<WallSensorState> emit, deviceId) { void _listenToChanges(String deviceId) {
try {
DatabaseReference ref = DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$deviceId'); FirebaseDatabase.instance.ref('device-status/$deviceId');
Stream<DatabaseEvent> stream = ref.onValue; ref.onValue.listen((DatabaseEvent event) {
final data = event.snapshot.value as Map<dynamic, dynamic>?;
if (data == null) return;
stream.listen((DatabaseEvent event) { final statusList = (data['status'] as List?)
Map<dynamic, dynamic> usersMap = ?.map((e) => Status(code: e['code'], value: e['value']))
event.snapshot.value as Map<dynamic, dynamic>; .toList();
List<Status> statusList = [];
usersMap['status'].forEach((element) { if (statusList != null) {
statusList final updatedDeviceStatus = WallSensorModel.fromJson(statusList);
.add(Status(code: element['code'], value: element['value'])); if (!isClosed) {
}); add(WallSensorRealtimeUpdateEvent(updatedDeviceStatus));
deviceStatus = WallSensorModel.fromJson(statusList);
emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
});
} catch (_) {}
} }
}
});
}
void _changeValue( void _changeValue(
WallSensorChangeValueEvent event, Emitter<WallSensorState> emit) async { WallSensorChangeValueEvent event, Emitter<WallSensorState> emit) async {
@ -195,4 +195,12 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
emit(WallSensorFailedState(error: e.toString())); emit(WallSensorFailedState(error: e.toString()));
} }
} }
void _onRealtimeUpdate(
WallSensorRealtimeUpdateEvent event,
Emitter<WallSensorState> emit,
) {
deviceStatus = event.deviceStatus;
emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
}
} }

View File

@ -1,5 +1,6 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart';
abstract class WallSensorEvent extends Equatable { abstract class WallSensorEvent extends Equatable {
const WallSensorEvent(); const WallSensorEvent();
@ -70,3 +71,8 @@ class WallSensorFactoryResetEvent extends WallSensorEvent {
required this.factoryReset, required this.factoryReset,
}); });
} }
class WallSensorRealtimeUpdateEvent extends WallSensorEvent {
final WallSensorModel deviceStatus;
const WallSensorRealtimeUpdateEvent(this.deviceStatus);
}

View File

@ -5,7 +5,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart'; import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart'; import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
@ -15,13 +14,18 @@ class SaveRoutineHelper {
static Future<void> showSaveRoutineDialog(BuildContext context) async { static Future<void> showSaveRoutineDialog(BuildContext context) async {
return showDialog<void>( return showDialog<void>(
context: context, context: context,
builder: (BuildContext context) { builder: (context) {
return BlocBuilder<RoutineBloc, RoutineState>( return BlocBuilder<RoutineBloc, RoutineState>(
builder: (context, state) { builder: (context, state) {
final selectedConditionLabel = state.selectedAutomationOperator == 'and'
? 'All Conditions are met'
: 'Any Condition is met';
return AlertDialog( return AlertDialog(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
content: Container( content: Container(
width: MediaQuery.sizeOf(context).width * 0.5, width: context.screenWidth * 0.5,
height: 500,
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20),
@ -29,25 +33,128 @@ class SaveRoutineHelper {
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
DialogHeader('Create a scene: ${state.routineName ?? ""}'), const SizedBox(height: 18),
Padding( Text(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), 'Create a scene: ${state.routineName ?? ""}',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 18),
_buildDivider(),
_buildListsLabelRow(selectedConditionLabel),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.symmetric(
horizontal: 16,
),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 24,
children: [ children: [
// Left side - IF _buildIfConditions(state, context),
Expanded( Container(
child: ListView( width: 1,
// crossAxisAlignment: CrossAxisAlignment.start, color: ColorsManager.greyColor.withValues(alpha: 0.8),
shrinkWrap: true, ),
children: [ _buildThenActions(state, context),
const Text( ],
'IF:',
style: TextStyle(
fontSize: 16,
), ),
), ),
),
_buildDivider(),
const SizedBox(height: 8), const SizedBox(height: 8),
_buildDialogFooter(context, state),
const SizedBox(height: 8),
],
),
),
);
},
);
},
);
}
static Container _buildDivider() {
return Container(
height: 1,
width: double.infinity,
color: ColorsManager.greyColor,
);
}
static Widget _buildListsLabelRow(String selectedConditionLabel) {
const textStyle = TextStyle(
fontSize: 16,
);
return Container(
color: ColorsManager.backgroundColor.withValues(alpha: 0.5),
padding: const EdgeInsetsDirectional.all(20),
child: Row(
spacing: 16,
children: [
Expanded(child: Text('IF: $selectedConditionLabel', style: textStyle)),
const Expanded(child: Text('THEN:', style: textStyle)),
],
),
);
}
static Widget _buildDialogFooter(BuildContext context, RoutineState state) {
return Row(
spacing: 16,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DialogFooterButton(
text: 'Cancel',
onTap: () => Navigator.pop(context),
),
DialogFooterButton(
text: 'Confirm',
onTap: () {
if (state.isAutomation) {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateAutomation());
} else {
context.read<RoutineBloc>().add(const CreateAutomationEvent());
}
} else {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateScene());
} else {
context.read<RoutineBloc>().add(const CreateSceneEvent());
}
}
Navigator.pop(context);
},
textColor: ColorsManager.primaryColorWithOpacity,
),
],
);
}
static Widget _buildThenActions(RoutineState state, BuildContext context) {
return Expanded(
child: ListView(
// shrinkWrap: true,
children: state.thenItems.map((item) {
final functions = state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}).toList(),
),
);
}
static Widget _buildIfConditions(RoutineState state, BuildContext context) {
return Expanded(
child: ListView(
// shrinkWrap: true,
children: [
if (state.isTabToRun) if (state.isTabToRun)
ListTile( ListTile(
leading: SvgPicture.asset( leading: SvgPicture.asset(
@ -65,75 +172,14 @@ class SaveRoutineHelper {
}), }),
], ],
), ),
),
const SizedBox(width: 16),
// Right side - THEN items
Expanded(
child: ListView(
// crossAxisAlignment: CrossAxisAlignment.start,
shrinkWrap: true,
children: [
const Text(
'THEN:',
style: TextStyle(
fontSize: 16,
),
),
const SizedBox(height: 8),
...state.thenItems.map((item) {
final functions =
state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}),
],
),
),
],
),
),
// if (state.errorMessage != null || state.errorMessage!.isNotEmpty)
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Text(
// state.errorMessage!,
// style: const TextStyle(color: Colors.red),
// ),
// ),
DialogFooter(
onCancel: () => Navigator.pop(context),
onConfirm: () async {
if (state.isAutomation) {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateAutomation());
} else {
context.read<RoutineBloc>().add(const CreateAutomationEvent());
}
} else {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateScene());
} else {
context.read<RoutineBloc>().add(const CreateSceneEvent());
}
}
// if (state.errorMessage == null || state.errorMessage!.isEmpty) {
Navigator.pop(context);
// }
},
isConfirmEnabled: true,
),
],
),
),
);
},
);
},
); );
} }
static Widget functionRow( static Widget functionRow(
dynamic item, BuildContext context, List<DeviceFunctionData> functions) { dynamic item,
BuildContext context,
List<DeviceFunctionData> functions,
) {
return Padding( return Padding(
padding: const EdgeInsets.only(top: 6), padding: const EdgeInsets.only(top: 6),
child: Row( child: Row(
@ -142,18 +188,35 @@ class SaveRoutineHelper {
Expanded( Expanded(
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
spacing: 8, spacing: 17,
children: [ children: [
item['type'] == 'tap_to_run' || item['type'] == 'scene' Container(
? Image.memory(
base64Decode(item['icon']),
width: 22, width: 22,
height: 22, height: 22,
padding: const EdgeInsetsDirectional.all(4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: ColorsManager.textFieldGreyColor,
border: Border.all(
color: ColorsManager.neutralGray,
width: 1.5,
),
),
child: Center(
child: item['type'] == 'tap_to_run' || item['type'] == 'scene'
? Image.memory(
base64Decode(item['icon']),
width: 12,
height: 22,
fit: BoxFit.scaleDown,
) )
: SvgPicture.asset( : SvgPicture.asset(
item['imagePath'], item['imagePath'],
width: 22, width: 12,
height: 22, height: 12,
fit: BoxFit.scaleDown,
),
),
), ),
Flexible( Flexible(
child: Column( child: Column(
@ -166,19 +229,25 @@ class SaveRoutineHelper {
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: context.textTheme.bodySmall?.copyWith( style: context.textTheme.bodySmall?.copyWith(
fontSize: 14, fontSize: 15,
color: ColorsManager.textPrimaryColor, color: ColorsManager.textPrimaryColor,
), ),
), ),
Wrap( Wrap(
runSpacing: 16,
spacing: 4,
children: functions children: functions
.map((f) => Text( .map(
'${f.operationName}: ${f.value}', (function) => Text(
style: context.textTheme.bodySmall '${function.operationName}: ${function.value}',
?.copyWith(color: ColorsManager.grayColor, fontSize: 8), style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.grayColor,
fontSize: 8,
),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
maxLines: 3, maxLines: 3,
)) ),
)
.toList(), .toList(),
), ),
], ],
@ -197,7 +266,13 @@ class SaveRoutineHelper {
child: Row( child: Row(
spacing: 2, spacing: 2,
children: [ children: [
SizedBox(width: 8, height: 8, child: SvgPicture.asset(Assets.deviceTagIcon)), SizedBox(
width: 8,
height: 8,
child: SvgPicture.asset(
Assets.deviceTagIcon,
),
),
Text( Text(
item['tag'] ?? '', item['tag'] ?? '',
textAlign: TextAlign.center, textAlign: TextAlign.center,
@ -218,7 +293,12 @@ class SaveRoutineHelper {
spacing: 2, spacing: 2,
children: [ children: [
SizedBox( SizedBox(
width: 8, height: 8, child: SvgPicture.asset(Assets.spaceLocationIcon)), width: 8,
height: 8,
child: SvgPicture.asset(
Assets.spaceLocationIcon,
),
),
Text( Text(
item['subSpace'] ?? '', item['subSpace'] ?? '',
textAlign: TextAlign.center, textAlign: TextAlign.center,

View File

@ -28,32 +28,40 @@ class DialogFooter extends StatelessWidget {
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [ children: [
_buildFooterButton( DialogFooterButton(
context: context,
text: 'Cancel', text: 'Cancel',
onTap: onCancel, onTap: onCancel,
), ),
if (isConfirmEnabled) ...[ if (isConfirmEnabled) ...[
Container(width: 1, height: 50, color: ColorsManager.greyColor), Container(width: 1, height: 50, color: ColorsManager.greyColor),
_buildFooterButton( DialogFooterButton(
context: context,
text: 'Confirm', text: 'Confirm',
onTap: onConfirm, onTap: onConfirm,
textColor: textColor: isConfirmEnabled
isConfirmEnabled ? ColorsManager.primaryColorWithOpacity : Colors.red, ? ColorsManager.primaryColorWithOpacity
: Colors.red,
), ),
], ],
], ],
), ),
); );
} }
}
Widget _buildFooterButton({ class DialogFooterButton extends StatelessWidget {
required BuildContext context, const DialogFooterButton({
required String text, required this.text,
required VoidCallback? onTap, required this.onTap,
Color? textColor, this.textColor,
}) { super.key,
});
final String text;
final VoidCallback? onTap;
final Color? textColor;
@override
Widget build(BuildContext context) {
return Expanded( return Expanded(
child: TextButton( child: TextButton(
style: TextButton.styleFrom( style: TextButton.styleFrom(

View File

@ -16,6 +16,7 @@ class DialogHeader extends StatelessWidget {
), ),
Text( Text(
title, title,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith( style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity, color: ColorsManager.primaryColorWithOpacity,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,

View File

@ -9,6 +9,7 @@ import 'package:syncrow_web/pages/routines/models/ac/ac_operational_value.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart'; import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -74,11 +75,26 @@ class ACHelper {
child: _buildFunctionsList( child: _buildFunctionsList(
context: context, context: context,
acFunctions: acFunctions, acFunctions: acFunctions,
onFunctionSelected: (functionCode, operationName) => device: device,
context.read<FunctionBloc>().add(SelectFunction( onFunctionSelected: (functionCode, operationName) {
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: functionCode, functionCode: functionCode,
operationName: operationName, functionOperationName: operationName,
)), functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'temp_set',
'temp_current',
],
defaultValue: functionCode == 'temp_set'
? 200
: functionCode == 'temp_current'
? -100
: 0,
);
},
), ),
), ),
// Value selector // Value selector
@ -137,6 +153,7 @@ class ACHelper {
required BuildContext context, required BuildContext context,
required List<ACFunction> acFunctions, required List<ACFunction> acFunctions,
required Function(String, String) onFunctionSelected, required Function(String, String) onFunctionSelected,
required AllDevicesModel? device,
}) { }) {
return ListView.separated( return ListView.separated(
shrinkWrap: false, shrinkWrap: false,

View File

@ -131,7 +131,12 @@ class _CeilingSensorDialogState extends State<CeilingSensorDialog> {
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
CpsFunctionsList(cpsFunctions: _cpsFunctions), CpsFunctionsList(
cpsFunctions: _cpsFunctions,
device: widget.device,
selectedFunctionData: selectedFunctionData,
dialogType: widget.dialogType,
),
if (state.selectedFunction != null) if (state.selectedFunction != null)
Expanded( Expanded(
child: isToggleFunction child: isToggleFunction

View File

@ -1,14 +1,24 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/models/ceiling_presence_sensor_functions.dart'; import 'package:syncrow_web/pages/routines/models/ceiling_presence_sensor_functions.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialog_function_list_tile.dart'; import 'package:syncrow_web/pages/routines/widgets/routine_dialog_function_list_tile.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
class CpsFunctionsList extends StatelessWidget { class CpsFunctionsList extends StatelessWidget {
const CpsFunctionsList({required this.cpsFunctions, super.key}); const CpsFunctionsList({
required this.cpsFunctions,
required this.device,
required this.selectedFunctionData,
required this.dialogType,
super.key,
});
final List<CpsFunctions> cpsFunctions; final List<CpsFunctions> cpsFunctions;
final AllDevicesModel? device;
final DeviceFunctionData? selectedFunctionData;
final String dialogType;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -26,11 +36,26 @@ class CpsFunctionsList extends StatelessWidget {
return RoutineDialogFunctionListTile( return RoutineDialogFunctionListTile(
iconPath: function.icon, iconPath: function.icon,
operationName: function.operationName, operationName: function.operationName,
onTap: () => context.read<FunctionBloc>().add( onTap: () => RoutineTapFunctionHelper.onTapFunction(
SelectFunction( context,
functionCode: function.code, functionCode: function.code,
operationName: function.operationName, functionOperationName: function.operationName,
), functionValueDescription: selectedFunctionData?.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'static_max_dis',
'presence_reference',
'moving_reference',
'perceptual_boundary',
'moving_boundary',
'moving_rigger_time',
'moving_static_time',
'none_body_time',
'moving_max_dis',
'moving_range',
'presence_range',
if (dialogType == "IF") 'sensitivity',
],
), ),
); );
}, },

View File

@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
abstract final class RoutineTapFunctionHelper {
const RoutineTapFunctionHelper._();
static void onTapFunction(
BuildContext context, {
required String functionCode,
required String functionOperationName,
required String? functionValueDescription,
required String? deviceUuid,
required List<String> codesToAddIntoFunctionsWithDefaultValue,
int defaultValue = 0,
}) {
final functionsBloc = context.read<FunctionBloc>();
functionsBloc.add(
SelectFunction(
functionCode: functionCode,
operationName: functionOperationName,
),
);
final addedFunctions = functionsBloc.state.addedFunctions;
final isFunctionAlreadyAdded = addedFunctions.any(
(e) => e.functionCode == functionCode,
);
final shouldAddFunction =
codesToAddIntoFunctionsWithDefaultValue.contains(functionCode);
if (!isFunctionAlreadyAdded && shouldAddFunction) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: deviceUuid ?? '',
functionCode: functionCode,
operationName: functionOperationName,
value: defaultValue,
condition: '==',
valueDescription: functionValueDescription,
),
),
);
}
}
}

View File

@ -11,6 +11,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/one_gang_switch/
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart'; import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -24,21 +25,23 @@ class OneGangSwitchHelper {
required String uniqueCustomId, required String uniqueCustomId,
required bool removeComparetors, required bool removeComparetors,
}) async { }) async {
List<BaseSwitchFunction> oneGangFunctions = functions.whereType<BaseSwitchFunction>().toList(); List<BaseSwitchFunction> oneGangFunctions =
functions.whereType<BaseSwitchFunction>().toList();
return showDialog<Map<String, dynamic>?>( return showDialog<Map<String, dynamic>?>(
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return BlocProvider( return BlocProvider(
create: (_) => FunctionBloc()..add(InitializeFunctions(deviceSelectedFunctions ?? [])), create: (_) => FunctionBloc()
..add(InitializeFunctions(deviceSelectedFunctions ?? [])),
child: AlertDialog( child: AlertDialog(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
content: BlocBuilder<FunctionBloc, FunctionBlocState>( content: BlocBuilder<FunctionBloc, FunctionBlocState>(
builder: (context, state) { builder: (context, state) {
final selectedFunction = state.selectedFunction; final selectedFunction = state.selectedFunction;
final selectedOperationName = state.selectedOperationName; final selectedOperationName = state.selectedOperationName;
final selectedFunctionData = final selectedFunctionData = state.addedFunctions
state.addedFunctions.firstWhere((f) => f.functionCode == selectedFunction, .firstWhere((f) => f.functionCode == selectedFunction,
orElse: () => DeviceFunctionData( orElse: () => DeviceFunctionData(
entityId: '', entityId: '',
functionCode: selectedFunction ?? '', functionCode: selectedFunction ?? '',
@ -84,12 +87,19 @@ class OneGangSwitchHelper {
size: 16, size: 16,
color: ColorsManager.textGray, color: ColorsManager.textGray,
), ),
onTap: () { onTap: () =>
context.read<FunctionBloc>().add(SelectFunction( RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code, functionCode: function.code,
operationName: function.operationName, functionOperationName:
)); function.operationName,
}, functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
],
),
); );
}, },
), ),
@ -220,11 +230,11 @@ class OneGangSwitchHelper {
selectedFunctionData, selectedFunctionData,
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
_buildCountDownDisplay( _buildCountDownDisplay(context, initialValue, device, operationName,
context, initialValue, device, operationName, selectedFunctionData, selectCode), selectedFunctionData, selectCode),
const SizedBox(height: 20), const SizedBox(height: 20),
_buildCountDownSlider( _buildCountDownSlider(context, initialValue, device, operationName,
context, initialValue, device, operationName, selectedFunctionData, selectCode), selectedFunctionData, selectCode),
], ],
); );
} }
@ -301,19 +311,21 @@ class OneGangSwitchHelper {
DeviceFunctionData? selectedFunctionData, DeviceFunctionData? selectedFunctionData,
String selectCode, String selectCode,
) { ) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue( final operationalValues = SwitchOperationalValue(
icon: '', icon: '',
description: "sec", description: "sec",
value: 0.0, value: 0.0,
minValue: 0, minValue: 0,
maxValue: 86400, maxValue: twelveHoursInSeconds,
stepValue: 1, stepValue: 1,
); );
return Slider( return Slider(
value: (initialValue ?? 0).toDouble(), value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0, min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0, max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) / divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1)) (operationalValues.stepValue ?? 1))
.round(), .round(),
onChanged: (value) { onChanged: (value) {
@ -367,7 +379,9 @@ class OneGangSwitchHelper {
trailing: Icon( trailing: Icon(
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked, isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24, size: 24,
color: isSelected ? ColorsManager.primaryColorWithOpacity : ColorsManager.textGray, color: isSelected
? ColorsManager.primaryColorWithOpacity
: ColorsManager.textGray,
), ),
onTap: () { onTap: () {
if (!isSelected) { if (!isSelected) {

View File

@ -10,6 +10,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_func
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart'; import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -85,15 +86,21 @@ class ThreeGangSwitchHelper {
size: 16, size: 16,
color: ColorsManager.textGray, color: ColorsManager.textGray,
), ),
onTap: () { onTap: () =>
context RoutineTapFunctionHelper.onTapFunction(
.read<FunctionBloc>() context,
.add(SelectFunction(
functionCode: function.code, functionCode: function.code,
operationName: functionOperationName:
function.operationName, function.operationName,
)); functionValueDescription:
}, selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
'countdown_2',
'countdown_3',
],
),
); );
}, },
), ),
@ -183,8 +190,7 @@ class ThreeGangSwitchHelper {
); );
} }
final selectedFn = final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues(); final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList( return _buildOperationalValuesList(
@ -266,8 +272,7 @@ class ThreeGangSwitchHelper {
minHeight: 40.0, minHeight: 40.0,
minWidth: 40.0, minWidth: 40.0,
), ),
isSelected: isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(), children: conditions.map((c) => Text(c)).toList(),
); );
} }
@ -303,20 +308,21 @@ class ThreeGangSwitchHelper {
DeviceFunctionData? selectedFunctionData, DeviceFunctionData? selectedFunctionData,
String selectCode, String selectCode,
) { ) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue( final operationalValues = SwitchOperationalValue(
icon: '', icon: '',
description: "sec", description: "sec",
value: 0.0, value: 0.0,
minValue: 0, minValue: 0,
maxValue: 86400, maxValue: twelveHoursInSeconds,
stepValue: 1, stepValue: 1,
); );
return Slider( return Slider(
value: (initialValue ?? 0).toDouble(), value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0, min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0, max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) - divisions:
(operationalValues.minValue ?? 0)) / (((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1)) (operationalValues.stepValue ?? 1))
.round(), .round(),
onChanged: (value) { onChanged: (value) {
@ -368,9 +374,7 @@ class ThreeGangSwitchHelper {
style: context.textTheme.bodyMedium, style: context.textTheme.bodyMedium,
), ),
trailing: Icon( trailing: Icon(
isSelected isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
size: 24, size: 24,
color: isSelected color: isSelected
? ColorsManager.primaryColorWithOpacity ? ColorsManager.primaryColorWithOpacity
@ -386,8 +390,7 @@ class ThreeGangSwitchHelper {
operationName: operationName, operationName: operationName,
value: value.value, value: value.value,
condition: selectedFunctionData?.condition, condition: selectedFunctionData?.condition,
valueDescription: valueDescription: selectedFunctionData?.valueDescription,
selectedFunctionData?.valueDescription,
), ),
), ),
); );

View File

@ -10,6 +10,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_func
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart'; import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -85,15 +86,20 @@ class TwoGangSwitchHelper {
size: 16, size: 16,
color: ColorsManager.textGray, color: ColorsManager.textGray,
), ),
onTap: () { onTap: () =>
context RoutineTapFunctionHelper.onTapFunction(
.read<FunctionBloc>() context,
.add(SelectFunction(
functionCode: function.code, functionCode: function.code,
operationName: functionOperationName:
function.operationName, function.operationName,
)); functionValueDescription:
}, selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
'countdown_2',
],
),
); );
}, },
), ),
@ -167,8 +173,7 @@ class TwoGangSwitchHelper {
required String operationName, required String operationName,
required bool removeComparetors, required bool removeComparetors,
}) { }) {
if (selectedFunction == 'countdown_1' || if (selectedFunction == 'countdown_1' || selectedFunction == 'countdown_2') {
selectedFunction == 'countdown_2') {
final initialValue = selectedFunctionData?.value ?? 0; final initialValue = selectedFunctionData?.value ?? 0;
return _buildTemperatureSelector( return _buildTemperatureSelector(
context: context, context: context,
@ -182,8 +187,7 @@ class TwoGangSwitchHelper {
); );
} }
final selectedFn = final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues(); final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList( return _buildOperationalValuesList(
@ -265,8 +269,7 @@ class TwoGangSwitchHelper {
minHeight: 40.0, minHeight: 40.0,
minWidth: 40.0, minWidth: 40.0,
), ),
isSelected: isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(), children: conditions.map((c) => Text(c)).toList(),
); );
} }
@ -302,20 +305,21 @@ class TwoGangSwitchHelper {
DeviceFunctionData? selectedFunctionData, DeviceFunctionData? selectedFunctionData,
String selectCode, String selectCode,
) { ) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue( final operationalValues = SwitchOperationalValue(
icon: '', icon: '',
description: "sec", description: "sec",
value: 0.0, value: 0.0,
minValue: 0, minValue: 0,
maxValue: 86400, maxValue: twelveHoursInSeconds,
stepValue: 1, stepValue: 1,
); );
return Slider( return Slider(
value: (initialValue ?? 0).toDouble(), value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0, min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0, max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) - divisions:
(operationalValues.minValue ?? 0)) / (((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1)) (operationalValues.stepValue ?? 1))
.round(), .round(),
onChanged: (value) { onChanged: (value) {
@ -367,9 +371,7 @@ class TwoGangSwitchHelper {
style: context.textTheme.bodyMedium, style: context.textTheme.bodyMedium,
), ),
trailing: Icon( trailing: Icon(
isSelected isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
size: 24, size: 24,
color: isSelected color: isSelected
? ColorsManager.primaryColorWithOpacity ? ColorsManager.primaryColorWithOpacity
@ -385,8 +387,7 @@ class TwoGangSwitchHelper {
operationName: operationName, operationName: operationName,
value: value.value, value: value.value,
condition: selectedFunctionData?.condition, condition: selectedFunctionData?.condition,
valueDescription: valueDescription: selectedFunctionData?.valueDescription,
selectedFunctionData?.valueDescription,
), ),
), ),
); );

View File

@ -8,6 +8,7 @@ import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/wps/wps_functions.dart'; import 'package:syncrow_web/pages/routines/models/wps/wps_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart'; import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/wps_value_selector_widget.dart'; import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/wps_value_selector_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart'; import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -111,13 +112,23 @@ class _WallPresenceSensorState extends State<WallPresenceSensor> {
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
_buildFunctionList(context), _buildFunctionList(context, state),
if (state.selectedFunction != null) _buildValueSelector(context, state), if (state.selectedFunction != null) _buildValueSelector(context, state),
], ],
); );
} }
Widget _buildFunctionList(BuildContext context) { Widget _buildFunctionList(BuildContext context, FunctionBlocState state) {
final selectedFunction = state.selectedFunction;
final selectedFunctionData = state.addedFunctions.firstWhere(
(f) => f.functionCode == selectedFunction,
orElse: () => DeviceFunctionData(
entityId: '',
functionCode: selectedFunction ?? '',
operationName: '',
value: null,
),
);
return SizedBox( return SizedBox(
width: 360, width: 360,
child: ListView.separated( child: ListView.separated(
@ -149,11 +160,17 @@ class _WallPresenceSensorState extends State<WallPresenceSensor> {
size: 16, size: 16,
color: ColorsManager.textGray, color: ColorsManager.textGray,
), ),
onTap: () => context.read<FunctionBloc>().add( onTap: () => RoutineTapFunctionHelper.onTapFunction(
SelectFunction( context,
functionCode: function.code, functionCode: function.code,
operationName: function.operationName, functionOperationName: function.operationName,
), functionValueDescription: selectedFunctionData.valueDescription,
deviceUuid: widget.device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'dis_current',
'presence_time',
'illuminance_value',
],
), ),
); );
}, },

View File

@ -41,14 +41,12 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) { return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) {
final communities = state.searchQuery.isNotEmpty final communities =
? state.filteredCommunity state.searchQuery.isNotEmpty ? state.filteredCommunity : state.communityList;
: state.communityList;
return Container( return Container(
height: MediaQuery.sizeOf(context).height, height: MediaQuery.sizeOf(context).height,
decoration: widget.isSide == true decoration: widget.isSide == true
? subSectionContainerDecoration.copyWith( ? subSectionContainerDecoration.copyWith(color: ColorsManager.whiteColors)
color: ColorsManager.whiteColors)
: const BoxDecoration(color: ColorsManager.whiteColors), : const BoxDecoration(color: ColorsManager.whiteColors),
child: state is SpaceTreeLoadingState child: state is SpaceTreeLoadingState
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
@ -81,12 +79,10 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
style: context.textTheme.bodyMedium?.copyWith( style: context.textTheme.bodyMedium?.copyWith(
color: ColorsManager.blackColor, color: ColorsManager.blackColor,
), ),
onChanged: (value) => onChanged: (value) => context.read<SpaceTreeBloc>().add(
context.read<SpaceTreeBloc>().add(
SearchQueryEvent(value), SearchQueryEvent(value),
), ),
decoration: decoration: textBoxDecoration(radios: 20)?.copyWith(
textBoxDecoration(radios: 20)?.copyWith(
fillColor: Colors.white, fillColor: Colors.white,
suffixIcon: Padding( suffixIcon: Padding(
padding: const EdgeInsets.only(right: 16), padding: const EdgeInsets.only(right: 16),
@ -96,8 +92,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
height: 24, height: 24,
), ),
), ),
hintStyle: hintStyle: context.textTheme.bodyMedium?.copyWith(
context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
fontSize: 12, fontSize: 12,
color: ColorsManager.textGray, color: ColorsManager.textGray,
@ -121,23 +116,26 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
child: state.isSearching child: state.isSearching
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: SidebarCommunitiesList( : SidebarCommunitiesList(
onScrollToEnd: () => context.read<SpaceTreeBloc>().add( onScrollToEnd: () {
if (!state.paginationIsLoading) {
context.read<SpaceTreeBloc>().add(
PaginationEvent( PaginationEvent(
state.paginationModel, state.paginationModel,
state.communityList, state.communityList,
), ),
), );
}
},
scrollController: _scrollController, scrollController: _scrollController,
communities: communities, communities: communities,
itemBuilder: (context, index) { itemBuilder: (context, index) {
return CustomExpansionTileSpaceTree( return CustomExpansionTileSpaceTree(
title: communities[index].name, title: communities[index].name,
isSelected: state.selectedCommunities isSelected:
.contains(communities[index].uuid), state.selectedCommunities.contains(communities[index].uuid),
isSoldCheck: state.selectedCommunities isSoldCheck:
.contains(communities[index].uuid), state.selectedCommunities.contains(communities[index].uuid),
onExpansionChanged: () => onExpansionChanged: () => context.read<SpaceTreeBloc>().add(
context.read<SpaceTreeBloc>().add(
OnCommunityExpanded( OnCommunityExpanded(
communities[index].uuid, communities[index].uuid,
), ),
@ -158,8 +156,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
(space) { (space) {
return CustomExpansionTileSpaceTree( return CustomExpansionTileSpaceTree(
title: space.name, title: space.name,
isExpanded: isExpanded: state.expandedSpaces.contains(space.uuid),
state.expandedSpaces.contains(space.uuid),
onItemSelected: () { onItemSelected: () {
context.read<SpaceTreeBloc>().add( context.read<SpaceTreeBloc>().add(
OnSpaceSelected( OnSpaceSelected(
@ -170,18 +167,15 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
); );
widget.onSelect(); widget.onSelect();
}, },
onExpansionChanged: () => onExpansionChanged: () => context.read<SpaceTreeBloc>().add(
context.read<SpaceTreeBloc>().add(
OnSpaceExpanded( OnSpaceExpanded(
communities[index].uuid, communities[index].uuid,
space.uuid ?? '', space.uuid ?? '',
), ),
), ),
isSelected: state.selectedSpaces isSelected: state.selectedSpaces.contains(space.uuid) ||
.contains(space.uuid) ||
state.soldCheck.contains(space.uuid),
isSoldCheck:
state.soldCheck.contains(space.uuid), state.soldCheck.contains(space.uuid),
isSoldCheck: state.soldCheck.contains(space.uuid),
children: _buildNestedSpaces( children: _buildNestedSpaces(
context, context,
state, state,
@ -210,8 +204,8 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
) { ) {
return space.children.map((child) { return space.children.map((child) {
return CustomExpansionTileSpaceTree( return CustomExpansionTileSpaceTree(
isSelected: state.selectedSpaces.contains(child.uuid) || isSelected:
state.soldCheck.contains(child.uuid), state.selectedSpaces.contains(child.uuid) || state.soldCheck.contains(child.uuid),
isSoldCheck: state.soldCheck.contains(child.uuid), isSoldCheck: state.soldCheck.contains(child.uuid),
title: child.name, title: child.name,
isExpanded: state.expandedSpaces.contains(child.uuid), isExpanded: state.expandedSpaces.contains(child.uuid),

View File

@ -1,4 +1,6 @@
// Flutter imports // Flutter imports
import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@ -336,6 +338,7 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
} }
spaces.add(newSpace); spaces.add(newSpace);
_updateNodePosition(newSpace, newSpace.position); _updateNodePosition(newSpace, newSpace.position);
realignTree();
}); });
}, },
); );
@ -450,7 +453,6 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
void _saveSpaces() { void _saveSpaces() {
if (widget.selectedCommunity == null) { if (widget.selectedCommunity == null) {
debugPrint("No community selected for saving spaces.");
return; return;
} }
@ -530,35 +532,83 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
} }
Offset getBalancedChildPosition(SpaceModel parent) { Offset getBalancedChildPosition(SpaceModel parent) {
int totalSiblings = parent.children.length + 1; const double nodeWidth = 200;
double totalWidth = (totalSiblings - 1) * 250; // Horizontal spacing const double verticalGap = 180;
if (parent.children.isEmpty) {
// First child → exactly center
return Offset(parent.position.dx, parent.position.dy + verticalGap);
} else {
// More children → arrange them spaced horizontally
double totalWidth = (parent.children.length) * (nodeWidth + 60);
double startX = parent.position.dx - (totalWidth / 2); double startX = parent.position.dx - (totalWidth / 2);
Offset position = Offset(startX + (parent.children.length * 250), parent.position.dy + 180); double childX = startX + (parent.children.length * (nodeWidth + 60));
return Offset(childX, parent.position.dy + verticalGap);
// Check for overlaps & adjust
while (spaces.any((s) => (s.position - position).distance < 250)) {
position = Offset(position.dx + 250, position.dy);
} }
return position;
} }
void realignTree() { void realignTree() {
void updatePositions(SpaceModel node, double x, double y) { const double nodeWidth = 200;
node.position = Offset(x, y); const double nodeHeight = 100;
const double horizontalGap = 60;
const double verticalGap = 180;
const double rootGap = 400; // extra space between different roots
int numChildren = node.children.length; double canvasRightEdge = 1000;
double childStartX = x - ((numChildren - 1) * 250) / 2; double canvasBottomEdge = 1000;
for (int i = 0; i < numChildren; i++) { double calculateSubtreeWidth(SpaceModel node) {
updatePositions(node.children[i], childStartX + (i * 250), y + 180); if (node.children.isEmpty) return nodeWidth;
double totalWidth = 0;
for (var child in node.children) {
totalWidth += calculateSubtreeWidth(child) + horizontalGap;
}
return totalWidth - horizontalGap;
}
void layoutSubtree(SpaceModel node, double startX, double y) {
double subtreeWidth = calculateSubtreeWidth(node);
double centerX = startX + subtreeWidth / 2 - nodeWidth / 2;
node.position = Offset(centerX, y);
canvasRightEdge = max(canvasRightEdge, centerX + nodeWidth);
canvasBottomEdge = max(canvasBottomEdge, y + nodeHeight);
if (node.children.length == 1) {
final child = node.children.first;
layoutSubtree(child, centerX, y + verticalGap);
} else {
double childX = startX;
for (var child in node.children) {
double childWidth = calculateSubtreeWidth(child);
layoutSubtree(child, childX, y + verticalGap);
childX += childWidth + horizontalGap;
}
} }
} }
if (spaces.isNotEmpty) { // ⚡ New: layout each root separately
updatePositions(spaces.first, spaces.first.position.dx, spaces.first.position.dy); final List<SpaceModel> roots = spaces
.where((s) =>
s.parent == null &&
s.status != SpaceStatus.deleted &&
s.status != SpaceStatus.parentDeleted)
.toList();
double currentX = 100; // start some margin from left
double currentY = 100; // top margin
for (var root in roots) {
layoutSubtree(root, currentX, currentY);
double rootWidth = calculateSubtreeWidth(root);
currentX += rootWidth + rootGap;
} }
setState(() {
canvasWidth = canvasRightEdge + 400;
canvasHeight = canvasBottomEdge + 400;
});
} }
void _onDuplicate(BuildContext parentContext) { void _onDuplicate(BuildContext parentContext) {
@ -642,63 +692,19 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
} }
void _duplicateSpace(SpaceModel space) { void _duplicateSpace(SpaceModel space) {
final Map<SpaceModel, SpaceModel> originalToDuplicate = {}; final double horizontalGap = 250.0;
double horizontalGap = 250.0; // Increased spacing final double verticalGap = 180.0;
double verticalGap = 180.0; // Adjusted for better visualization final double nodeWidth = 200;
final double nodeHeight = 100;
final double breathingSpace = 300.0; // extra gap after original tree
print("🟢 Duplicating: ${space.name}"); /// Helper to recursively duplicate a node and its children
/// **Find a new position ensuring no overlap**
Offset getBalancedChildPosition(SpaceModel parent) {
int totalSiblings = parent.children.length + 1;
double totalWidth = (totalSiblings - 1) * horizontalGap;
double startX = parent.position.dx - (totalWidth / 2);
Offset position = Offset(
startX + (parent.children.length * horizontalGap), parent.position.dy + verticalGap);
// **Check for overlaps & adjust**
while (spaces.any((s) => (s.position - position).distance < horizontalGap)) {
position = Offset(position.dx + horizontalGap, position.dy);
}
print("🔹 New position for ${parent.name}: (${position.dx}, ${position.dy})");
return position;
}
/// **Realign the entire tree after duplication**
void realignTree() {
void updatePositions(SpaceModel node, double x, double y) {
node.position = Offset(x, y);
print("✅ Adjusted ${node.name} to (${x}, ${y})");
int numChildren = node.children.length;
double childStartX = x - ((numChildren - 1) * horizontalGap) / 2;
for (int i = 0; i < numChildren; i++) {
updatePositions(node.children[i], childStartX + (i * horizontalGap), y + verticalGap);
}
}
if (spaces.isNotEmpty) {
print("🔄 Realigning tree...");
updatePositions(spaces.first, spaces.first.position.dx, spaces.first.position.dy);
}
}
/// **Recursive duplication logic**
SpaceModel duplicateRecursive(SpaceModel original, SpaceModel? duplicatedParent) { SpaceModel duplicateRecursive(SpaceModel original, SpaceModel? duplicatedParent) {
Offset newPosition = duplicatedParent == null
? Offset(original.position.dx + horizontalGap, original.position.dy)
: getBalancedChildPosition(duplicatedParent);
final duplicatedName = SpaceHelper.generateUniqueSpaceName(original.name, spaces); final duplicatedName = SpaceHelper.generateUniqueSpaceName(original.name, spaces);
print(
"🟡 Duplicating ${original.name}${duplicatedName} at (${newPosition.dx}, ${newPosition.dy})");
final duplicated = SpaceModel( final duplicated = SpaceModel(
name: duplicatedName, name: duplicatedName,
icon: original.icon, icon: original.icon,
position: newPosition, position: Offset.zero,
isPrivate: original.isPrivate, isPrivate: original.isPrivate,
children: [], children: [],
status: SpaceStatus.newSpace, status: SpaceStatus.newSpace,
@ -708,9 +714,7 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
tags: original.tags, tags: original.tags,
); );
setState(() {
spaces.add(duplicated); spaces.add(duplicated);
_updateNodePosition(duplicated, duplicated.position);
if (duplicatedParent != null) { if (duplicatedParent != null) {
final newConnection = Connection( final newConnection = Connection(
@ -722,14 +726,8 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
duplicated.incomingConnection = newConnection; duplicated.incomingConnection = newConnection;
duplicatedParent.addOutgoingConnection(newConnection); duplicatedParent.addOutgoingConnection(newConnection);
duplicatedParent.children.add(duplicated); duplicatedParent.children.add(duplicated);
print("🔗 Created connection: ${duplicatedParent.name}${duplicated.name}");
} }
// **Recalculate the whole tree to avoid overlaps**
realignTree();
});
// Recursively duplicate children
for (var child in original.children) { for (var child in original.children) {
duplicateRecursive(child, duplicated); duplicateRecursive(child, duplicated);
} }
@ -737,21 +735,49 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
return duplicated; return duplicated;
} }
/// **Handle root duplication** /// Layout a subtree rooted at node
if (space.parent == null) { void layoutSubtree(SpaceModel node, double startX, double startY) {
print("🟠 Duplicating root node: ${space.name}"); double calculateSubtreeWidth(SpaceModel n) {
SpaceModel duplicatedRoot = duplicateRecursive(space, null); if (n.children.isEmpty) return nodeWidth;
double width = 0;
for (var child in n.children) {
width += calculateSubtreeWidth(child) + horizontalGap;
}
return width - horizontalGap;
}
setState(() { void assignPositions(SpaceModel n, double x, double y) {
spaces.add(duplicatedRoot); double subtreeWidth = calculateSubtreeWidth(n);
realignTree(); double centerX = x + subtreeWidth / 2 - nodeWidth / 2;
}); n.position = Offset(centerX, y);
print("✅ Root duplication successful: ${duplicatedRoot.name}"); if (n.children.length == 1) {
assignPositions(n.children.first, centerX, y + verticalGap);
} else { } else {
duplicateRecursive(space, space.parent); double childX = x;
for (var child in n.children) {
double childWidth = calculateSubtreeWidth(child);
assignPositions(child, childX, y + verticalGap);
childX += childWidth + horizontalGap;
}
}
} }
print("🟢 Finished duplication process for: ${space.name}"); double totalSubtreeWidth = calculateSubtreeWidth(node);
assignPositions(node, startX, startY);
}
/// Actual duplication process
setState(() {
if (space.parent == null) {
// Duplicating a ROOT node
SpaceModel duplicatedRoot = duplicateRecursive(space, null);
realignTree();
} else {
// Duplicating a CHILD node inside its parent
SpaceModel duplicated = duplicateRecursive(space, space.parent);
realignTree();
}
});
} }
} }

View File

@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/widgets/empty_search_result_widget.dart'; import 'package:syncrow_web/common/widgets/empty_search_result_widget.dart';
import 'package:syncrow_web/common/widgets/search_bar.dart'; import 'package:syncrow_web/common/widgets/search_bar.dart';
import 'package:syncrow_web/common/widgets/sidebar_communities_list.dart'; import 'package:syncrow_web/common/widgets/sidebar_communities_list.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
@ -15,6 +16,8 @@ import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/cent
import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_event.dart'; import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_event.dart';
import 'package:syncrow_web/utils/style.dart'; import 'package:syncrow_web/utils/style.dart';
import '../../../space_tree/bloc/space_tree_event.dart';
class SidebarWidget extends StatefulWidget { class SidebarWidget extends StatefulWidget {
final List<CommunityModel> communities; final List<CommunityModel> communities;
final String? selectedSpaceUuid; final String? selectedSpaceUuid;
@ -40,13 +43,31 @@ class _SidebarWidgetState extends State<SidebarWidget> {
@override @override
void initState() { void initState() {
_selectedId = widget.selectedSpaceUuid;
_scrollController = ScrollController(); _scrollController = ScrollController();
_scrollController.addListener(_onScroll);
_selectedId = widget.selectedSpaceUuid;
super.initState(); super.initState();
} }
void _onScroll() {
if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
// Trigger pagination event
final bloc = context.read<SpaceTreeBloc>();
if (!bloc.state.paginationIsLoading && bloc.state.paginationModel?.hasNext == true) {
bloc.add(
PaginationEvent(
bloc.state.paginationModel!,
bloc.state.communityList,
),
);
}
}
}
@override @override
void dispose() { void dispose() {
_scrollController.removeListener(_onScroll);
_scrollController.dispose(); _scrollController.dispose();
super.dispose(); super.dispose();
} }
@ -59,38 +80,6 @@ class _SidebarWidgetState extends State<SidebarWidget> {
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
} }
List<CommunityModel> _filteredCommunities() {
if (_searchQuery.isEmpty) {
_selectedSpaceUuid = null;
return widget.communities;
}
return widget.communities.where((community) {
final containsQueryInCommunity =
community.name.toLowerCase().contains(_searchQuery.toLowerCase());
final containsQueryInSpaces = community.spaces.any((space) =>
_containsQuery(space: space, query: _searchQuery.toLowerCase()));
return containsQueryInCommunity || containsQueryInSpaces;
}).toList();
}
bool _containsQuery({
required SpaceModel space,
required String query,
}) {
final matchesSpace = space.name.toLowerCase().contains(query);
final matchesChildren = space.children.any(
(child) => _containsQuery(space: child, query: query),
);
if (matchesSpace || matchesChildren) {
_selectedSpaceUuid = space.uuid;
}
return matchesSpace || matchesChildren;
}
bool _isSpaceOrChildSelected(SpaceModel space) { bool _isSpaceOrChildSelected(SpaceModel space) {
final isSpaceSelected = _selectedSpaceUuid == space.uuid; final isSpaceSelected = _selectedSpaceUuid == space.uuid;
final anySubSpaceIsSelected = space.children.any(_isSpaceOrChildSelected); final anySubSpaceIsSelected = space.children.any(_isSpaceOrChildSelected);
@ -101,7 +90,10 @@ class _SidebarWidgetState extends State<SidebarWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final filteredCommunities = _filteredCommunities(); final spaceTreeState = context.watch<SpaceTreeBloc>().state;
final filteredCommunities = spaceTreeState.isSearching
? spaceTreeState.filteredCommunity
: spaceTreeState.communityList;
return Container( return Container(
width: _width, width: _width,
@ -112,7 +104,13 @@ class _SidebarWidgetState extends State<SidebarWidget> {
children: [ children: [
SidebarHeader(onAddCommunity: _onAddCommunity), SidebarHeader(onAddCommunity: _onAddCommunity),
CustomSearchBar( CustomSearchBar(
onSearchChanged: (query) => setState(() => _searchQuery = query), onSearchChanged: (query) {
setState(() {
_searchQuery = query;
});
context.read<SpaceTreeBloc>().add(SearchQueryEvent(query));
},
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Expanded( Expanded(
@ -123,11 +121,15 @@ class _SidebarWidgetState extends State<SidebarWidget> {
scrollController: _scrollController, scrollController: _scrollController,
onScrollToEnd: () {}, onScrollToEnd: () {},
communities: filteredCommunities, communities: filteredCommunities,
itemBuilder: (context, index) => _buildCommunityTile( itemBuilder: (context, index) {
context, if (index == filteredCommunities.length) {
filteredCommunities[index], return const Padding(
), padding: EdgeInsets.all(8.0),
), child: Center(child: CircularProgressIndicator()),
);
}
return _buildCommunityTile(context, filteredCommunities[index]);
}),
), ),
), ),
], ],
@ -205,9 +207,8 @@ class _SidebarWidgetState extends State<SidebarWidget> {
); );
} }
void _onAddCommunity() => _selectedId?.isNotEmpty ?? true void _onAddCommunity() =>
? _clearSelection() _selectedId?.isNotEmpty ?? true ? _clearSelection() : _showCreateCommunityDialog();
: _showCreateCommunityDialog();
void _clearSelection() { void _clearSelection() {
setState(() => _selectedId = ''); setState(() => _selectedId = '');

View File

@ -0,0 +1,85 @@
import 'dart:developer';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';
abstract interface class BatchControlDevicesService {
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
});
}
final class RemoteBatchControlDevicesService implements BatchControlDevicesService {
@override
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
}) async {
try {
final body = {
'devicesUuid': uuids,
'code': code,
'value': value,
'operationType': 'COMMAND',
};
final response = await HTTPService().post(
path: ApiEndpoints.deviceBatchControl,
body: body,
showServerMessage: true,
expectedResponseModel: (json) => (json['success'] as bool?) ?? false,
);
return response;
} catch (e) {
log('Error fetching $e', name: 'BatchControlDevicesService');
return false;
}
}
}
final class DebouncedBatchControlDevicesService
implements BatchControlDevicesService {
final BatchControlDevicesService decoratee;
final Duration debounceDuration;
final _pendingRequests = <(List<String> uuids, String code, Object value)>[];
var _isProcessing = false;
DebouncedBatchControlDevicesService({
required this.decoratee,
this.debounceDuration = const Duration(milliseconds: 800),
});
@override
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
}) async {
_pendingRequests.add((uuids, code, value));
if (_isProcessing) return false;
_isProcessing = true;
await Future.delayed(debounceDuration);
final lastRequest = _pendingRequests.last;
_pendingRequests.clear();
try {
final (lastRequestUuids, lastRequestCode, lastRequestValue) = lastRequest;
return decoratee.batchControlDevices(
uuids: lastRequestUuids,
code: lastRequestCode,
value: lastRequestValue,
);
} finally {
_isProcessing = false;
}
}
}

View File

@ -0,0 +1,75 @@
import 'dart:developer';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';
abstract interface class ControlDeviceService {
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
});
}
final class RemoteControlDeviceService implements ControlDeviceService {
@override
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
}) async {
try {
final response = await HTTPService().post(
path: ApiEndpoints.deviceControl.replaceAll('{uuid}', deviceUuid),
body: status.toMap(),
showServerMessage: true,
expectedResponseModel: (json) {
return (json['success'] as bool?) ?? false;
},
);
return response;
} catch (e) {
log('Error fetching $e', name: 'ControlDeviceService');
return false;
}
}
}
final class DebouncedControlDeviceService implements ControlDeviceService {
final ControlDeviceService decoratee;
final Duration debounceDuration;
DebouncedControlDeviceService({
required this.decoratee,
this.debounceDuration = const Duration(milliseconds: 800),
});
final _pendingRequests = <(String deviceUuid, Status status)>[];
var _isProcessing = false;
@override
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
}) async {
_pendingRequests.add((deviceUuid, status));
if (_isProcessing) return false;
_isProcessing = true;
await Future.delayed(debounceDuration);
final lastRequest = _pendingRequests.last;
_pendingRequests.clear();
try {
final (lastRequestDeviceUuid, lastRequestStatus) = lastRequest;
return decoratee.controlDevice(
deviceUuid: lastRequestDeviceUuid,
status: lastRequestStatus,
);
} finally {
_isProcessing = false;
}
}
}

View File

@ -60,6 +60,7 @@ dependencies:
firebase_core: ^3.11.0 firebase_core: ^3.11.0
firebase_crashlytics: ^4.3.2 firebase_crashlytics: ^4.3.2
firebase_database: ^11.3.2 firebase_database: ^11.3.2
bloc: ^8.1.4
dev_dependencies: dev_dependencies: