Compare commits

..
Author SHA1 Message Date
mohammad ad4a0fc2ed Add new grey color constant and new icons for settings in assets
Update CreateNewRoutineView to use const constructor
Add SubSpaceModel class for device settings
Add DefaultContainer widget for web layout
Add events and states for device settings bloc
Update API endpoints for device settings
2025-05-28 14:18:32 +03:00
61 changed files with 1858 additions and 1694 deletions
-1
View File
@@ -10,7 +10,6 @@
analyzer:
errors:
constant_identifier_names: ignore
overridden_fields: ignore
include: package:flutter_lints/flutter.yaml
linter:
+3
View File
@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 24C8.79469 24 5.78123 22.7518 3.51469 20.4853C1.24823 18.2188 0 15.2053 0 12C0 8.79469 1.24823 5.78123 3.51469 3.51469C5.78123 1.24823 8.79469 0 12 0C15.2053 0 18.2188 1.24823 20.4853 3.51469C22.7518 5.78123 24 8.79469 24 12C24 15.2053 22.7518 18.2188 20.4853 20.4853C18.2188 22.7518 15.2053 24 12 24ZM12 1.875C9.2955 1.875 6.75291 2.92819 4.84055 4.84055C2.92819 6.75291 1.875 9.2955 1.875 12C1.875 14.7045 2.92819 17.2471 4.84055 19.1595C6.75291 21.0718 9.2955 22.125 12 22.125C14.7045 22.125 17.2471 21.0718 19.1595 19.1595C21.0718 17.2471 22.125 14.7045 22.125 12C22.125 9.2955 21.0718 6.75291 19.1595 4.84055C17.2471 2.92819 14.7045 1.875 12 1.875ZM15.9775 17.3033L12 13.3258L8.02252 17.3033L6.6967 15.9775L10.6742 12L6.6967 8.02252L8.02252 6.6967L12 10.6742L15.9775 6.6967L17.3033 8.02252L13.3258 12L17.3033 15.9775L15.9775 17.3033Z" fill="#999999" fill-opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 992 B

+3
View File
@@ -0,0 +1,3 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.4854 3.1332L9.8668 0.515228C9.64704 0.295536 9.34903 0.172119 9.03829 0.172119C8.72755 0.172119 8.42953 0.295536 8.20977 0.515228L0.983989 7.74042C0.874797 7.84895 0.788225 7.97806 0.729285 8.12027C0.670346 8.26249 0.640212 8.41499 0.640629 8.56894V11.1875C0.640629 11.4983 0.764094 11.7964 0.983864 12.0161C1.20363 12.2359 1.5017 12.3594 1.8125 12.3594H11.6563C11.8427 12.3594 12.0216 12.2853 12.1534 12.1534C12.2853 12.0216 12.3594 11.8427 12.3594 11.6562C12.3594 11.4698 12.2853 11.2909 12.1534 11.1591C12.0216 11.0272 11.8427 10.9531 11.6563 10.9531H6.32422L12.4854 4.79081C12.5942 4.68199 12.6806 4.55278 12.7395 4.41057C12.7984 4.26836 12.8288 4.11594 12.8288 3.96201C12.8288 3.80807 12.7984 3.65565 12.7395 3.51344C12.6806 3.37123 12.5942 3.24202 12.4854 3.1332ZM4.33204 10.9531H2.04688V8.66796L6.96875 3.74609L9.25391 6.03124L4.33204 10.9531ZM10.25 5.03515L7.96485 2.74999L9.03946 1.67538L11.3246 3.96054L10.25 5.03515Z" fill="#D5D5D5"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

-12
View File
@@ -1,12 +0,0 @@
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_7305_15779)">
<path d="M17.0872 11.5142C17.0872 13.2025 16.427 14.8021 15.2211 15.9954C14.0278 17.2014 12.4283 17.8615 10.7399 17.8615C9.05141 17.8615 7.45185 17.2014 6.25856 15.9954C5.05262 14.8021 4.39249 13.2025 4.39249 11.5142C4.39249 9.82574 5.05266 8.22618 6.25856 7.03289C7.45185 5.8269 9.05141 5.16681 10.7399 5.16681C11.8063 5.16681 12.8471 5.43337 13.7866 5.95388L11.2984 8.97523H21.0861L18.6486 0L16.2113 2.97053C14.5737 1.91691 12.6948 1.35835 10.7398 1.35835C8.02314 1.35835 5.47142 2.41197 3.55459 4.32888C1.63765 6.24578 0.583984 8.79747 0.583984 11.5142C0.583984 14.2309 1.63765 16.7825 3.55459 18.6994C5.47146 20.6163 8.0231 21.67 10.7398 21.67C13.4565 21.67 16.0082 20.6163 17.925 18.6994C19.8419 16.7825 20.8956 14.2309 20.8956 11.5142V10.8794H17.0872V11.5142Z" fill="#77DD00"/>
<path d="M17.0876 10.8799H20.8961V11.5146C20.8961 14.2313 19.8424 16.7829 17.9254 18.6998C16.0086 20.6168 13.4569 21.6704 10.7402 21.6704V17.862C12.4287 17.862 14.0282 17.2019 15.2215 15.9959C16.4275 14.8026 17.0876 13.203 17.0876 11.5147V10.8799H17.0876Z" fill="#66BB00"/>
<path d="M13.787 5.95388C12.8475 5.43333 11.8066 5.16681 10.7402 5.16681V1.35835C12.6952 1.35835 14.5741 1.91691 16.2117 2.97057L18.6491 0L21.0866 8.97523H11.2989L13.787 5.95388Z" fill="#66BB00"/>
</g>
<defs>
<clipPath id="clip0_7305_15779">
<rect width="21.67" height="21.67" fill="white"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

@@ -20,11 +20,7 @@ class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrateg
spaces,
),
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(
context,
communityId: community.uuid,
spaceId: spaces.isNotEmpty ? spaces.first.uuid ?? '' : '',
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(context);
}
@override
@@ -40,12 +36,7 @@ class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrateg
space.children,
),
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(
context,
communityId: community.uuid,
spaceId: space.uuid ?? '',
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(context);
}
@override
@@ -54,7 +45,14 @@ class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrateg
CommunityModel community,
SpaceModel child,
) {
// Do nothing
context.read<SpaceTreeBloc>().add(
OnSpaceSelected(
community,
child.uuid ?? '',
child.children,
),
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(context);
}
@override
@@ -17,14 +17,10 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
context.read<SpaceTreeBloc>().add(
OnCommunitySelected(
community.uuid,
spaces.isNotEmpty ? [spaces.first] : [],
spaces,
),
);
FetchOccupancyDataHelper.loadOccupancyData(
context,
communityId: community.uuid,
spaceId: spaces.isNotEmpty ? spaces.first.uuid ?? '' : '',
);
FetchOccupancyDataHelper.loadOccupancyData(context);
}
@override
@@ -33,25 +29,14 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
CommunityModel community,
SpaceModel space,
) {
final spaceTreeBloc = context.read<SpaceTreeBloc>();
final selectedSpacesIds = spaceTreeBloc.state.selectedSpaces;
final isSpaceSelected = selectedSpacesIds.contains(space.uuid);
if (selectedSpacesIds.isEmpty) {
spaceTreeBloc.add(OnCommunitySelected(community.uuid, [space]));
} else if (isSpaceSelected) {
spaceTreeBloc.add(const SpaceTreeClearSelectionEvent());
} else {
spaceTreeBloc
..add(const SpaceTreeClearSelectionEvent())
..add(OnSpaceSelected(community, space.uuid ?? '', []));
}
FetchOccupancyDataHelper.loadOccupancyData(
context,
communityId: community.uuid,
spaceId: space.uuid ?? '',
);
context.read<SpaceTreeBloc>().add(
OnSpaceSelected(
community,
space.uuid ?? '',
space.children,
),
);
FetchOccupancyDataHelper.loadOccupancyData(context);
}
@override
@@ -60,12 +45,18 @@ class OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
CommunityModel community,
SpaceModel child,
) {
// Do nothing
context.read<SpaceTreeBloc>().add(
OnSpaceSelected(
community,
child.uuid ?? '',
child.children,
),
);
FetchOccupancyDataHelper.loadOccupancyData(context);
}
@override
void clearData(BuildContext context) {
context.read<SpaceTreeBloc>().add(const SpaceTreeClearSelectionEvent());
// FetchOccupancyDataHelper.clearAllData(context);
}
}
@@ -9,21 +9,29 @@ class AnalyticsCommunitiesSidebar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final selectedTab = context.watch<AnalyticsTabBloc>().state;
final strategy = AnalyticsDataLoadingStrategyFactory.getStrategy(selectedTab);
return Builder(
builder: (context) {
final selectedTab = context.read<AnalyticsTabBloc>().state;
final strategy =
AnalyticsDataLoadingStrategyFactory.getStrategy(selectedTab);
return Expanded(
child: AnalyticsSpaceTreeView(
onSelectCommunity: (community, spaces) {
strategy.onCommunitySelected(context, community, spaces);
},
onSelectSpace: (community, space) {
strategy.onSpaceSelected(context, community, space);
},
onSelectChildSpace: (community, child) {
strategy.onChildSpaceSelected(context, community, child);
},
),
// Clear data when tab changes
strategy.clearData(context);
return Expanded(
child: AnalyticsSpaceTreeView(
onSelectCommunity: (community, spaces) {
strategy.onCommunitySelected(context, community, spaces);
},
onSelectSpace: (community, space) {
strategy.onSpaceSelected(context, community, space);
},
onSelectChildSpace: (community, child) {
strategy.onChildSpaceSelected(context, community, child);
},
),
);
},
);
}
}
@@ -6,7 +6,6 @@ import 'package:syncrow_web/pages/analytics/modules/analytics/enums/analytics_pa
import 'package:syncrow_web/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/style.dart';
class AnalyticsPageTabsAndChildren extends StatelessWidget {
@@ -14,7 +13,6 @@ class AnalyticsPageTabsAndChildren extends StatelessWidget {
@override
Widget build(BuildContext context) {
final spaceTreeState = context.read<SpaceTreeBloc>().state;
return BlocBuilder<AnalyticsTabBloc, AnalyticsPageTab>(
buildWhen: (previous, current) => previous != current,
builder: (context, selectedTab) => Column(
@@ -68,14 +66,10 @@ class AnalyticsPageTabsAndChildren extends StatelessWidget {
context.read<AnalyticsDatePickerBloc>().add(
UpdateAnalyticsDatePickerEvent(montlyDate: value),
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(
FetchEnergyManagementDataHelper
.fetchEnergyManagementData(
context,
selectedDate: value,
communityId:
spaceTreeState.selectedCommunities.firstOrNull ??
'',
spaceId:
spaceTreeState.selectedSpaces.firstOrNull ?? '',
);
},
selectedDate: context
@@ -9,38 +9,58 @@ import 'package:syncrow_web/pages/analytics/modules/energy_management/blocs/tota
import 'package:syncrow_web/pages/analytics/params/get_energy_consumption_by_phases_param.dart';
import 'package:syncrow_web/pages/analytics/params/get_energy_consumption_per_device_param.dart';
import 'package:syncrow_web/pages/analytics/params/get_total_energy_consumption_param.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
abstract final class FetchEnergyManagementDataHelper {
const FetchEnergyManagementDataHelper._();
static const String _powerClampId = 'cb71d6ad-6e29-4eaa-ae3e-1a0d1c5f60fa';
static void loadEnergyManagementData(
static void fetchEnergyManagementData(
BuildContext context, {
required String communityId,
required String spaceId,
DateTime? selectedDate,
}) {
if (communityId.isEmpty && spaceId.isEmpty) {
final (selectedCommunities, selectedSpaces) =
getSelectedCommunitiesAndSpaces(context);
if (selectedCommunities.isEmpty && selectedSpaces.isEmpty) {
clearAllData(context);
return;
}
final datePickerState = context.read<AnalyticsDatePickerBloc>().state;
final selectedDate0 = selectedDate ?? datePickerState.monthlyDate;
loadTotalEnergyConsumption(
loadTotalEnergyConsumption(context, selectedDate: datePickerState.monthlyDate);
loadEnergyConsumptionByPhases(
context,
selectedDate: selectedDate0,
communityId: communityId,
spaceId: spaceId,
selectedDate: datePickerState.monthlyDate,
);
loadEnergyConsumptionByPhases(context, selectedDate: selectedDate);
loadEnergyConsumptionPerDevice(context);
loadRealtimeDeviceChanges(context);
loadPowerClampInfo(context);
return;
}
static void loadEnergyManagementData(BuildContext context) {
final (selectedCommunities, selectedSpaces) =
FetchEnergyManagementDataHelper.getSelectedCommunitiesAndSpaces(context);
if (selectedCommunities.isEmpty && selectedSpaces.isEmpty) return;
FetchEnergyManagementDataHelper.fetchEnergyManagementData(context,
selectedDate: DateTime.now());
FetchEnergyManagementDataHelper.loadRealtimeDeviceChanges(context);
context.read<PowerClampInfoBloc>().add(const ClearPowerClampInfoEvent());
if (selectedCommunities.isEmpty && selectedSpaces.isEmpty) {
context.read<PowerClampInfoBloc>().add(
const ClearPowerClampInfoEvent(),
);
} else {
FetchEnergyManagementDataHelper.loadPowerClampInfo(context);
}
}
static (List<String> selectedCommunities, List<String> selectedSpaces)
getSelectedCommunitiesAndSpaces(BuildContext context) {
final spaceTreeState = context.read<SpaceTreeBloc>().state;
final selectedCommunities = spaceTreeState.selectedCommunities;
final selectedSpaces = spaceTreeState.selectedSpaces;
return (selectedCommunities, selectedSpaces);
}
static void loadEnergyConsumptionByPhases(
@@ -59,12 +79,13 @@ abstract final class FetchEnergyManagementDataHelper {
static void loadTotalEnergyConsumption(
BuildContext context, {
DateTime? selectedDate,
required String communityId,
required String spaceId,
}) {
final (selectedCommunities, selectedSpaces) =
getSelectedCommunitiesAndSpaces(context);
final param = GetTotalEnergyConsumptionParam(
spaceId: spaceId,
communityId: communityId,
spaceId: selectedCommunities.firstOrNull,
communityId: selectedCommunities.firstOrNull,
monthDate: selectedDate,
);
context.read<TotalEnergyConsumptionBloc>().add(
@@ -81,13 +102,13 @@ abstract final class FetchEnergyManagementDataHelper {
static void loadPowerClampInfo(BuildContext context) {
context.read<PowerClampInfoBloc>().add(
const LoadPowerClampInfoEvent(_powerClampId),
const LoadPowerClampInfoEvent('cb71d6ad-6e29-4eaa-ae3e-1a0d1c5f60fa'),
);
}
static void loadRealtimeDeviceChanges(BuildContext context) {
context.read<RealtimeDeviceChangesBloc>().add(
const RealtimeDeviceChangesStarted(_powerClampId),
const RealtimeDeviceChangesStarted('cb71d6ad-6e29-4eaa-ae3e-1a0d1c5f60fa'),
);
}
@@ -99,7 +120,6 @@ abstract final class FetchEnergyManagementDataHelper {
context.read<PowerClampInfoBloc>().add(
const ClearPowerClampInfoEvent(),
);
context.read<EnergyConsumptionPerDeviceBloc>().add(
const ClearEnergyConsumptionPerDeviceEvent(),
);
@@ -1,10 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/energy_consumption_per_device_chart_box.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/power_clamp_energy_data_widget.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/total_energy_consumption_chart_box.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
class AnalyticsEnergyManagementView extends StatefulWidget {
const AnalyticsEnergyManagementView({super.key});
@@ -18,14 +16,7 @@ class _AnalyticsEnergyManagementViewState
extends State<AnalyticsEnergyManagementView> {
@override
void initState() {
final spaceTreeBloc = context.read<SpaceTreeBloc>();
final communityId = spaceTreeBloc.state.selectedCommunities.firstOrNull;
final spaceId = spaceTreeBloc.state.selectedSpaces.firstOrNull;
FetchEnergyManagementDataHelper.loadEnergyManagementData(
context,
communityId: communityId ?? '',
spaceId: spaceId ?? '',
);
FetchEnergyManagementDataHelper.loadEnergyManagementData(context);
super.initState();
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_date_picker_bloc/analytics_date_picker_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/blocs/occupancy/occupancy_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/blocs/occupancy_heat_map/occupancy_heat_map_bloc.dart';
import 'package:syncrow_web/pages/analytics/params/get_occupancy_heat_map_param.dart';
@@ -10,13 +11,17 @@ import 'package:syncrow_web/pages/analytics/params/get_occupancy_param.dart';
abstract final class FetchOccupancyDataHelper {
const FetchOccupancyDataHelper._();
static void loadOccupancyData(
BuildContext context, {
required String communityId,
required String spaceId,
}) {
if (communityId.isEmpty && spaceId.isEmpty) {
clearAllData(context);
static void loadOccupancyData(BuildContext context) {
final (selectedCommunities, selectedSpaces) =
FetchEnergyManagementDataHelper.getSelectedCommunitiesAndSpaces(context);
if (selectedCommunities.isEmpty && selectedSpaces.isEmpty) {
context.read<OccupancyBloc>().add(
const ClearOccupancyEvent(),
);
context.read<OccupancyHeatMapBloc>().add(
const ClearOccupancyHeatMapEvent(),
);
return;
}
final datePickerState = context.read<AnalyticsDatePickerBloc>().state;
@@ -26,8 +31,8 @@ abstract final class FetchOccupancyDataHelper {
GetOccupancyParam(
monthDate:
'${datePickerState.monthlyDate.year}-${datePickerState.monthlyDate.month}',
spaceUuid: spaceId,
communityUuid: communityId,
spaceUuid: selectedSpaces.firstOrNull,
communityUuid: selectedCommunities.first,
),
),
);
@@ -35,8 +40,9 @@ abstract final class FetchOccupancyDataHelper {
context.read<OccupancyHeatMapBloc>().add(
LoadOccupancyHeatMapEvent(
GetOccupancyHeatMapParam(
spaceId: spaceId,
communityId: communityId,
spaceId: selectedSpaces.isNotEmpty ? selectedSpaces.first : '',
communityId:
selectedCommunities.isNotEmpty ? selectedCommunities.first : '',
year: datePickerState.yearlyDate,
),
),
@@ -48,16 +54,4 @@ abstract final class FetchOccupancyDataHelper {
const RealtimeDeviceChangesStarted('14fe6e7e-47af-4a07-ae0a-7c4a26ef8135'),
);
}
static void clearAllData(BuildContext context) {
context.read<OccupancyBloc>().add(
const ClearOccupancyEvent(),
);
context.read<OccupancyHeatMapBloc>().add(
const ClearOccupancyHeatMapEvent(),
);
context.read<RealtimeDeviceChangesBloc>().add(
const RealtimeDeviceChangesClosed(),
);
}
}
@@ -1,13 +1,25 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_chart_box.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_end_side_bar.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_heat_map_box.dart';
class AnalyticsOccupancyView extends StatelessWidget {
class AnalyticsOccupancyView extends StatefulWidget {
const AnalyticsOccupancyView({super.key});
static const _padding = EdgeInsetsDirectional.all(32);
@override
State<AnalyticsOccupancyView> createState() => _AnalyticsOccupancyViewState();
}
class _AnalyticsOccupancyViewState extends State<AnalyticsOccupancyView> {
@override
void initState() {
FetchOccupancyDataHelper.loadOccupancyData(context);
super.initState();
}
@override
Widget build(BuildContext context) {
final height = MediaQuery.sizeOf(context).height;
@@ -16,7 +28,7 @@ class AnalyticsOccupancyView extends StatelessWidget {
final isMediumOrLess = constraints.maxWidth <= 900;
if (isMediumOrLess) {
return SingleChildScrollView(
padding: _padding,
padding: AnalyticsOccupancyView._padding,
child: Column(
spacing: 32,
children: [
@@ -30,7 +42,7 @@ class AnalyticsOccupancyView extends StatelessWidget {
return SingleChildScrollView(
child: Container(
padding: _padding,
padding: AnalyticsOccupancyView._padding,
height: height * 0.9,
child: const Row(
spacing: 32,
@@ -7,7 +7,6 @@ import 'package:syncrow_web/pages/analytics/modules/occupancy/blocs/occupancy/oc
import 'package:syncrow_web/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_chart.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_error_widget.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/style.dart';
class OccupancyChartBox extends StatelessWidget {
@@ -15,7 +14,6 @@ class OccupancyChartBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
final spaceTreeState = context.watch<SpaceTreeBloc>().state;
return BlocBuilder<OccupancyBloc, OccupancyState>(
builder: (context, state) {
return Container(
@@ -47,11 +45,7 @@ class OccupancyChartBox extends StatelessWidget {
context.read<AnalyticsDatePickerBloc>().add(
UpdateAnalyticsDatePickerEvent(montlyDate: value),
);
FetchOccupancyDataHelper.loadOccupancyData(
context,
communityId: spaceTreeState.selectedCommunities.firstOrNull ?? '',
spaceId: spaceTreeState.selectedSpaces.firstOrNull ?? '',
);
FetchOccupancyDataHelper.loadOccupancyData(context);
},
selectedDate: context
.watch<AnalyticsDatePickerBloc>()
@@ -7,7 +7,6 @@ import 'package:syncrow_web/pages/analytics/modules/occupancy/blocs/occupancy_he
import 'package:syncrow_web/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_heat_map.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_error_widget.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/style.dart';
class OccupancyHeatMapBox extends StatelessWidget {
@@ -15,7 +14,6 @@ class OccupancyHeatMapBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
final spaceTreeState = context.watch<SpaceTreeBloc>().state;
return BlocBuilder<OccupancyHeatMapBloc, OccupancyHeatMapState>(
builder: (context, state) {
return Container(
@@ -47,12 +45,7 @@ class OccupancyHeatMapBox extends StatelessWidget {
context.read<AnalyticsDatePickerBloc>().add(
UpdateAnalyticsDatePickerEvent(yearlyDate: value),
);
FetchOccupancyDataHelper.loadOccupancyData(
context,
communityId:
spaceTreeState.selectedCommunities.firstOrNull ?? '',
spaceId: spaceTreeState.selectedSpaces.firstOrNull ?? '',
);
FetchOccupancyDataHelper.loadOccupancyData(context);
},
datePickerType: DatePickerType.year,
selectedDate: context
+63 -12
View File
@@ -21,6 +21,7 @@ class DynamicTable extends StatefulWidget {
final List<String>? initialSelectedIds;
final int uuidIndex;
final Function(dynamic selectedRows)? onSelectionChanged;
final Function(int rowIndex)? onSettingsPressed;
const DynamicTable({
super.key,
required this.headers,
@@ -37,6 +38,7 @@ class DynamicTable extends StatefulWidget {
this.initialSelectedIds,
required this.uuidIndex,
this.onSelectionChanged,
this.onSettingsPressed,
});
@override
@@ -63,7 +65,8 @@ class _DynamicTableState extends State<DynamicTable> {
}
}
bool _compareListOfLists(List<List<dynamic>> oldList, List<List<dynamic>> newList) {
bool _compareListOfLists(
List<List<dynamic>> oldList, List<List<dynamic>> newList) {
// Check if the old and new lists are the same
if (oldList.length != newList.length) return false;
@@ -132,7 +135,8 @@ class _DynamicTableState extends State<DynamicTable> {
children: [
if (widget.withCheckBox) _buildSelectAllCheckbox(),
...List.generate(widget.headers.length, (index) {
return _buildTableHeaderCell(widget.headers[index], index);
return _buildTableHeaderCell(
widget.headers[index], index);
})
//...widget.headers.map((header) => _buildTableHeaderCell(header)),
],
@@ -153,11 +157,14 @@ class _DynamicTableState extends State<DynamicTable> {
height: 15,
),
Text(
widget.tableName == 'AccessManagement' ? 'No Password ' : 'No Devices',
widget.tableName == 'AccessManagement'
? 'No Password '
: 'No Devices',
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: ColorsManager.grayColor),
.copyWith(
color: ColorsManager.grayColor),
)
],
),
@@ -166,16 +173,28 @@ class _DynamicTableState extends State<DynamicTable> {
],
)
: Column(
children: List.generate(widget.data.length, (index) {
final row = widget.data[index];
children:
List.generate(widget.data.length, (rowIndex) {
final row = widget.data[rowIndex];
return Row(
children: [
if (widget.withCheckBox) _buildRowCheckbox(index, widget.size.height * 0.08),
...row.map((cell) => _buildTableCell(cell.toString(), widget.size.height * 0.08)),
if (widget.withCheckBox)
_buildRowCheckbox(
rowIndex, widget.size.height * 0.08),
...row.asMap().entries.map((entry) {
int columnIndex = entry.key;
dynamic cell = entry.value;
return _buildTableCell(
cell.toString(),
widget.size.height * 0.08,
rowIndex: rowIndex,
columnIndex: columnIndex,
);
}).toList(),
],
);
}),
),
)
],
),
),
@@ -196,7 +215,9 @@ class _DynamicTableState extends State<DynamicTable> {
),
child: Checkbox(
value: _selectAll,
onChanged: widget.withSelectAll && widget.data.isNotEmpty ? _toggleSelectAll : null,
onChanged: widget.withSelectAll && widget.data.isNotEmpty
? _toggleSelectAll
: null,
),
);
}
@@ -238,7 +259,9 @@ class _DynamicTableState extends State<DynamicTable> {
constraints: const BoxConstraints.expand(height: 40),
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: index == widget.headers.length - 1 ? 12 : 8.0, vertical: 4),
padding: EdgeInsets.symmetric(
horizontal: index == widget.headers.length - 1 ? 12 : 8.0,
vertical: 4),
child: Text(
title,
style: context.textTheme.titleSmall!.copyWith(
@@ -253,13 +276,23 @@ class _DynamicTableState extends State<DynamicTable> {
);
}
Widget _buildTableCell(String content, double size) {
Widget _buildTableCell(
String content,
double size, {
required int rowIndex,
required int columnIndex,
}) {
bool isBatteryLevel = content.endsWith('%');
double? batteryLevel;
if (isBatteryLevel) {
batteryLevel = double.tryParse(content.replaceAll('%', '').trim());
}
bool isSettingsColumn = widget.headers[columnIndex] == 'Settings';
if (isSettingsColumn) {
return _buildSettingsIcon(rowIndex, size);
}
Color? statusColor;
switch (content) {
@@ -311,4 +344,22 @@ class _DynamicTableState extends State<DynamicTable> {
),
);
}
Widget _buildSettingsIcon(int rowIndex, double size) {
return Container(
height: size,
padding: const EdgeInsets.all(5.0),
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: ColorsManager.boxDivider, width: 1.0),
),
color: Colors.white,
),
alignment: Alignment.center,
child: IconButton(
icon: SvgPicture.asset(Assets.settings),
onPressed: () => widget.onSettingsPressed?.call(rowIndex),
),
);
}
}
@@ -12,7 +12,6 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/one_gang_switch/
import 'package:syncrow_web/pages/routines/models/gang_switches/three_gang_switch/three_gang_switch.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/two_gang_switch/two_gang_switch.dart';
import 'package:syncrow_web/pages/routines/models/gateway.dart';
import 'package:syncrow_web/pages/routines/models/water_heater/water_heater_functions.dart';
import 'package:syncrow_web/pages/routines/models/wps/wps_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/ceiling_sensor/ceiling_sensor_helper.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
@@ -359,10 +358,7 @@ SOS
case 'NCPS':
return [
FlushPresenceDelayFunction(
deviceId: uuid ?? '',
deviceName: name ?? '',
type: 'IF',
),
deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF',),
FlushIlluminanceFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'),
@@ -382,17 +378,6 @@ SOS
FlushTriggerLevelFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'THEN'),
];
case 'WH':
return [
WHRestartStatusFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'),
WHSwitchFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'BOTH'),
TimerConfirmTimeFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'BOTH'),
BacklightFunction(
deviceId: uuid ?? '', deviceName: name ?? '', type: 'IF'),
];
default:
return [];
@@ -95,7 +95,7 @@ class DeviceManagementPage extends StatelessWidget with HelperResponsiveLayout {
return const RoutinesView();
}
if (state.createRoutineView) {
return CreateNewRoutineView();
return const CreateNewRoutineView();
}
return BlocBuilder<DeviceManagementBloc, DeviceManagementState>(
@@ -6,9 +6,11 @@ import 'package:syncrow_web/pages/common/filter/filter_widget.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/widgets/device_search_filters.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/device_settings_panel.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_batch_control_dialog.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_control_dialog.dart';
import 'package:syncrow_web/pages/space_tree/view/space_tree_view.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/format_date_time.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
import 'package:syncrow_web/utils/style.dart';
@@ -58,7 +60,8 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
'Low Battery ($lowBatteryCount)',
];
final buttonLabel = (selectedDevices.length > 1) ? 'Batch Control' : 'Control';
final buttonLabel =
(selectedDevices.length > 1) ? 'Batch Control' : 'Control';
return Row(
children: [
@@ -105,18 +108,23 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
if (selectedDevices.length == 1) {
showDialog(
context: context,
builder: (context) => DeviceControlDialog(
builder: (context) =>
DeviceControlDialog(
device: selectedDevices.first,
),
);
} else if (selectedDevices.length > 1) {
final productTypes = selectedDevices
.map((device) => device.productType)
.toSet();
} else if (selectedDevices.length >
1) {
final productTypes =
selectedDevices
.map((device) =>
device.productType)
.toSet();
if (productTypes.length == 1) {
showDialog(
context: context,
builder: (context) => DeviceBatchControlDialog(
builder: (context) =>
DeviceBatchControlDialog(
devices: selectedDevices,
),
);
@@ -130,7 +138,9 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: isControlButtonEnabled ? Colors.white : Colors.grey,
color: isControlButtonEnabled
? Colors.white
: Colors.grey,
),
),
),
@@ -166,29 +176,40 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
'Installation Date and Time',
'Status',
'Last Offline Date and Time',
'Settings'
],
data: devicesToShow.map((device) {
final combinedSpaceNames = device.spaces != null
? device.spaces!.map((space) => space.spaceName).join(' > ') +
? device.spaces!
.map((space) => space.spaceName)
.join(' > ') +
(device.community != null
? ' > ${device.community!.name}'
: '')
: (device.community != null ? device.community!.name : '');
: (device.community != null
? device.community!.name
: '');
return [
device.name ?? '',
device.productName ?? '',
device.uuid ?? '',
(device.spaces != null && device.spaces!.isNotEmpty)
(device.spaces != null &&
device.spaces!.isNotEmpty)
? device.spaces![0].spaceName
: '',
combinedSpaceNames,
device.batteryLevel != null ? '${device.batteryLevel}%' : '-',
formatDateTime(DateTime.fromMillisecondsSinceEpoch(
(device.createTime ?? 0) * 1000)),
device.batteryLevel != null
? '${device.batteryLevel}%'
: '-',
formatDateTime(
DateTime.fromMillisecondsSinceEpoch(
(device.createTime ?? 0) * 1000)),
device.online == true ? 'Online' : 'Offline',
formatDateTime(DateTime.fromMillisecondsSinceEpoch(
(device.updateTime ?? 0) * 1000)),
formatDateTime(
DateTime.fromMillisecondsSinceEpoch(
(device.updateTime ?? 0) * 1000)),
'Settings',
];
}).toList(),
onSelectionChanged: (selectedRows) {
@@ -202,6 +223,10 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
.map((device) => device.uuid!)
.toList(),
isEmpty: devicesToShow.isEmpty,
onSettingsPressed: (rowIndex) {
final device = devicesToShow[rowIndex];
showDeviceSettingsSidebar(context, device);
},
),
),
)
@@ -213,4 +238,37 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
},
);
}
void showDeviceSettingsSidebar(BuildContext context, AllDevicesModel device) {
showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: "Device Settings",
transitionDuration: const Duration(milliseconds: 300),
pageBuilder: (context, anim1, anim2) {
return Align(
alignment: Alignment.centerRight,
child: Material(
child: Container(
width: MediaQuery.of(context).size.width * 0.3,
color: ColorsManager.whiteColors,
child: DeviceSettingsPanel(
device: device,
onClose: () => Navigator.of(context).pop(),
),
),
),
);
},
transitionBuilder: (context, anim1, anim2, child) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(anim1),
child: child,
);
},
);
}
}
@@ -0,0 +1,182 @@
class DeviceInfoModel {
final int activeTime;
final String category;
final String categoryName;
final int createTime;
final String gatewayId;
final String icon;
final String ip;
final String lat;
final String localKey;
final String lon;
final String model;
final String name;
final String nodeId;
final bool online;
final String ownerId;
final String productName;
final bool sub;
final String timeZone;
final int updateTime;
final String uuid;
final String productUuid;
final String productType;
final String permissionType;
final String macAddress;
final Subspace subspace;
DeviceInfoModel({
required this.activeTime,
required this.category,
required this.categoryName,
required this.createTime,
required this.gatewayId,
required this.icon,
required this.ip,
required this.lat,
required this.localKey,
required this.lon,
required this.model,
required this.name,
required this.nodeId,
required this.online,
required this.ownerId,
required this.productName,
required this.sub,
required this.timeZone,
required this.updateTime,
required this.uuid,
required this.productUuid,
required this.productType,
required this.permissionType,
required this.macAddress,
required this.subspace,
});
factory DeviceInfoModel.fromJson(Map<String, dynamic> json) {
return DeviceInfoModel(
activeTime: json['activeTime'],
category: json['category'],
categoryName: json['categoryName'],
createTime: json['createTime'],
gatewayId: json['gatewayId'],
icon: json['icon'],
ip: json['ip'] ?? "",
lat: json['lat'],
localKey: json['localKey'],
lon: json['lon'],
model: json['model'],
name: json['name'],
nodeId: json['nodeId'],
online: json['online'],
ownerId: json['ownerId'],
productName: json['productName'],
sub: json['sub'],
timeZone: json['timeZone'],
updateTime: json['updateTime'],
uuid: json['uuid'],
productUuid: json['productUuid'],
productType: json['productType'],
permissionType: json['permissionType'] ?? '',
macAddress: json['macAddress'],
subspace: Subspace.fromJson(json['subspace']),
);
}
Map<String, dynamic> toJson() {
return {
'activeTime': activeTime,
'category': category,
'categoryName': categoryName,
'createTime': createTime,
'gatewayId': gatewayId,
'icon': icon,
'ip': ip,
'lat': lat,
'localKey': localKey,
'lon': lon,
'model': model,
'name': name,
'nodeId': nodeId,
'online': online,
'ownerId': ownerId,
'productName': productName,
'sub': sub,
'timeZone': timeZone,
'updateTime': updateTime,
'uuid': uuid,
'productUuid': productUuid,
'productType': productType,
'permissionType': permissionType,
'macAddress': macAddress,
'subspace': subspace.toJson(),
};
}
static DeviceInfoModel empty() {
return DeviceInfoModel(
activeTime: 0,
category: '',
categoryName: '',
createTime: 0,
gatewayId: '',
icon: '',
ip: '',
lat: '',
localKey: '',
lon: '',
model: '',
name: '',
nodeId: '',
online: false,
ownerId: '',
productName: '',
sub: false,
timeZone: '',
updateTime: 0,
uuid: '',
productUuid: '',
productType: '',
permissionType: '',
macAddress: '',
subspace: Subspace(
uuid: '',
createdAt: '',
updatedAt: '',
subspaceName: '',
),
);
}
}
class Subspace {
final String uuid;
final String createdAt;
final String updatedAt;
final String subspaceName;
Subspace({
required this.uuid,
required this.createdAt,
required this.updatedAt,
required this.subspaceName,
});
factory Subspace.fromJson(Map<String, dynamic> json) {
return Subspace(
uuid: json['uuid'],
createdAt: json['createdAt'],
updatedAt: json['updatedAt'],
subspaceName: json['subspaceName'],
);
}
Map<String, dynamic> toJson() {
return {
'uuid': uuid,
'createdAt': createdAt,
'updatedAt': updatedAt,
'subspaceName': subspaceName,
};
}
}
@@ -0,0 +1,149 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/device_info_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/sub_space_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';
import 'package:syncrow_web/utils/snack_bar.dart';
part 'setting_bloc_event.dart';
class SettingBlocBloc extends Bloc<SettingBlocEvent, DeviceSettingsState> {
final String deviceId;
SettingBlocBloc({
required this.deviceId,
}) : super(const SettingBlocInitial()) {
on<DeviceSettingInitialInfo>(fetchDeviceInfo);
on<SaveNameEvent>(saveName);
on<ChangeNameEvent>(_changeName);
on<DeleteDeviceEvent>(deleteDevice);
//on<FetchRoomsEvent>(_fetchRoomsAndDevices);
}
static String deviceName = '';
final TextEditingController nameController =
TextEditingController(text: deviceName);
List<SubSpaceModel> roomsList = [];
bool isEditingName = false;
bool _validateInputs() {
final nameError = fullNameValidator(nameController.text);
if (nameError != null) {
CustomSnackBar.displaySnackBar(nameError);
return true;
}
return false;
}
String? fullNameValidator(String? value) {
if (value == null) return 'name is required';
final withoutExtraSpaces = value.replaceAll(RegExp(r"\s+"), ' ').trim();
if (withoutExtraSpaces.length < 2 || withoutExtraSpaces.length > 30) {
return 'name must be between 2 and 30 characters long';
}
if (RegExp(r"/[^ a-zA-Z0-9-\']/").hasMatch(withoutExtraSpaces)) {
return 'Only alphanumeric characters, space, dash and single quote are allowed';
}
return null;
}
Future<void> saveName(
SaveNameEvent event, Emitter<DeviceSettingsState> emit) async {
if (_validateInputs()) return;
try {
emit(SettingLoadingState());
var response = await DevicesManagementApi.putDeviceName(
deviceId: deviceId, deviceName: nameController.text);
add(DeviceSettingInitialInfo());
CustomSnackBar.displaySnackBar('Save Successfully');
emit(UpdateSettingState(deviceName: nameController.text));
} catch (e) {
emit(ErrorState(message: e.toString()));
} finally {
// isSaving = false;
}
}
DeviceInfoModel deviceInfo = DeviceInfoModel(
activeTime: 0,
category: "",
categoryName: "",
createTime: 0,
gatewayId: "",
icon: "",
ip: "",
lat: "",
localKey: "",
lon: "",
model: "",
name: "",
nodeId: "",
online: false,
ownerId: "",
productName: "",
sub: false,
timeZone: "",
updateTime: 0,
uuid: "",
productUuid: "",
productType: "",
permissionType: "",
macAddress: "",
subspace: Subspace(
uuid: "",
createdAt: "",
updatedAt: "",
subspaceName: "",
),
);
Future fetchDeviceInfo(
DeviceSettingInitialInfo event, Emitter<DeviceSettingsState> emit) async {
try {
emit(SettingLoadingState());
var response = await DevicesManagementApi.getDeviceInfo(deviceId);
deviceInfo = DeviceInfoModel.fromJson(response);
nameController.text = deviceInfo.name;
emit(UpdateSettingState(
deviceName: nameController.text,
deviceInfo: deviceInfo,
));
} catch (e) {
emit(ErrorState(message: e.toString()));
}
}
bool editName = false;
final FocusNode focusNode = FocusNode();
void _changeName(ChangeNameEvent event, Emitter<DeviceSettingsState> emit) {
emit(SettingLoadingState());
editName = event.value!;
if (editName) {
Future.delayed(const Duration(milliseconds: 500), () {
focusNode.requestFocus();
});
} else {
add(const SaveNameEvent());
focusNode.unfocus();
}
emit(UpdateSettingState(deviceName: deviceName, deviceInfo: deviceInfo));
}
void deleteDevice(
DeleteDeviceEvent event, Emitter<DeviceSettingsState> emit) async {
try {
emit(SettingLoadingState());
var response =
await DevicesManagementApi.resetDevise(devicesUuid: deviceId);
CustomSnackBar.displaySnackBar('Reset Successfully');
emit(UpdateSettingState(
deviceName: nameController.text,
deviceInfo: deviceInfo,
));
} catch (e) {
emit(ErrorState(message: e.toString()));
return;
}
}
}
@@ -0,0 +1,50 @@
part of 'setting_bloc_bloc.dart';
abstract class SettingBlocEvent extends Equatable {
const SettingBlocEvent();
@override
List<Object?> get props => [];
}
class SaveDeviceName extends SettingBlocEvent {
final String deviceName;
final String deviceId;
const SaveDeviceName({required this.deviceName, required this.deviceId});
@override
List<Object?> get props => [deviceName, deviceId];
}
class StartEditingName extends SettingBlocEvent {}
class CancelEditingName extends SettingBlocEvent {}
class ChangeEditingNameValue extends SettingBlocEvent {
final String value;
const ChangeEditingNameValue(this.value);
@override
List<Object?> get props => [value];
}
class FetchRoomsEvent extends SettingBlocEvent {
final String deviceId;
const FetchRoomsEvent(this.deviceId);
@override
List<Object?> get props => [deviceId];
}
class SaveNameEvent extends SettingBlocEvent {
const SaveNameEvent();
}
class DeviceSettingInitialInfo extends SettingBlocEvent {}
class ChangeNameEvent extends SettingBlocEvent {
final bool? value;
const ChangeNameEvent({this.value});
}
class DeleteDeviceEvent extends SettingBlocEvent {}
@@ -0,0 +1,69 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/device_info_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/sub_space_model.dart';
abstract class DeviceSettingsState extends Equatable {
const DeviceSettingsState();
@override
List<Object?> get props => [];
}
class SettingBlocInitial extends DeviceSettingsState {
final String deviceName;
final String deviceId;
final bool isEditingName;
final String editingNameValue;
const SettingBlocInitial({
this.deviceName = '',
this.deviceId = '',
this.isEditingName = false,
this.editingNameValue = '',
});
SettingBlocInitial copyWith({
String? deviceName,
String? deviceId,
bool? isEditingName,
String? editingNameValue,
}) =>
SettingBlocInitial(
deviceName: deviceName ?? this.deviceName,
deviceId: deviceId ?? this.deviceId,
isEditingName: isEditingName ?? this.isEditingName,
editingNameValue: editingNameValue ?? this.editingNameValue,
);
@override
List<Object?> get props =>
[deviceName, deviceId, isEditingName, editingNameValue];
}
class SettingLoadingState extends DeviceSettingsState {}
class UpdateSettingState extends DeviceSettingsState {
final String deviceName;
final DeviceInfoModel? deviceInfo;
const UpdateSettingState({required this.deviceName, this.deviceInfo});
@override
List<Object?> get props => [deviceName, deviceInfo];
}
class ErrorState extends DeviceSettingsState {
final String message;
const ErrorState({required this.message});
@override
List<Object?> get props => [message];
}
class FetchRoomsState extends DeviceSettingsState {
final List<SubSpaceModel> roomsList;
const FetchRoomsState({required this.roomsList});
@override
List<Object?> get props => [roomsList];
}
@@ -0,0 +1,35 @@
import 'package:syncrow_web/pages/visitor_password/model/device_model.dart';
class SubSpaceModel {
final String? id;
final String? name;
List<DeviceModel>? devices;
SubSpaceModel({
required this.id,
required this.name,
required this.devices,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'devices': devices?.map((device) => device.toJson()).toList(),
};
}
factory SubSpaceModel.fromJson(Map<String, dynamic> json) {
List<DeviceModel> devices = [];
if (json['devices'] != null) {
for (var device in json['devices']) {
devices.add(DeviceModel.fromJson(device));
}
}
return SubSpaceModel(
id: json['uuid'],
name: json['subspaceName'],
devices: devices,
);
}
}
@@ -0,0 +1,267 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/device_info_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/web_layout/default_container.dart';
class DeviceSettingsPanel extends StatelessWidget {
final VoidCallback? onClose;
final AllDevicesModel device;
const DeviceSettingsPanel({this.onClose, super.key, required this.device});
@override
Widget build(BuildContext context) {
final sectionTitle = context.theme.textTheme.titleMedium!.copyWith(
fontWeight: FontWeight.bold,
color: ColorsManager.grayColor,
);
Widget infoRow(
{required String label, required String value, Widget? trailing}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: context.theme.textTheme.bodyMedium!.copyWith(
fontSize: 14,
color: ColorsManager.grayColor,
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.end,
style: context.theme.textTheme.bodyMedium!.copyWith(
fontSize: 14,
color: ColorsManager.blackColor,
),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
trailing ?? const SizedBox.shrink(),
],
),
);
}
return BlocProvider(
create: (context) => SettingBlocBloc(
deviceId: device.uuid ?? '',
)..add(DeviceSettingInitialInfo()),
child: BlocBuilder<SettingBlocBloc, DeviceSettingsState>(
builder: (context, state) {
final iconPath =
DeviceTypeHelper.getDeviceIconByTypeCode(device.productType);
final _bloc = BlocProvider.of<SettingBlocBloc>(context);
DeviceInfoModel deviceInfo = DeviceInfoModel.empty();
if (state is UpdateSettingState) {
deviceInfo = state.deviceInfo!;
}
return Container(
width: MediaQuery.of(context).size.width * 0.3,
color: ColorsManager.grey25,
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
child: ListView(
children: [
/// Header
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: SvgPicture.asset(Assets.closeSettingsIcon),
onPressed: onClose ?? () => Navigator.of(context).pop(),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Device Settings',
style: context.theme.textTheme.titleLarge!.copyWith(
fontWeight: FontWeight.bold,
color: ColorsManager.primaryColor)),
],
),
const SizedBox(height: 24),
/// Device Name + Icon
DefaultContainer(
child: Row(
children: [
CircleAvatar(
radius: 40,
backgroundColor:
const Color.fromARGB(177, 213, 213, 213),
child: CircleAvatar(
backgroundColor: ColorsManager.whiteColors,
radius: 36,
child: SvgPicture.asset(
iconPath,
fit: BoxFit.cover,
),
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
maxLength: 30,
style: const TextStyle(
color: ColorsManager.blackColor,
),
textAlign: TextAlign.center,
focusNode: _bloc.focusNode,
controller: _bloc.nameController,
enabled: _bloc.editName,
onFieldSubmitted: (value) {
_bloc.add(const ChangeNameEvent(value: false));
},
decoration: const InputDecoration(
border: InputBorder.none,
fillColor: Colors.white10,
counterText: '',
),
),
),
const SizedBox(width: 8),
_bloc.editName == true
? const SizedBox()
: GestureDetector(
onTap: () {
_bloc.add(const ChangeNameEvent(value: true));
},
child: SvgPicture.asset(
Assets.editNameIconSettings,
color: ColorsManager.grayColor,
height: 20,
width: 20,
),
),
],
),
),
const SizedBox(height: 32),
/// Device Management
Text('Device Management', style: sectionTitle),
DefaultContainer(
padding: EdgeInsets.zero,
child: Column(
children: [
const SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: infoRow(
label: 'Sub-Space:',
value: device.subspace!.subspaceName,
trailing: const Icon(
Icons.arrow_forward_ios,
size: 16,
color: ColorsManager.greyColor,
),
),
),
const Divider(color: ColorsManager.dividerColor),
Padding(
padding: const EdgeInsets.all(10.0),
child: infoRow(
label: 'Virtual Address:',
value: deviceInfo.productUuid,
trailing: InkWell(
onTap: () {
Clipboard.setData(
ClipboardData(text: device.productUuid ?? ''),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Virtual Address copied to clipboard'),
),
);
},
child: const Icon(
Icons.copy,
size: 16,
color: ColorsManager.greyColor,
),
),
),
),
const Divider(color: ColorsManager.dividerColor),
Padding(
padding: const EdgeInsets.all(10.0),
child: infoRow(
label: 'MAC Address:',
value: deviceInfo.macAddress),
),
const SizedBox(
height: 5,
),
],
),
),
const SizedBox(height: 32),
/// Remove Device Button
SizedBox(
width: double.infinity,
child: InkWell(
onTap: () {
_bloc.add(DeleteDeviceEvent());
},
child: const DefaultContainer(
padding: EdgeInsets.all(25),
child: Center(
child: Text(
'Remove Device',
style: TextStyle(color: ColorsManager.red),
),
),
),
),
)
],
),
);
}));
}
}
class DeviceTypeHelper {
static const Map<String, String> _iconMap = {
'AC': Assets.ac,
'GW': Assets.gateway,
'CPS': Assets.sensors,
'DL': Assets.doorLock,
'WPS': Assets.sensors,
'3G': Assets.gangSwitch,
'2G': Assets.twoGang,
'1G': Assets.oneGang,
'CUR': Assets.curtain,
'WH': Assets.waterHeater,
'DS': Assets.doorSensor,
'1GT': Assets.oneTouchSwitch,
'2GT': Assets.twoTouchSwitch,
'3GT': Assets.threeTouchSwitch,
'GD': Assets.garageDoor,
'WL': Assets.waterLeakNormal,
'NCPS': Assets.sensors,
};
static String getDeviceIconByTypeCode(String? typeCode) {
if (typeCode == null) return Assets.logoHorizontal;
return _iconMap[typeCode] ?? Assets.logoHorizontal;
}
}
@@ -26,10 +26,8 @@ class FunctionBloc extends Bloc<FunctionBlocEvent, FunctionBlocState> {
functionCode: event.functionData.functionCode,
operationName: event.functionData.operationName,
value: event.functionData.value ?? existingData.value,
valueDescription: event.functionData.valueDescription ??
existingData.valueDescription,
valueDescription: event.functionData.valueDescription ?? existingData.valueDescription,
condition: event.functionData.condition ?? existingData.condition,
step: event.functionData.step ?? existingData.step,
);
} else {
functions.clear();
@@ -61,10 +59,8 @@ class FunctionBloc extends Bloc<FunctionBlocEvent, FunctionBlocState> {
);
}
FutureOr<void> _onSelectFunction(
SelectFunction event, Emitter<FunctionBlocState> emit) {
FutureOr<void> _onSelectFunction(SelectFunction event, Emitter<FunctionBlocState> emit) {
emit(state.copyWith(
selectedFunction: event.functionCode,
selectedOperationName: event.operationName));
selectedFunction: event.functionCode, selectedOperationName: event.operationName));
}
}
@@ -536,7 +536,7 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
// 'entityId': 'tab_to_run',
// 'uniqueCustomId': const Uuid().v4(),
// 'deviceId': 'tab_to_run',
// 'title': 'Tap to run',
// 'title': 'Tab to run',
// 'productType': 'tab_to_run',
// 'imagePath': Assets.tabToRun,
// }
@@ -771,7 +771,7 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
'entityId': 'tab_to_run',
'uniqueCustomId': const Uuid().v4(),
'deviceId': 'tab_to_run',
'title': 'Tap to run',
'title': 'Tab to run',
'productType': 'tab_to_run',
'imagePath': Assets.tabToRun,
}
@@ -10,7 +10,6 @@ import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/one_gang_swit
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/three_gang_switch_dialog.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/two_gang_switch_dialog.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/wall_presence_sensor.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/water_heater/water_heater_presence_sensor.dart';
class DeviceDialogHelper {
static Future<Map<String, dynamic>?> showDeviceDialog({
@@ -127,15 +126,6 @@ class DeviceDialogHelper {
dialogType: dialogType,
device: data['device'],
);
case 'WH':
return WaterHeaterDialogRoutines.showWHFunctionsDialog(
context: context,
functions: functions,
uniqueCustomId: data['uniqueCustomId'],
deviceSelectedFunctions: deviceSelectedFunctions,
dialogType: dialogType,
device: data['device'],
);
default:
return null;
@@ -162,7 +162,7 @@ class SaveRoutineHelper {
width: 24,
height: 24,
),
title: const Text('Tap to run'),
title: const Text('Tab to run'),
),
if (state.isAutomation)
...state.ifItems.map((item) {
+17 -19
View File
@@ -14,10 +14,6 @@ abstract class ACFunction extends DeviceFunction<AcStatusModel> {
required super.operationName,
required super.icon,
required this.type,
super.step,
super.unit,
super.max,
super.min,
});
List<ACOperationalValue> getOperationalValues();
@@ -79,24 +75,26 @@ class ModeFunction extends ACFunction {
}
class TempSetFunction extends ACFunction {
TempSetFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) : super(
final int min;
final int max;
final int step;
TempSetFunction(
{required super.deviceId, required super.deviceName, required type})
: min = 160,
max = 300,
step = 1,
super(
code: 'temp_set',
operationName: 'Set Temperature',
icon: Assets.assetsTempreture,
min: 200,
max: 300,
step: 1,
unit: "°C",
type: type,
);
@override
List<ACOperationalValue> getOperationalValues() {
List<ACOperationalValue> values = [];
for (int temp = min!.toInt(); temp <= max!; temp += step!.toInt()) {
for (int temp = min; temp <= max; temp += step) {
values.add(ACOperationalValue(
icon: Assets.assetsTempreture,
description: "${temp / 10}°C",
@@ -106,6 +104,7 @@ class TempSetFunction extends ACFunction {
return values;
}
}
class LevelFunction extends ACFunction {
LevelFunction(
{required super.deviceId, required super.deviceName, required type})
@@ -167,10 +166,9 @@ class ChildLockFunction extends ACFunction {
}
class CurrentTempFunction extends ACFunction {
final double min;
final double max;
final double step;
final String unit = "°C";
final int min;
final int max;
final int step;
CurrentTempFunction(
{required super.deviceId, required super.deviceName, required type})
@@ -187,7 +185,7 @@ class CurrentTempFunction extends ACFunction {
@override
List<ACOperationalValue> getOperationalValues() {
List<ACOperationalValue> values = [];
for (int temp = min.toInt(); temp <= max; temp += step.toInt()) {
for (int temp = min; temp <= max; temp += step) {
values.add(ACOperationalValue(
icon: Assets.currentTemp,
description: "${temp / 10}°C",
@@ -6,12 +6,10 @@ class CpsOperationalValue {
final String description;
final dynamic value;
CpsOperationalValue({
required this.icon,
required this.description,
required this.value,
});
}
@@ -96,9 +94,9 @@ final class CpsSensitivityFunction extends CpsFunctions {
icon: Assets.sensitivity,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
static const _images = <String>[
Assets.sensitivityFeature1,
@@ -117,10 +115,10 @@ final class CpsSensitivityFunction extends CpsFunctions {
@override
List<CpsOperationalValue> getOperationalValues() {
final values = <CpsOperationalValue>[];
for (var value = min; value <= max; value += step.toInt()) {
for (var value = min; value <= max; value += step) {
values.add(
CpsOperationalValue(
icon: _images[value.toInt()],
icon: _images[value],
description: '$value',
value: value,
),
@@ -144,9 +142,9 @@ final class CpsMovingSpeedFunction extends CpsFunctions {
icon: Assets.speedoMeter,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
@override
List<CpsOperationalValue> getOperationalValues() {
@@ -175,9 +173,9 @@ final class CpsSpatialStaticValueFunction extends CpsFunctions {
icon: Assets.spatialStaticValue,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
@override
List<CpsOperationalValue> getOperationalValues() {
@@ -206,9 +204,9 @@ final class CpsSpatialMotionValueFunction extends CpsFunctions {
icon: Assets.spatialMotionValue,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
@override
List<CpsOperationalValue> getOperationalValues() {
@@ -377,9 +375,9 @@ final class CpsPresenceJudgementThrsholdFunction extends CpsFunctions {
icon: Assets.presenceJudgementThrshold,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
@override
List<CpsOperationalValue> getOperationalValues() {
@@ -408,9 +406,9 @@ final class CpsMotionAmplitudeTriggerThresholdFunction extends CpsFunctions {
icon: Assets.presenceJudgementThrshold,
);
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
@override
List<CpsOperationalValue> getOperationalValues() {
@@ -4,11 +4,6 @@ abstract class DeviceFunction<T> {
final String code;
final String operationName;
final String icon;
final double? step;
final String? unit;
final double? max;
final double? min;
DeviceFunction({
required this.deviceId,
@@ -16,10 +11,6 @@ abstract class DeviceFunction<T> {
required this.code,
required this.operationName,
required this.icon,
this.step,
this.unit,
this.max,
this.min,
});
}
@@ -31,10 +22,6 @@ class DeviceFunctionData {
final dynamic value;
final String? condition;
final String? valueDescription;
final double? step;
final String? unit;
final double? max;
final double? min;
DeviceFunctionData({
required this.entityId,
@@ -44,10 +31,6 @@ class DeviceFunctionData {
required this.value,
this.condition,
this.valueDescription,
this.step,
this.unit,
this.max,
this.min,
});
Map<String, dynamic> toJson() {
@@ -59,10 +42,6 @@ class DeviceFunctionData {
'value': value,
if (condition != null) 'condition': condition,
if (valueDescription != null) 'valueDescription': valueDescription,
if (step != null) 'step': step,
if (unit != null) 'unit': unit,
if (max != null) 'max': max,
if (min != null) 'min': min,
};
}
@@ -75,10 +54,6 @@ class DeviceFunctionData {
value: json['value'],
condition: json['condition'],
valueDescription: json['valueDescription'],
step: json['step']?.toDouble(),
unit: json['unit'],
max: json['max']?.toDouble(),
min: json['min']?.toDouble(),
);
}
@@ -93,11 +68,7 @@ class DeviceFunctionData {
other.operationName == operationName &&
other.value == value &&
other.condition == condition &&
other.valueDescription == valueDescription &&
other.step == step &&
other.unit == unit &&
other.max == max &&
other.min == min;
other.valueDescription == valueDescription;
}
@override
@@ -108,10 +79,6 @@ class DeviceFunctionData {
operationName.hashCode ^
value.hashCode ^
condition.hashCode ^
valueDescription.hashCode ^
step.hashCode ^
unit.hashCode ^
max.hashCode ^
min.hashCode;
valueDescription.hashCode;
}
}
@@ -20,11 +20,12 @@ abstract class FlushFunctions
}
class FlushPresenceDelayFunction extends FlushFunctions {
final int min;
FlushPresenceDelayFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) :
}) : min = 0,
super(
code: FlushMountedPresenceSensorModel.codePresenceState,
operationName: 'Presence State',
@@ -49,9 +50,9 @@ class FlushPresenceDelayFunction extends FlushFunctions {
}
class FlushSensiReduceFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
FlushSensiReduceFunction({
required super.deviceId,
@@ -79,8 +80,8 @@ class FlushSensiReduceFunction extends FlushFunctions {
}
class FlushNoneDelayFunction extends FlushFunctions {
final double min;
final double max;
final int min;
final int max;
final String unit;
FlushNoneDelayFunction({
@@ -109,9 +110,9 @@ class FlushNoneDelayFunction extends FlushFunctions {
}
class FlushIlluminanceFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
FlushIlluminanceFunction({
required super.deviceId,
@@ -129,7 +130,7 @@ class FlushIlluminanceFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
List<FlushOperationalValue> values = [];
for (int lux = min.toInt(); lux <= max; lux += step.toInt()) {
for (int lux = min; lux <= max; lux += step) {
values.add(FlushOperationalValue(
icon: Assets.IlluminanceIcon,
description: "$lux Lux",
@@ -141,9 +142,9 @@ class FlushIlluminanceFunction extends FlushFunctions {
}
class FlushOccurDistReduceFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
FlushOccurDistReduceFunction({
required super.deviceId,
@@ -172,9 +173,9 @@ class FlushOccurDistReduceFunction extends FlushFunctions {
// ==== then functions ====
class FlushSensitivityFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
FlushSensitivityFunction({
required super.deviceId,
@@ -202,9 +203,9 @@ class FlushSensitivityFunction extends FlushFunctions {
}
class FlushNearDetectionFunction extends FlushFunctions {
final double min;
final int min;
final double max;
final double step;
final int step;
final String unit;
FlushNearDetectionFunction({
@@ -224,7 +225,7 @@ class FlushNearDetectionFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min.toDouble(); value <= max; value += step) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -236,9 +237,9 @@ class FlushNearDetectionFunction extends FlushFunctions {
}
class FlushMaxDetectDistFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
FlushMaxDetectDistFunction({
@@ -258,7 +259,7 @@ class FlushMaxDetectDistFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min; value <= max; value += step.toInt()) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -270,9 +271,9 @@ class FlushMaxDetectDistFunction extends FlushFunctions {
}
class FlushTargetConfirmTimeFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
FlushTargetConfirmTimeFunction({
@@ -292,7 +293,7 @@ class FlushTargetConfirmTimeFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min.toDouble(); value <= max; value += step) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -304,9 +305,9 @@ class FlushTargetConfirmTimeFunction extends FlushFunctions {
}
class FlushDisappeDelayFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
FlushDisappeDelayFunction({
@@ -326,7 +327,7 @@ class FlushDisappeDelayFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min.toDouble(); value <= max; value += step) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -338,9 +339,9 @@ class FlushDisappeDelayFunction extends FlushFunctions {
}
class FlushIndentLevelFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
FlushIndentLevelFunction({
@@ -360,7 +361,7 @@ class FlushIndentLevelFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min.toDouble(); value <= max; value += step) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -372,9 +373,9 @@ class FlushIndentLevelFunction extends FlushFunctions {
}
class FlushTriggerLevelFunction extends FlushFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
FlushTriggerLevelFunction({
@@ -394,7 +395,7 @@ class FlushTriggerLevelFunction extends FlushFunctions {
@override
List<FlushOperationalValue> getOperationalValues() {
final values = <FlushOperationalValue>[];
for (var value = min.toDouble(); value <= max; value += step) {
for (var value = min; value <= max; value += step) {
values.add(FlushOperationalValue(
icon: Assets.nobodyTime,
description: '$value $unit',
@@ -1,130 +0,0 @@
import 'package:syncrow_web/pages/device_managment/water_heater/models/water_heater_status_model.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/water_heater/water_heater_operational_value.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
abstract class WaterHeaterFunctions
extends DeviceFunction<WaterHeaterStatusModel> {
final String type;
WaterHeaterFunctions({
required super.deviceId,
required super.deviceName,
required super.code,
required super.operationName,
required super.icon,
required this.type,
});
List<WaterHeaterOperationalValue> getOperationalValues();
}
class WHRestartStatusFunction extends WaterHeaterFunctions {
WHRestartStatusFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) : super(
code: 'relay_status',
operationName: 'Restart Status',
icon: Assets.refreshStatusIcon,
);
@override
List<WaterHeaterOperationalValue> getOperationalValues() {
return [
WaterHeaterOperationalValue(
icon: Assets.assetsAcPowerOFF,
description: 'Power OFF',
value: "off",
),
WaterHeaterOperationalValue(
icon: Assets.assetsAcPower,
description: 'Power ON',
value: 'on',
),
WaterHeaterOperationalValue(
icon: Assets.refreshStatusIcon,
description: "Restart Memory",
value: 'memory',
),
];
}
}
class WHSwitchFunction extends WaterHeaterFunctions {
WHSwitchFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) : super(
code: 'switch_1',
operationName: 'Switch',
icon: Assets.assetsAcPower,
);
@override
List<WaterHeaterOperationalValue> getOperationalValues() {
return [
WaterHeaterOperationalValue(
icon: Assets.assetsAcPower,
description: 'ON',
value: true,
),
WaterHeaterOperationalValue(
icon: Assets.assetsAcPowerOFF,
description: 'OFF',
value: false,
),
];
}
}
class TimerConfirmTimeFunction extends WaterHeaterFunctions {
TimerConfirmTimeFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) : super(
code: 'countdown_1',
operationName: 'Timer',
icon: Assets.targetConfirmTimeIcon,
);
@override
List<WaterHeaterOperationalValue> getOperationalValues() {
final values = <WaterHeaterOperationalValue>[];
return values;
}
}
class BacklightFunction extends WaterHeaterFunctions {
BacklightFunction({
required super.deviceId,
required super.deviceName,
required super.type,
}) :
super(
code: 'switch_backlight',
operationName: 'Backlight',
icon: Assets.indicator,
);
@override
List<WaterHeaterOperationalValue> getOperationalValues() {
return [
WaterHeaterOperationalValue(
icon: Assets.assetsAcPower,
description: 'ON',
value: true,
),
WaterHeaterOperationalValue(
icon: Assets.assetsAcPowerOFF,
description: 'OFF',
value: false,
),
];
}
}
@@ -1,11 +0,0 @@
class WaterHeaterOperationalValue {
final String icon;
final String description;
final dynamic value;
WaterHeaterOperationalValue({
required this.icon,
required this.description,
required this.value,
});
}
@@ -4,7 +4,7 @@ import 'package:syncrow_web/pages/routines/models/wps/wps_operational_value.dart
import 'package:syncrow_web/utils/constants/assets.dart';
abstract class WpsFunctions extends DeviceFunction<WallSensorModel> {
final String type;
final String type;
WpsFunctions({
required super.deviceId,
@@ -13,10 +13,6 @@ abstract class WpsFunctions extends DeviceFunction<WallSensorModel> {
required super.operationName,
required super.icon,
required this.type,
super.step,
super.unit,
super.max,
super.min,
});
List<WpsOperationalValue> getOperationalValues();
@@ -24,13 +20,9 @@ abstract class WpsFunctions extends DeviceFunction<WallSensorModel> {
// For far_detection (75-600cm in 75cm steps)
class FarDetectionFunction extends WpsFunctions {
final double min;
@override
final double max;
@override
final double step;
@override
final int min;
final int max;
final int step;
final String unit;
FarDetectionFunction(
@@ -49,7 +41,7 @@ class FarDetectionFunction extends WpsFunctions {
@override
List<WpsOperationalValue> getOperationalValues() {
final values = <WpsOperationalValue>[];
for (var value = min; value <= max; value += step.toInt()) {
for (var value = min; value <= max; value += step) {
values.add(WpsOperationalValue(
icon: Assets.currentDistanceIcon,
description: '$value $unit',
@@ -62,9 +54,9 @@ class FarDetectionFunction extends WpsFunctions {
// For presence_time (0-65535 minutes)
class PresenceTimeFunction extends WpsFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
final String unit;
PresenceTimeFunction(
@@ -94,9 +86,9 @@ class PresenceTimeFunction extends WpsFunctions {
// For motion_sensitivity_value (1-5 levels)
class MotionSensitivityFunction extends WpsFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
MotionSensitivityFunction(
{required super.deviceId, required super.deviceName, required type})
@@ -124,9 +116,9 @@ class MotionSensitivityFunction extends WpsFunctions {
}
class MotionLessSensitivityFunction extends WpsFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
MotionLessSensitivityFunction(
{required super.deviceId, required super.deviceName, required type})
@@ -179,8 +171,8 @@ class IndicatorFunction extends WpsFunctions {
}
class NoOneTimeFunction extends WpsFunctions {
final double min;
final double max;
final int min;
final int max;
final String unit;
NoOneTimeFunction(
@@ -233,9 +225,9 @@ class PresenceStateFunction extends WpsFunctions {
}
class CurrentDistanceFunction extends WpsFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
CurrentDistanceFunction(
{required super.deviceId, required super.deviceName, required type})
@@ -252,10 +244,11 @@ class CurrentDistanceFunction extends WpsFunctions {
@override
List<WpsOperationalValue> getOperationalValues() {
List<WpsOperationalValue> values = [];
for (int cm = min.toInt(); cm <= max; cm += step.toInt()) {
for (int cm = min; cm <= max; cm += step) {
values.add(WpsOperationalValue(
icon: Assets.assetsTempreture,
description: "${cm}CM",
value: cm,
));
}
@@ -264,9 +257,9 @@ class CurrentDistanceFunction extends WpsFunctions {
}
class IlluminanceValueFunction extends WpsFunctions {
final double min;
final double max;
final double step;
final int min;
final int max;
final int step;
IlluminanceValueFunction({
required super.deviceId,
@@ -284,7 +277,7 @@ class IlluminanceValueFunction extends WpsFunctions {
@override
List<WpsOperationalValue> getOperationalValues() {
List<WpsOperationalValue> values = [];
for (int lux = min.toInt(); lux <= max; lux += step.toInt()) {
for (int lux = min; lux <= max; lux += step) {
values.add(WpsOperationalValue(
icon: Assets.IlluminanceIcon,
description: "$lux Lux",
@@ -29,11 +29,11 @@ class ConditionsRoutinesDevicesView extends StatelessWidget {
children: [
DraggableCard(
imagePath: Assets.tabToRun,
title: 'Tap to run',
title: 'Tab to run',
deviceData: {
'deviceId': 'tab_to_run',
'type': 'trigger',
'name': 'Tap to run',
'name': 'Tab to run',
},
),
DraggableCard(
@@ -1,297 +0,0 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:syncrow_web/pages/routines/widgets/condition_toggle.dart';
import 'package:syncrow_web/pages/routines/widgets/slider_value_selector.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class CustomRoutinesTextbox extends StatefulWidget {
final String? currentCondition;
final String dialogType;
final (double, double) sliderRange;
final dynamic displayedValue;
final dynamic initialValue;
final void Function(String condition) onConditionChanged;
final void Function(double value) onTextChanged;
final String unit;
final double dividendOfRange;
final double stepIncreaseAmount;
final bool withSpecialChar;
const CustomRoutinesTextbox({
required this.dialogType,
required this.sliderRange,
required this.displayedValue,
required this.initialValue,
required this.onConditionChanged,
required this.onTextChanged,
required this.currentCondition,
required this.unit,
required this.dividendOfRange,
required this.stepIncreaseAmount,
required this.withSpecialChar,
super.key,
});
@override
State<CustomRoutinesTextbox> createState() => _CustomRoutinesTextboxState();
}
class _CustomRoutinesTextboxState extends State<CustomRoutinesTextbox> {
late final TextEditingController _controller;
bool hasError = false;
String? errorMessage;
int getDecimalPlaces(double step) {
String stepStr = step.toString();
if (stepStr.contains('.')) {
List<String> parts = stepStr.split('.');
String decimalPart = parts[1];
decimalPart = decimalPart.replaceAll(RegExp(r'0+$'), '');
return decimalPart.isEmpty ? 0 : decimalPart.length;
} else {
return 0;
}
}
@override
void initState() {
super.initState();
int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount);
double initialValue;
if (widget.initialValue != null &&
widget.initialValue is num &&
(widget.initialValue as num) == 0) {
initialValue = 0.0;
} else {
initialValue = double.tryParse(widget.displayedValue) ?? 0.0;
}
_controller = TextEditingController(
text: initialValue.toStringAsFixed(decimalPlaces),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _validateInput(String value) {
final doubleValue = double.tryParse(value);
if (doubleValue == null) {
setState(() {
errorMessage = "Invalid number";
hasError = true;
});
return;
}
final min = widget.sliderRange.$1;
final max = widget.sliderRange.$2;
if (doubleValue < min) {
setState(() {
errorMessage = "Value must be at least $min";
hasError = true;
});
} else if (doubleValue > max) {
setState(() {
errorMessage = "Value must be at most $max";
hasError = true;
});
} else {
int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount);
int factor = pow(10, decimalPlaces).toInt();
int scaledStep = (widget.stepIncreaseAmount * factor).round();
int scaledValue = (doubleValue * factor).round();
if (scaledValue % scaledStep != 0) {
setState(() {
errorMessage = "must be a multiple of ${widget.stepIncreaseAmount}";
hasError = true;
});
} else {
setState(() {
errorMessage = null;
hasError = false;
});
}
}
}
@override
void didUpdateWidget(CustomRoutinesTextbox oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialValue != oldWidget.initialValue) {
if (widget.initialValue != null &&
widget.initialValue is num &&
(widget.initialValue as num) == 0) {
int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount);
_controller.text = 0.0.toStringAsFixed(decimalPlaces);
}
}
}
void _correctAndUpdateValue(String value) {
final doubleValue = double.tryParse(value) ?? 0.0;
int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount);
double rounded = (doubleValue / widget.stepIncreaseAmount).round() *
widget.stepIncreaseAmount;
rounded = rounded.clamp(widget.sliderRange.$1, widget.sliderRange.$2);
rounded = double.parse(rounded.toStringAsFixed(decimalPlaces));
setState(() {
hasError = false;
errorMessage = null;
});
_controller.text = rounded.toStringAsFixed(decimalPlaces);
_controller.selection = TextSelection.fromPosition(
TextPosition(offset: _controller.text.length),
);
widget.onTextChanged(rounded);
}
@override
Widget build(BuildContext context) {
int decimalPlaces = getDecimalPlaces(widget.stepIncreaseAmount);
List<TextInputFormatter> formatters = [];
if (decimalPlaces == 0) {
formatters.add(FilteringTextInputFormatter.digitsOnly);
} else {
formatters.add(FilteringTextInputFormatter.allow(
RegExp(r'^\d*\.?\d{0,' + decimalPlaces.toString() + r'}$'),
));
}
formatters.add(RangeInputFormatter(
min: widget.sliderRange.$1,
max: widget.sliderRange.$2,
));
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (widget.dialogType == 'IF')
ConditionToggle(
currentCondition: widget.currentCondition,
onChanged: widget.onConditionChanged,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35, vertical: 2),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'Step: ${widget.stepIncreaseAmount}',
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.grayColor,
fontSize: 10,
fontWeight: FontWeight.w400,
),
),
],
),
),
Center(
child: Container(
width: 170,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xFFF8F8F8),
borderRadius: BorderRadius.circular(20),
border: hasError
? Border.all(color: Colors.red, width: 1)
: Border.all(
color: ColorsManager.lightGrayBorderColor, width: 1),
boxShadow: [
BoxShadow(
color: ColorsManager.blackColor.withOpacity(0.05),
blurRadius: 8,
offset: const Offset(0, 4),
),
],
),
child: Row(
children: [
Expanded(
child: TextFormField(
controller: _controller,
style: context.textTheme.bodyLarge?.copyWith(
fontSize: 20,
fontWeight: FontWeight.bold,
color: ColorsManager.blackColor,
),
keyboardType: TextInputType.number,
inputFormatters: widget.withSpecialChar == true
? [FilteringTextInputFormatter.digitsOnly]
: null,
decoration: const InputDecoration(
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
onChanged: _validateInput,
onFieldSubmitted: _correctAndUpdateValue,
onTapOutside: (_) =>
_correctAndUpdateValue(_controller.text),
),
),
const SizedBox(width: 12),
Text(
widget.unit,
style: context.textTheme.bodyMedium?.copyWith(
fontSize: 20,
fontWeight: FontWeight.bold,
color: ColorsManager.vividBlue,
),
),
],
),
),
),
if (errorMessage != null)
Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Text(
errorMessage!,
style: context.textTheme.bodySmall?.copyWith(
color: Colors.red,
fontSize: 10,
),
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Min. ${widget.sliderRange.$1.toInt()}${widget.unit}',
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.grayColor,
fontSize: 10,
fontWeight: FontWeight.w400,
),
),
Text(
'Max. ${widget.sliderRange.$2.toInt()}${widget.unit}',
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.grayColor,
fontSize: 10,
fontWeight: FontWeight.w400,
),
),
],
),
),
const SizedBox(height: 16),
],
);
}
}
+3 -4
View File
@@ -43,7 +43,7 @@ class IfContainer extends StatelessWidget {
children: [
DraggableCard(
imagePath: Assets.tabToRun,
title: 'Tap to run',
title: 'Tab to run',
deviceData: {},
),
],
@@ -76,8 +76,7 @@ class IfContainer extends StatelessWidget {
'WPS',
'GW',
'CPS',
'NCPS',
'WH',
'NCPS'
].contains(state.ifItems[index]
['productType'])) {
@@ -137,7 +136,7 @@ class IfContainer extends StatelessWidget {
context
.read<RoutineBloc>()
.add(AddToIfContainer(mutableData, false));
} else if (!['AC', '1G', '2G', '3G', 'WPS', 'GW', 'CPS', 'NCPS','WH']
} else if (!['AC', '1G', '2G', '3G', 'WPS', 'GW', 'CPS', 'NCPS']
.contains(mutableData['productType'])) {
context
.read<RoutineBloc>()
@@ -26,7 +26,7 @@ class FetchRoutineScenesAutomation extends StatelessWidget
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildListTitle(context, "Scenes (Tap to Run)"),
_buildListTitle(context, "Scenes (Tab to Run)"),
const SizedBox(height: 10),
Visibility(
visible: state.scenes.isNotEmpty,
@@ -25,8 +25,7 @@ class _RoutineDevicesState extends State<RoutineDevices> {
'WPS',
'GW',
'CPS',
'NCPS',
'WH',
'NCPS'
};
@override
@@ -7,7 +7,6 @@ import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/ac/ac_function.dart';
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/widgets/custom_routines_textbox.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/routine_dialogs/helpers/routine_tap_function_helper.dart';
@@ -77,20 +76,24 @@ class ACHelper {
context: context,
acFunctions: acFunctions,
device: device,
onFunctionSelected:
(functionCode, operationName) {
onFunctionSelected: (functionCode, operationName) {
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: functionCode,
functionOperationName: operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'temp_set',
'temp_current',
],
defaultValue: 0);
context,
functionCode: functionCode,
functionOperationName: operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'temp_set',
'temp_current',
],
defaultValue: functionCode == 'temp_set'
? 200
: functionCode == 'temp_current'
? -100
: 0,
);
},
),
),
@@ -203,61 +206,27 @@ class ACHelper {
required String operationName,
bool? removeComparators,
}) {
final selectedFn =
acFunctions.firstWhere((f) => f.code == selectedFunction);
final initialVal = selectedFunction == 'temp_set' ? 200 : -100;
if (selectedFunction == 'temp_set' || selectedFunction == 'temp_current') {
// Convert stored integer value to display value
final displayValue =
(selectedFunctionData?.value ?? selectedFn.min ?? 0) / 10;
final minValue = selectedFn.min! / 10;
final maxValue = selectedFn.max! / 10;
return CustomRoutinesTextbox(
withSpecialChar: true,
dividendOfRange: maxValue,
final initialValue = selectedFunctionData?.value ?? initialVal;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
selectCode: selectedFunction,
currentCondition: selectedFunctionData?.condition,
dialogType: selectedFn.type,
sliderRange: (minValue, maxValue),
displayedValue: displayValue.toStringAsFixed(1),
initialValue: displayValue.toDouble(),
unit: selectedFn.unit!,
onConditionChanged: (condition) => context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectedFunction,
operationName: selectedFn.operationName,
condition: condition,
value: 0,
step: selectedFn.step,
unit: selectedFn.unit,
max: selectedFn.max,
min: selectedFn.min,
),
),
),
onTextChanged: (value) => context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectedFunction,
operationName: selectedFn.operationName,
value: (value * 10).round(), // Store as integer
condition: selectedFunctionData?.condition,
step: selectedFn.step,
unit: selectedFn.unit,
max: selectedFn.max,
min: selectedFn.min,
),
),
),
stepIncreaseAmount: selectedFn.step! / 10, // Convert step for display
device: device,
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparators: removeComparators,
);
}
final selectedFn = acFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
context: context,
values: selectedFn.getOperationalValues(),
values: values,
selectedValue: selectedFunctionData?.value,
device: device,
operationName: operationName,
@@ -266,151 +235,150 @@ class ACHelper {
);
}
// /// Build temperature selector for AC functions dialog
// static Widget _buildTemperatureSelector({
// required BuildContext context,
// required dynamic initialValue,
// required String? currentCondition,
// required String selectCode,
// AllDevicesModel? device,
// required String operationName,
// DeviceFunctionData? selectedFunctionData,
// bool? removeComparators,
// }) {
// return Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// if (removeComparators != true)
// _buildConditionToggle(
// context,
// currentCondition,
// selectCode,
// device,
// operationName,
// selectedFunctionData,
// ),
// const SizedBox(height: 20),
// _buildTemperatureDisplay(
// context,
// initialValue,
// device,
// operationName,
// selectedFunctionData,
// selectCode,
// ),
// const SizedBox(height: 20),
// _buildTemperatureSlider(
// context,
// initialValue,
// device,
// operationName,
// selectedFunctionData,
// selectCode,
// ),
// ],
// );
// }
/// Build temperature selector for AC functions dialog
static Widget _buildTemperatureSelector({
required BuildContext context,
required dynamic initialValue,
required String? currentCondition,
required String selectCode,
AllDevicesModel? device,
required String operationName,
DeviceFunctionData? selectedFunctionData,
bool? removeComparators,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (removeComparators != true)
_buildConditionToggle(
context,
currentCondition,
selectCode,
device,
operationName,
selectedFunctionData,
),
const SizedBox(height: 20),
_buildTemperatureDisplay(
context,
initialValue,
device,
operationName,
selectedFunctionData,
selectCode,
),
const SizedBox(height: 20),
_buildTemperatureSlider(
context,
initialValue,
device,
operationName,
selectedFunctionData,
selectCode,
),
],
);
}
// /// Build condition toggle for AC functions dialog
// static Widget _buildConditionToggle(
// BuildContext context,
// String? currentCondition,
// String selectCode,
// AllDevicesModel? device,
// String operationName,
// DeviceFunctionData? selectedFunctionData,
/// Build condition toggle for AC functions dialog
static Widget _buildConditionToggle(
BuildContext context,
String? currentCondition,
String selectCode,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
// // Function(String) onConditionChanged,
// ) {
// final conditions = ["<", "==", ">"];
// Function(String) onConditionChanged,
) {
final conditions = ["<", "==", ">"];
// return ToggleButtons(
// onPressed: (int index) {
// context.read<FunctionBloc>().add(
// AddFunction(
// functionData: DeviceFunctionData(
// entityId: device?.uuid ?? '',
// functionCode: selectCode,
// operationName: operationName,
// condition: conditions[index],
// value: selectedFunctionData?.value ?? selectCode == 'temp_set'
// ? 200
// : -100,
// valueDescription: selectedFunctionData?.valueDescription,
// ),
// ),
// );
// },
// borderRadius: const BorderRadius.all(Radius.circular(8)),
// selectedBorderColor: ColorsManager.primaryColorWithOpacity,
// selectedColor: Colors.white,
// fillColor: ColorsManager.primaryColorWithOpacity,
// color: ColorsManager.primaryColorWithOpacity,
// constraints: const BoxConstraints(
// minHeight: 40.0,
// minWidth: 40.0,
// ),
// isSelected:
// conditions.map((c) => c == (currentCondition ?? "==")).toList(),
// children: conditions.map((c) => Text(c)).toList(),
// );
// }
return ToggleButtons(
onPressed: (int index) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value ?? selectCode == 'temp_set'
? 200
: -100,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: ColorsManager.primaryColorWithOpacity,
selectedColor: Colors.white,
fillColor: ColorsManager.primaryColorWithOpacity,
color: ColorsManager.primaryColorWithOpacity,
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 40.0,
),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
// /// Build temperature display for AC functions dialog
// static Widget _buildTemperatureDisplay(
// BuildContext context,
// dynamic initialValue,
// AllDevicesModel? device,
// String operationName,
// DeviceFunctionData? selectedFunctionData,
// String selectCode,
// ) {
// final initialVal = selectCode == 'temp_set' ? 200 : -100;
// return Container(
// padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
// decoration: BoxDecoration(
// color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1),
// borderRadius: BorderRadius.circular(10),
// ),
// child: Text(
// '${(initialValue ?? initialVal) / 10}°C',
// style: context.textTheme.headlineMedium!.copyWith(
// color: ColorsManager.primaryColorWithOpacity,
// ),
// ),
// );
// }
/// Build temperature display for AC functions dialog
static Widget _buildTemperatureDisplay(
BuildContext context,
dynamic initialValue,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
final initialVal = selectCode == 'temp_set' ? 200 : -100;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'${(initialValue ?? initialVal) / 10}°C',
style: context.textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
),
),
);
}
// static Widget _buildTemperatureSlider(
// BuildContext context,
// dynamic initialValue,
// AllDevicesModel? device,
// String operationName,
// DeviceFunctionData? selectedFunctionData,
// String selectCode,
// ) {
// return Slider(
// value: initialValue is int ? initialValue.toDouble() : 200.0,
// min: selectCode == 'temp_current' ? -100 : 200,
// max: selectCode == 'temp_current' ? 900 : 300,
// divisions: 10,
// label: '${((initialValue ?? 160) / 10).toInt()}°C',
// onChanged: (value) {
// context.read<FunctionBloc>().add(
// AddFunction(
// functionData: DeviceFunctionData(
// entityId: device?.uuid ?? '',
// functionCode: selectCode,
// operationName: operationName,
// value: value,
// condition: selectedFunctionData?.condition,
// valueDescription: selectedFunctionData?.valueDescription,
// ),
// ),
// );
// },
// );
// }
static Widget _buildTemperatureSlider(
BuildContext context,
dynamic initialValue,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
return Slider(
value: initialValue is int ? initialValue.toDouble() : 200.0,
min: selectCode == 'temp_current' ? -100 : 200,
max: selectCode == 'temp_current' ? 900 : 300,
divisions: 10,
label: '${((initialValue ?? 160) / 10).toInt()}°C',
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: value,
condition: selectedFunctionData?.condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
);
}
static Widget _buildOperationalValuesList({
required BuildContext context,
@@ -446,9 +414,7 @@ class ACHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@@ -464,8 +430,7 @@ class ACHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
@@ -41,8 +41,7 @@ class _CeilingSensorDialogState extends State<CeilingSensorDialog> {
void initState() {
super.initState();
_cpsFunctions =
widget.functions.whereType<CpsFunctions>().where((function) {
_cpsFunctions = widget.functions.whereType<CpsFunctions>().where((function) {
if (widget.dialogType == 'THEN') {
return function.type == 'THEN' || function.type == 'BOTH';
}
@@ -150,7 +149,6 @@ class _CeilingSensorDialogState extends State<CeilingSensorDialog> {
device: widget.device,
)
: CpsDialogSliderSelector(
step: selectedCpsFunctions.step!,
operations: operations,
selectedFunction: selectedFunction ?? '',
selectedFunctionData: selectedFunctionData,
@@ -4,7 +4,6 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_mo
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/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/ceiling_sensor/cps_slider_helpers.dart';
import 'package:syncrow_web/pages/routines/widgets/slider_value_selector.dart';
@@ -17,7 +16,6 @@ class CpsDialogSliderSelector extends StatelessWidget {
required this.device,
required this.operationName,
required this.dialogType,
required this.step,
super.key,
});
@@ -28,16 +26,13 @@ class CpsDialogSliderSelector extends StatelessWidget {
final AllDevicesModel? device;
final String operationName;
final String dialogType;
final double step;
@override
Widget build(BuildContext context) {
return CustomRoutinesTextbox(
withSpecialChar: false,
return SliderValueSelector(
currentCondition: selectedFunctionData.condition,
dialogType: dialogType,
sliderRange:
CpsSliderHelpers.sliderRange(selectedFunctionData.functionCode),
sliderRange: CpsSliderHelpers.sliderRange(selectedFunctionData.functionCode),
displayedValue: CpsSliderHelpers.displayText(
value: selectedFunctionData.value,
functionCode: selectedFunctionData.functionCode,
@@ -55,7 +50,7 @@ class CpsDialogSliderSelector extends StatelessWidget {
),
),
),
onTextChanged: (value) => context.read<FunctionBloc>().add(
onSliderChanged: (value) => context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
@@ -69,7 +64,6 @@ class CpsDialogSliderSelector extends StatelessWidget {
dividendOfRange: CpsSliderHelpers.dividendOfRange(
selectedFunctionData.functionCode,
),
stepIncreaseAmount: step,
);
}
}
@@ -34,33 +34,30 @@ class CpsFunctionsList extends StatelessWidget {
itemBuilder: (context, index) {
final function = cpsFunctions[index];
return RoutineDialogFunctionListTile(
iconPath: function.icon,
operationName: function.operationName,
onTap: () {
RoutineTapFunctionHelper.onTapFunction(
context,
step: function.step,
functionCode: function.code,
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',
],
);
});
iconPath: function.icon,
operationName: function.operationName,
onTap: () => RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
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',
],
),
);
},
),
);
@@ -1,7 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.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/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/flush/flush_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/time_wheel.dart';
class FlushOperationalValuesList extends StatelessWidget {
final List<FlushOperationalValue> values;
@@ -22,20 +26,22 @@ class FlushOperationalValuesList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.all(20),
itemCount: values.length,
itemBuilder: (context, index) => _buildValueItem(context, values[index]),
);
return ListView.builder(
padding: const EdgeInsets.all(20),
itemCount: values.length,
itemBuilder: (context, index) =>
_buildValueItem(context, values[index]),
);
}
Widget _buildValueItem(BuildContext context, FlushOperationalValue value) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SvgPicture.asset(value.icon, width: 25, height: 25),
Expanded(child: _buildValueDescription(value)),
_buildValueRadio(context, value),
],
@@ -43,6 +49,9 @@ class FlushOperationalValuesList extends StatelessWidget {
);
}
Widget _buildValueDescription(FlushOperationalValue value) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
@@ -56,4 +65,6 @@ class FlushOperationalValuesList extends StatelessWidget {
groupValue: selectedValue,
onChanged: (_) => onSelect(value));
}
}
@@ -5,7 +5,6 @@ import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/flush/flush_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/flush_presence_sensor/flush_operational_values_list.dart';
import 'package:syncrow_web/pages/routines/widgets/slider_value_selector.dart';
@@ -67,8 +66,7 @@ class FlushValueSelectorWidget extends StatelessWidget {
if (isDistanceDetection) {
initialValue = initialValue / 100;
}
return CustomRoutinesTextbox(
withSpecialChar: true,
return SliderValueSelector(
currentCondition: functionData.condition,
dialogType: dialogType,
sliderRange: sliderRange,
@@ -85,7 +83,7 @@ class FlushValueSelectorWidget extends StatelessWidget {
),
),
),
onTextChanged: (value) {
onSliderChanged: (value) {
final roundedValue = _roundToStep(value, stepSize);
final finalValue =
isDistanceDetection ? (roundedValue * 100).toInt() : roundedValue;
@@ -104,7 +102,6 @@ class FlushValueSelectorWidget extends StatelessWidget {
},
unit: _unit,
dividendOfRange: stepSize,
stepIncreaseAmount: stepSize,
);
}
@@ -8,7 +8,6 @@ abstract final class RoutineTapFunctionHelper {
static void onTapFunction(
BuildContext context, {
double? step,
required String functionCode,
required String functionOperationName,
required String? functionValueDescription,
@@ -4,11 +4,11 @@ import 'package:flutter_svg/flutter_svg.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/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/helper/duration_format_helper.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_function.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/one_gang_switch/one_gang_switch.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.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/routine_dialogs/helpers/routine_tap_function_helper.dart';
@@ -87,15 +87,14 @@ class OneGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () => RoutineTapFunctionHelper
.onTapFunction(
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData
.valueDescription,
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
@@ -109,16 +108,14 @@ class OneGangSwitchHelper {
if (selectedFunction != null)
Expanded(
child: _buildValueSelector(
context: context,
selectedFunction: selectedFunction,
selectedFunctionData:
selectedFunctionData,
acFunctions: oneGangFunctions,
device: device,
operationName:
selectedOperationName ?? '',
removeComparetors: removeComparetors,
dialogType: dialogType),
context: context,
selectedFunction: selectedFunction,
selectedFunctionData: selectedFunctionData,
acFunctions: oneGangFunctions,
device: device,
operationName: selectedOperationName ?? '',
removeComparetors: removeComparetors,
),
),
],
),
@@ -175,7 +172,6 @@ class OneGangSwitchHelper {
AllDevicesModel? device,
required String operationName,
required bool removeComparetors,
required String dialogType,
}) {
if (selectedFunction == 'countdown_1') {
final initialValue = selectedFunctionData?.value ?? 0;
@@ -188,7 +184,6 @@ class OneGangSwitchHelper {
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparetors: removeComparetors,
dialogType: dialogType,
);
}
final selectedFn = acFunctions.firstWhere(
@@ -221,18 +216,93 @@ class OneGangSwitchHelper {
required String operationName,
DeviceFunctionData? selectedFunctionData,
required bool removeComparetors,
String? dialogType,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (removeComparetors != true)
_buildConditionToggle(
context,
currentCondition,
selectCode,
device,
operationName,
selectedFunctionData,
),
const SizedBox(height: 20),
_buildCountDownDisplay(context, initialValue, device, operationName,
selectedFunctionData, selectCode),
const SizedBox(height: 20),
_buildCountDownSlider(context, initialValue, device, operationName,
selectedFunctionData, selectCode, dialogType!),
selectedFunctionData, selectCode),
],
);
}
/// Build condition toggle for AC functions dialog
static Widget _buildConditionToggle(
BuildContext context,
String? currentCondition,
String selectCode,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
// Function(String) onConditionChanged,
) {
final conditions = ["<", "==", ">"];
return ToggleButtons(
onPressed: (int index) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: ColorsManager.primaryColorWithOpacity,
selectedColor: Colors.white,
fillColor: ColorsManager.primaryColorWithOpacity,
color: ColorsManager.primaryColorWithOpacity,
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 40.0,
),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
/// Build temperature display for AC functions dialog
static Widget _buildCountDownDisplay(
BuildContext context,
dynamic initialValue,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1),
borderRadius: BorderRadius.circular(10),
),
child: Text(
DurationFormatMixin.formatDuration(initialValue?.toInt() ?? 0),
style: context.textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
),
),
);
}
static Widget _buildCountDownSlider(
BuildContext context,
dynamic initialValue,
@@ -240,47 +310,38 @@ class OneGangSwitchHelper {
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
String dialogType,
) {
return CustomRoutinesTextbox(
withSpecialChar: false,
currentCondition: selectedFunctionData?.condition,
dialogType: dialogType,
sliderRange: (0, 43200),
displayedValue: (initialValue ?? 0).toString(),
initialValue: (initialValue ?? 0).toString(),
onConditionChanged: (condition) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: condition,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
onTextChanged: (value) {
final roundedValue = value.round();
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: roundedValue,
value: value,
condition: selectedFunctionData?.condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
unit: 'sec',
dividendOfRange: 1,
stepIncreaseAmount: 1,
);
}
@@ -316,9 +377,7 @@ class OneGangSwitchHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@@ -334,8 +393,7 @@ class OneGangSwitchHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
@@ -4,10 +4,10 @@ import 'package:flutter_svg/flutter_svg.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/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/helper/duration_format_helper.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_function.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.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/routine_dialogs/helpers/routine_tap_function_helper.dart';
@@ -86,21 +86,20 @@ class ThreeGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () => RoutineTapFunctionHelper
.onTapFunction(
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData
.valueDescription,
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue:
function.code
.startsWith('countdown')
? [function.code]
: [],
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
'countdown_2',
'countdown_3',
],
),
);
},
@@ -110,16 +109,14 @@ class ThreeGangSwitchHelper {
if (selectedFunction != null)
Expanded(
child: _buildValueSelector(
context: context,
selectedFunction: selectedFunction,
selectedFunctionData:
selectedFunctionData,
switchFunctions: switchFunctions,
device: device,
operationName:
selectedOperationName ?? '',
removeComparetors: removeComparetors,
dialogType: dialogType),
context: context,
selectedFunction: selectedFunction,
selectedFunctionData: selectedFunctionData,
switchFunctions: switchFunctions,
device: device,
operationName: selectedOperationName ?? '',
removeComparetors: removeComparetors,
),
),
],
),
@@ -136,6 +133,14 @@ class ThreeGangSwitchHelper {
onConfirm: state.addedFunctions.isNotEmpty
? () {
/// add the functions to the routine bloc
// for (var function in state.addedFunctions) {
// context.read<RoutineBloc>().add(
// AddFunctionToRoutine(
// function,
// uniqueCustomId,
// ),
// );
// }
context.read<RoutineBloc>().add(
AddFunctionToRoutine(
state.addedFunctions,
@@ -168,26 +173,24 @@ class ThreeGangSwitchHelper {
AllDevicesModel? device,
required String operationName,
required bool removeComparetors,
required String dialogType,
}) {
if (selectedFunction == 'countdown_1' ||
selectedFunction == 'countdown_2' ||
selectedFunction == 'countdown_3') {
final initialValue = selectedFunctionData?.value ?? 0;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
selectCode: selectedFunction,
currentCondition: selectedFunctionData?.condition,
device: device,
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparetors: removeComparetors,
dialogType: dialogType);
context: context,
initialValue: initialValue,
selectCode: selectedFunction,
currentCondition: selectedFunctionData?.condition,
device: device,
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparetors: removeComparetors,
);
}
final selectedFn =
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
@@ -210,18 +213,93 @@ class ThreeGangSwitchHelper {
required String operationName,
DeviceFunctionData? selectedFunctionData,
bool? removeComparetors,
required String dialogType,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (removeComparetors != true)
_buildConditionToggle(
context,
currentCondition,
selectCode,
device,
operationName,
selectedFunctionData,
),
const SizedBox(height: 20),
_buildCountDownDisplay(context, initialValue, device, operationName,
selectedFunctionData, selectCode),
const SizedBox(height: 20),
_buildCountDownSlider(context, initialValue, device, operationName,
selectedFunctionData, selectCode, dialogType),
selectedFunctionData, selectCode),
],
);
}
/// Build condition toggle for AC functions dialog
static Widget _buildConditionToggle(
BuildContext context,
String? currentCondition,
String selectCode,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
// Function(String) onConditionChanged,
) {
final conditions = ["<", "==", ">"];
return ToggleButtons(
onPressed: (int index) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: ColorsManager.primaryColorWithOpacity,
selectedColor: Colors.white,
fillColor: ColorsManager.primaryColorWithOpacity,
color: ColorsManager.primaryColorWithOpacity,
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 40.0,
),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
/// Build temperature display for AC functions dialog
static Widget _buildCountDownDisplay(
BuildContext context,
dynamic initialValue,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: ColorsManager.primaryColorWithOpacity.withOpacity(0.1),
borderRadius: BorderRadius.circular(10),
),
child: Text(
DurationFormatMixin.formatDuration(initialValue?.toInt() ?? 0),
style: context.textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
),
),
);
}
static Widget _buildCountDownSlider(
BuildContext context,
dynamic initialValue,
@@ -229,47 +307,38 @@ class ThreeGangSwitchHelper {
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
String dialogType,
) {
return CustomRoutinesTextbox(
withSpecialChar: true,
currentCondition: selectedFunctionData?.condition,
dialogType: dialogType,
sliderRange: (0, 43200),
displayedValue: (initialValue ?? 0).toString(),
initialValue: (initialValue ?? 0).toString(),
onConditionChanged: (condition) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: condition,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
onTextChanged: (value) {
final roundedValue = value.round();
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: roundedValue,
value: value,
condition: selectedFunctionData?.condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
unit: 'sec',
dividendOfRange: 1,
stepIncreaseAmount: 1,
);
}
@@ -305,9 +374,7 @@ class ThreeGangSwitchHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@@ -323,8 +390,7 @@ class ThreeGangSwitchHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
@@ -8,7 +8,6 @@ import 'package:syncrow_web/pages/routines/helper/duration_format_helper.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_function.dart';
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.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/routine_dialogs/helpers/routine_tap_function_helper.dart';
@@ -87,15 +86,14 @@ class TwoGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () => RoutineTapFunctionHelper
.onTapFunction(
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData
.valueDescription,
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
@@ -117,7 +115,6 @@ class TwoGangSwitchHelper {
device: device,
operationName: selectedOperationName ?? '',
removeComparetors: removeComparetors,
dialogType: dialogType,
),
),
],
@@ -175,25 +172,22 @@ class TwoGangSwitchHelper {
AllDevicesModel? device,
required String operationName,
required bool removeComparetors,
required String dialogType,
}) {
if (selectedFunction == 'countdown_1' ||
selectedFunction == 'countdown_2') {
if (selectedFunction == 'countdown_1' || selectedFunction == 'countdown_2') {
final initialValue = selectedFunctionData?.value ?? 0;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
selectCode: selectedFunction,
currentCondition: selectedFunctionData?.condition,
device: device,
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparetors: removeComparetors,
dialogType: dialogType);
context: context,
initialValue: initialValue,
selectCode: selectedFunction,
currentCondition: selectedFunctionData?.condition,
device: device,
operationName: operationName,
selectedFunctionData: selectedFunctionData,
removeComparetors: removeComparetors,
);
}
final selectedFn =
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
@@ -216,13 +210,25 @@ class TwoGangSwitchHelper {
required String operationName,
DeviceFunctionData? selectedFunctionData,
bool? removeComparetors,
String? dialogType,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (removeComparetors != true)
_buildConditionToggle(
context,
currentCondition,
selectCode,
device,
operationName,
selectedFunctionData,
),
const SizedBox(height: 20),
_buildCountDownDisplay(context, initialValue, device, operationName,
selectedFunctionData, selectCode),
const SizedBox(height: 20),
_buildCountDownSlider(context, initialValue, device, operationName,
selectedFunctionData, selectCode, dialogType!),
selectedFunctionData, selectCode),
],
);
}
@@ -263,8 +269,7 @@ class TwoGangSwitchHelper {
minHeight: 40.0,
minWidth: 40.0,
),
isSelected:
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
@@ -299,48 +304,38 @@ class TwoGangSwitchHelper {
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
String dialogType,
) {
return CustomRoutinesTextbox(
withSpecialChar: true,
currentCondition: selectedFunctionData?.condition,
dialogType: dialogType,
sliderRange: (0, 43200),
displayedValue: (initialValue ?? 0).toString(),
initialValue: (initialValue ?? 0).toString(),
onConditionChanged: (condition) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
condition: condition,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
onTextChanged: (value) {
final roundedValue =
value.round(); // Round to nearest integer (stepSize 1)
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: roundedValue,
value: value,
condition: selectedFunctionData?.condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
unit: 'sec',
dividendOfRange: 1,
stepIncreaseAmount: 1,
);
}
@@ -376,9 +371,7 @@ class TwoGangSwitchHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@@ -394,8 +387,7 @@ class TwoGangSwitchHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
@@ -4,8 +4,8 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_mo
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
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/widgets/custom_routines_textbox.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/wps_operational_values_list.dart';
import 'package:syncrow_web/pages/routines/widgets/slider_value_selector.dart';
class WpsValueSelectorWidget extends StatelessWidget {
final String selectedFunction;
@@ -27,13 +27,11 @@ class WpsValueSelectorWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final selectedFn =
wpsFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = wpsFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
if (_isSliderFunction(selectedFunction)) {
return CustomRoutinesTextbox(
withSpecialChar: false,
return SliderValueSelector(
currentCondition: functionData.condition,
dialogType: dialogType,
sliderRange: sliderRange,
@@ -50,7 +48,7 @@ class WpsValueSelectorWidget extends StatelessWidget {
),
),
),
onTextChanged: (value) => context.read<FunctionBloc>().add(
onSliderChanged: (value) => context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
@@ -63,7 +61,6 @@ class WpsValueSelectorWidget extends StatelessWidget {
),
unit: _unit,
dividendOfRange: 1,
stepIncreaseAmount: _steps,
);
}
@@ -102,10 +99,4 @@ class WpsValueSelectorWidget extends StatelessWidget {
'illuminance_value' => 'Lux',
_ => '',
};
double get _steps => switch (functionData.functionCode) {
'presence_time' => 1,
'dis_current' => 1,
'illuminance_value' => 1,
_ => 1,
};
}
@@ -1,65 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/models/water_heater/water_heater_operational_value.dart';
class WaterHeaterOperationalValuesList extends StatelessWidget {
final List<WaterHeaterOperationalValue> values;
final dynamic selectedValue;
final AllDevicesModel? device;
final String operationName;
final String selectCode;
final ValueChanged<WaterHeaterOperationalValue> onSelect;
const WaterHeaterOperationalValuesList({
required this.values,
required this.selectedValue,
required this.device,
required this.operationName,
required this.selectCode,
required this.onSelect,
super.key,
});
@override
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.all(20),
itemCount: values.length,
itemBuilder: (context, index) => _buildValueItem(context, values[index]),
);
}
Widget _buildValueItem(
BuildContext context, WaterHeaterOperationalValue value) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SvgPicture.asset(
value.icon,
width: 24,
height: 24,
),
Expanded(child: _buildValueDescription(value)),
_buildValueRadio(context, value),
],
),
);
}
Widget _buildValueDescription(WaterHeaterOperationalValue value) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Text(value.description),
);
}
Widget _buildValueRadio(context, WaterHeaterOperationalValue value) {
return Radio<dynamic>(
value: value.value,
groupValue: selectedValue,
onChanged: (_) => onSelect(value));
}
}
@@ -1,204 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.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/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/water_heater/water_heater_functions.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/routine_dialogs/water_heater/water_heater_value_selector_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class WaterHeaterDialogRoutines extends StatefulWidget {
final List<DeviceFunction> functions;
final AllDevicesModel? device;
final List<DeviceFunctionData>? deviceSelectedFunctions;
final String? uniqueCustomId;
final String dialogType;
const WaterHeaterDialogRoutines({
super.key,
required this.functions,
this.device,
this.deviceSelectedFunctions,
this.uniqueCustomId,
required this.dialogType,
});
static Future<Map<String, dynamic>?> showWHFunctionsDialog({
required BuildContext context,
required List<DeviceFunction> functions,
AllDevicesModel? device,
List<DeviceFunctionData>? deviceSelectedFunctions,
String? uniqueCustomId,
required String dialogType,
}) async {
return showDialog<Map<String, dynamic>?>(
context: context,
builder: (context) => WaterHeaterDialogRoutines(
functions: functions,
device: device,
deviceSelectedFunctions: deviceSelectedFunctions,
uniqueCustomId: uniqueCustomId,
dialogType: dialogType,
),
);
}
@override
State<WaterHeaterDialogRoutines> createState() =>
_WaterHeaterDialogRoutinesState();
}
class _WaterHeaterDialogRoutinesState extends State<WaterHeaterDialogRoutines> {
late final List<WaterHeaterFunctions> _waterHeaterFunctions;
@override
void initState() {
super.initState();
_waterHeaterFunctions =
widget.functions.whereType<WaterHeaterFunctions>().where((function) {
if (widget.dialogType == 'THEN') {
return function.type == 'THEN' || function.type == 'BOTH';
}
return function.type == 'IF' || function.type == 'BOTH';
}).toList();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => FunctionBloc()
..add(InitializeFunctions(widget.deviceSelectedFunctions ?? [])),
child: _buildDialogContent(),
);
}
Widget _buildDialogContent() {
return AlertDialog(
contentPadding: EdgeInsets.zero,
content: BlocBuilder<FunctionBloc, FunctionBlocState>(
builder: (context, state) {
final selectedFunction = state.selectedFunction;
return Container(
width: selectedFunction != null ? 600 : 360,
height: 450,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
),
padding: const EdgeInsets.only(top: 20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const DialogHeader('Water Heater Condition'),
Expanded(child: _buildMainContent(context, state)),
_buildDialogFooter(context, state),
],
),
);
},
),
);
}
Widget _buildMainContent(BuildContext context, FunctionBlocState state) {
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildFunctionList(context),
if (state.selectedFunction != null) _buildValueSelector(context, state),
],
);
}
Widget _buildFunctionList(BuildContext context) {
return SizedBox(
width: 360,
child: ListView.separated(
shrinkWrap: false,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: _waterHeaterFunctions.length,
separatorBuilder: (context, index) => const Padding(
padding: EdgeInsets.symmetric(horizontal: 40.0),
child: Divider(color: ColorsManager.dividerColor),
),
itemBuilder: (context, index) {
final function = _waterHeaterFunctions[index];
return ListTile(
leading: SvgPicture.asset(
function.icon,
width: 24,
height: 24,
placeholderBuilder: (context) => const SizedBox(
width: 24,
height: 24,
),
),
title: Text(
function.operationName,
style: context.textTheme.bodyMedium,
),
trailing: const Icon(
Icons.arrow_forward_ios,
size: 16,
color: ColorsManager.textGray,
),
onTap: () => context.read<FunctionBloc>().add(
SelectFunction(
functionCode: function.code,
operationName: function.operationName,
),
),
);
},
),
);
}
Widget _buildValueSelector(BuildContext context, FunctionBlocState state) {
final selectedFunction = state.selectedFunction ?? '';
final functionData = state.addedFunctions.firstWhere(
(f) => f.functionCode == selectedFunction,
orElse: () => DeviceFunctionData(
entityId: '',
functionCode: selectedFunction,
operationName: state.selectedOperationName ?? '',
value: null,
),
);
return Expanded(
child: WaterHeaterValueSelectorWidget(
selectedFunction: selectedFunction,
functionData: functionData,
whFunctions: _waterHeaterFunctions,
device: widget.device,
dialogType: widget.dialogType,
),
);
}
Widget _buildDialogFooter(BuildContext context, FunctionBlocState state) {
return DialogFooter(
onCancel: () => Navigator.pop(context),
onConfirm: state.addedFunctions.isNotEmpty
? () {
context.read<RoutineBloc>().add(
AddFunctionToRoutine(
state.addedFunctions,
widget.uniqueCustomId!,
),
);
Navigator.pop(
context,
{'deviceId': widget.functions.first.deviceId},
);
}
: null,
isConfirmEnabled: state.selectedFunction != null,
);
}
}
@@ -1,127 +0,0 @@
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/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/water_heater/water_heater_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/custom_routines_textbox.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/water_heater/water_heater_operational_values_list.dart';
class WaterHeaterValueSelectorWidget extends StatelessWidget {
final String selectedFunction;
final DeviceFunctionData functionData;
final List<WaterHeaterFunctions> whFunctions;
final AllDevicesModel? device;
final String dialogType;
const WaterHeaterValueSelectorWidget({
required this.selectedFunction,
required this.functionData,
required this.whFunctions,
required this.device,
required this.dialogType,
super.key,
});
@override
Widget build(BuildContext context) {
final selectedFn = whFunctions.firstWhere(
(f) => f.code == selectedFunction,
orElse: () => WHSwitchFunction(
deviceId: '',
deviceName: '',
type: '',
),
);
if (selectedFunction == 'countdown_1') {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildCountDownSlider(
context,
functionData.value,
device,
selectedFn.operationName,
functionData,
selectedFunction,
dialogType
),
const SizedBox(height: 10),
],
);
}
return WaterHeaterOperationalValuesList(
values: selectedFn.getOperationalValues(),
selectedValue: functionData.value,
device: device,
operationName: selectedFn.operationName,
selectCode: selectedFunction,
onSelect: (selectedValue) async {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectedFunction,
operationName: functionData.operationName,
value: selectedValue.value,
condition: functionData.condition,
),
),
);
},
);
}
static Widget _buildCountDownSlider(
BuildContext context,
dynamic initialValue,
AllDevicesModel? device,
String operationName,
DeviceFunctionData? selectedFunctionData,
String selectCode,
String dialogType,
) {
return CustomRoutinesTextbox(
withSpecialChar: false,
currentCondition: selectedFunctionData?.condition,
dialogType: dialogType,
sliderRange: (0, 43200),
displayedValue: (initialValue ?? 0).toString(),
initialValue: (initialValue ?? 0).toString(),
onConditionChanged: (condition) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: condition,
condition: condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
onTextChanged: (value) {
final roundedValue = value.round();
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: device?.uuid ?? '',
functionCode: selectCode,
operationName: operationName,
value: roundedValue,
condition: selectedFunctionData?.condition,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);
},
unit: 'sec',
dividendOfRange: 1,
stepIncreaseAmount: 1,
);
}
}
+3 -13
View File
@@ -116,8 +116,7 @@ class ThenContainer extends StatelessWidget {
'WPS',
'CPS',
"GW",
"NCPS",
'WH',
"NCPS"
].contains(state.thenItems[index]
['productType'])) {
context.read<RoutineBloc>().add(
@@ -233,17 +232,8 @@ class ThenContainer extends StatelessWidget {
dialogType: "THEN");
if (result != null) {
context.read<RoutineBloc>().add(AddToThenContainer(mutableData));
} else if (![
'AC',
'1G',
'2G',
'3G',
'WPS',
'GW',
'CPS',
"NCPS",
"WH"
].contains(mutableData['productType'])) {
} else if (!['AC', '1G', '2G', '3G', 'WPS', 'GW', 'CPS', "NCPS"]
.contains(mutableData['productType'])) {
context.read<RoutineBloc>().add(AddToThenContainer(mutableData));
}
},
+58 -7
View File
@@ -91,7 +91,8 @@ class DevicesManagementApi {
}
}
Future<bool> deviceBatchControl(List<String> uuids, String code, dynamic value) async {
Future<bool> deviceBatchControl(
List<String> uuids, String code, dynamic value) async {
try {
final body = {
'devicesUuid': uuids,
@@ -116,7 +117,8 @@ class DevicesManagementApi {
}
}
static Future<List<DeviceModel>> getDevicesByGatewayId(String gatewayId) async {
static Future<List<DeviceModel>> getDevicesByGatewayId(
String gatewayId) async {
final response = await HTTPService().get(
path: ApiEndpoints.gatewayApi.replaceAll('{gatewayUuid}', gatewayId),
showServerMessage: false,
@@ -150,7 +152,9 @@ class DevicesManagementApi {
String code,
) async {
final response = await HTTPService().get(
path: ApiEndpoints.getDeviceLogs.replaceAll('{uuid}', uuid).replaceAll('{code}', code),
path: ApiEndpoints.getDeviceLogs
.replaceAll('{uuid}', uuid)
.replaceAll('{code}', code),
showServerMessage: false,
expectedResponseModel: (json) {
return DeviceReport.fromJson(json['data']);
@@ -223,7 +227,8 @@ class DevicesManagementApi {
}
}
Future<bool> addScheduleRecord(ScheduleEntry sendSchedule, String uuid) async {
Future<bool> addScheduleRecord(
ScheduleEntry sendSchedule, String uuid) async {
try {
final response = await HTTPService().post(
path: ApiEndpoints.scheduleByDeviceId.replaceAll('{deviceUuid}', uuid),
@@ -240,7 +245,8 @@ class DevicesManagementApi {
}
}
Future<List<ScheduleModel>> getDeviceSchedules(String uuid, String category) async {
Future<List<ScheduleModel>> getDeviceSchedules(
String uuid, String category) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.getScheduleByDeviceId
@@ -263,7 +269,9 @@ class DevicesManagementApi {
}
Future<bool> updateScheduleRecord(
{required bool enable, required String uuid, required String scheduleId}) async {
{required bool enable,
required String uuid,
required String scheduleId}) async {
try {
final response = await HTTPService().put(
path: ApiEndpoints.updateScheduleByDeviceId
@@ -284,7 +292,8 @@ class DevicesManagementApi {
}
}
Future<bool> editScheduleRecord(String uuid, ScheduleEntry newSchedule) async {
Future<bool> editScheduleRecord(
String uuid, ScheduleEntry newSchedule) async {
try {
final response = await HTTPService().put(
path: ApiEndpoints.scheduleByDeviceId.replaceAll('{deviceUuid}', uuid),
@@ -335,4 +344,46 @@ class DevicesManagementApi {
return false;
}
}
static Future<Map<String, dynamic>> putDeviceName(
{required String deviceId, required String deviceName}) async {
try {
final response = await HTTPService().put(
path: ApiEndpoints.deviceByUuid.replaceAll('{deviceUuid}', deviceId),
body: {"deviceName": deviceName},
expectedResponseModel: (json) {
return json['data'];
},
);
return response;
} catch (e) {
rethrow;
}
}
static Future getDeviceInfo(String deviceId) async {
final response = await HTTPService().get(
path: ApiEndpoints.deviceByUuid.replaceAll('{deviceUuid}', deviceId),
showServerMessage: false,
expectedResponseModel: (json) {
return json['data'] as Map<String, dynamic>;
});
return response;
}
static Future resetDevise({
String? devicesUuid,
}) async {
final response = await HTTPService().post(
path: ApiEndpoints.resetDevice.replaceAll('{deviceUuid}', devicesUuid!),
showServerMessage: false,
body: {
"devicesUuid": [devicesUuid]
},
expectedResponseModel: (json) {
return json;
},
);
return response;
}
}
+71 -17
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/sub_space_model.dart';
import 'package:syncrow_web/pages/space_tree/model/pagination_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart';
@@ -12,14 +13,16 @@ import 'package:syncrow_web/utils/constants/api_const.dart';
class CommunitySpaceManagementApi {
// Community Management APIs
Future<List<CommunityModel>> fetchCommunities(String projectId, {int page = 1}) async {
Future<List<CommunityModel>> fetchCommunities(String projectId,
{int page = 1}) async {
try {
List<CommunityModel> allCommunities = [];
bool hasNext = true;
while (hasNext) {
await HTTPService().get(
path: ApiEndpoints.getCommunityList.replaceAll('{projectId}', projectId),
path: ApiEndpoints.getCommunityList
.replaceAll('{projectId}', projectId),
queryParameters: {
'page': page,
},
@@ -55,8 +58,14 @@ class CommunitySpaceManagementApi {
try {
bool hasNext = false;
await HTTPService().get(
path: ApiEndpoints.getCommunityList.replaceAll('{projectId}', projectId),
queryParameters: {'page': page, 'includeSpaces': true, 'size': 25, 'search': search},
path:
ApiEndpoints.getCommunityList.replaceAll('{projectId}', projectId),
queryParameters: {
'page': page,
'includeSpaces': true,
'size': 25,
'search': search
},
expectedResponseModel: (json) {
try {
List<dynamic> jsonData = json['data'] ?? [];
@@ -68,7 +77,10 @@ class CommunitySpaceManagementApi {
page = currentPage + 1;
paginationModel = PaginationModel(
pageNum: page, hasNext: hasNext, size: 25, communities: communityList);
pageNum: page,
hasNext: hasNext,
size: 25,
communities: communityList);
return paginationModel;
} catch (_) {
hasNext = false;
@@ -83,7 +95,8 @@ class CommunitySpaceManagementApi {
Future<CommunityModel?> getCommunityById(String communityId) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.getCommunityById.replaceAll('{communityId}', communityId),
path: ApiEndpoints.getCommunityById
.replaceAll('{communityId}', communityId),
expectedResponseModel: (json) {
return CommunityModel.fromJson(json['data']);
},
@@ -95,7 +108,8 @@ class CommunitySpaceManagementApi {
}
}
Future<CommunityModel?> createCommunity(String name, String description, String projectId) async {
Future<CommunityModel?> createCommunity(
String name, String description, String projectId) async {
try {
final response = await HTTPService().post(
path: ApiEndpoints.createCommunity.replaceAll('{projectId}', projectId),
@@ -114,7 +128,8 @@ class CommunitySpaceManagementApi {
}
}
Future<bool> updateCommunity(String communityId, String name, String projectId) async {
Future<bool> updateCommunity(
String communityId, String name, String projectId) async {
try {
final response = await HTTPService().put(
path: ApiEndpoints.updateCommunity
@@ -151,7 +166,8 @@ class CommunitySpaceManagementApi {
}
}
Future<SpacesResponse> fetchSpaces(String communityId, String projectId) async {
Future<SpacesResponse> fetchSpaces(
String communityId, String projectId) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.listSpaces
@@ -177,7 +193,8 @@ class CommunitySpaceManagementApi {
}
}
Future<SpaceModel?> getSpace(String communityId, String spaceId, String projectId) async {
Future<SpaceModel?> getSpace(
String communityId, String spaceId, String projectId) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.getSpace
@@ -289,7 +306,8 @@ class CommunitySpaceManagementApi {
}
}
Future<bool> deleteSpace(String communityId, String spaceId, String projectId) async {
Future<bool> deleteSpace(
String communityId, String spaceId, String projectId) async {
try {
final response = await HTTPService().delete(
path: ApiEndpoints.deleteSpace
@@ -307,15 +325,17 @@ class CommunitySpaceManagementApi {
}
}
Future<List<SpaceModel>> getSpaceHierarchy(String communityId, String projectId) async {
Future<List<SpaceModel>> getSpaceHierarchy(
String communityId, String projectId) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.getSpaceHierarchy
.replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', projectId),
expectedResponseModel: (json) {
final spaceModels =
(json['data'] as List).map((spaceJson) => SpaceModel.fromJson(spaceJson)).toList();
final spaceModels = (json['data'] as List)
.map((spaceJson) => SpaceModel.fromJson(spaceJson))
.toList();
return spaceModels;
},
@@ -327,15 +347,17 @@ class CommunitySpaceManagementApi {
}
}
Future<List<SpaceModel>> getSpaceOnlyWithDevices({String? communityId, String? projectId}) async {
Future<List<SpaceModel>> getSpaceOnlyWithDevices(
{String? communityId, String? projectId}) async {
try {
final response = await HTTPService().get(
path: ApiEndpoints.spaceOnlyWithDevices
.replaceAll('{communityId}', communityId!)
.replaceAll('{projectId}', projectId!),
expectedResponseModel: (json) {
final spaceModels =
(json['data'] as List).map((spaceJson) => SpaceModel.fromJson(spaceJson)).toList();
final spaceModels = (json['data'] as List)
.map((spaceJson) => SpaceModel.fromJson(spaceJson))
.toList();
return spaceModels;
},
);
@@ -345,4 +367,36 @@ class CommunitySpaceManagementApi {
return [];
}
}
static Future<List<SubSpaceModel>> getSubSpaceBySpaceId(
String communityId, String spaceId, String projectId) async {
try {
// Construct the API path
final path = ApiEndpoints.listSubspace
.replaceFirst('{communityUuid}', communityId)
.replaceFirst('{spaceUuid}', spaceId)
.replaceAll('{projectUuid}', projectId);
final response = await HTTPService().get(
path: path,
queryParameters: {"page": 1, "pageSize": 10},
showServerMessage: false,
expectedResponseModel: (json) {
List<SubSpaceModel> rooms = [];
if (json['data'] != null) {
for (var subspace in json['data']) {
rooms.add(SubSpaceModel.fromJson(subspace));
}
} else {
print("Warning: 'data' key is missing or null in response JSON.");
}
return rooms;
},
);
return response;
} catch (error, stackTrace) {
return []; // Return an empty list if there's an error
}
}
}
+2
View File
@@ -73,4 +73,6 @@ abstract class ColorsManager {
static const Color vividBlue = Color(0xFF023DFE);
static const Color semiTransparentRed = Color(0x99FF0000);
static const Color grey700 = Color(0xFF2D3748);
static const Color grey25 = Color(0xFFF9F9F9);
}
+12 -3
View File
@@ -60,9 +60,12 @@ abstract class ApiEndpoints {
'/devices/{uuid}/report-logs?code={code}&startTime={startTime}&endTime={endTime}';
static const String scheduleByDeviceId = '/schedule/{deviceUuid}';
static const String getScheduleByDeviceId = '/schedule/{deviceUuid}?category={category}';
static const String deleteScheduleByDeviceId = '/schedule/{deviceUuid}/{scheduleUuid}';
static const String updateScheduleByDeviceId = '/schedule/enable/{deviceUuid}';
static const String getScheduleByDeviceId =
'/schedule/{deviceUuid}?category={category}';
static const String deleteScheduleByDeviceId =
'/schedule/{deviceUuid}/{scheduleUuid}';
static const String updateScheduleByDeviceId =
'/schedule/enable/{deviceUuid}';
static const String factoryReset = '/devices/batch';
//product
@@ -124,4 +127,10 @@ abstract class ApiEndpoints {
'/projects/{projectId}/communities/{communityId}/spaces/{unitUuid}/automations';
static const String spaceOnlyWithDevices =
'/projects/{projectId}/communities/{communityId}/spaces?onlyWithDevices=true';
static const String listSubspace =
'/projects/{projectUuid}/communities/{communityUuid}/spaces/{spaceUuid}/subspaces';
static const String deviceByUuid = '/devices/{deviceUuid}';
static const String resetDevice = '/factory/reset/{deviceUuid}';
}
+5 -1
View File
@@ -481,5 +481,9 @@ class Assets {
static const String indentLevelIcon = 'assets/icons/indent_level_icon.svg';
static const String triggerLevelIcon = 'assets/icons/trigger_level_icon.svg';
static const String blankCalendar = 'assets/icons/blank_calendar.svg';
static const String refreshStatusIcon = 'assets/icons/refresh_status_icon.svg';
static const String closeSettingsIcon =
'assets/icons/close_settings_icon.svg';
static const String editNameIconSettings =
'assets/icons/edit_name_icon_settings.svg';
}
+45
View File
@@ -0,0 +1,45 @@
import 'package:flutter/material.dart';
class DefaultContainer extends StatelessWidget {
const DefaultContainer({
super.key,
required this.child,
this.height,
this.width,
this.color,
this.boxConstraints,
this.margin,
this.padding,
this.onTap,
this.borderRadius,
});
final double? height;
final double? width;
final Widget child;
final BoxConstraints? boxConstraints;
final EdgeInsets? margin;
final EdgeInsets? padding;
final Color? color;
final Function()? onTap;
final BorderRadius? borderRadius;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(20),
child: Container(
height: height,
width: width,
margin: margin ?? const EdgeInsets.only(right: 3, bottom: 3),
constraints: boxConstraints,
decoration: BoxDecoration(
color: color ?? Colors.white,
borderRadius: borderRadius ?? BorderRadius.circular(20),
),
padding: padding ?? const EdgeInsets.all(10),
child: child,
),
);
}
}