feat: revamp sensor add flow

This commit is contained in:
2026-05-16 12:00:55 +02:00
parent be6ac42059
commit f37176cce5
12 changed files with 478 additions and 186 deletions
@@ -5,10 +5,10 @@ import 'package:go_router/go_router.dart';
import '../../data/sources/ble/ble_provisioner.dart';
import '../../providers.dart';
enum _Step { provision, done }
enum _Step { scan, configure, done }
// Shared bottom sheet used by onboarding and the main sensor screens.
// Flow: scan select device → enter WiFi credentials → provision → place on map.
// Flow: scan -> select device (slides to configure) -> provision -> done.
class BleProvisionSheet extends ConsumerStatefulWidget {
const BleProvisionSheet({super.key});
@@ -20,10 +20,12 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
final _provisioner = BleProvisioner();
final _ssidController = TextEditingController();
final _wifiPasswordController = TextEditingController();
late final PageController _pageController;
late Stream<BleScanResult> _scanStream;
int _scanGeneration = 0;
_Step _step = _Step.provision;
_Step _step = _Step.scan;
BleScanResult? _selected;
bool _provisioning = false;
String? _error;
@@ -31,6 +33,7 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
@override
void initState() {
super.initState();
_pageController = PageController();
_scanStream = _provisioner.scan();
}
@@ -39,6 +42,7 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
_provisioner.dispose();
_ssidController.dispose();
_wifiPasswordController.dispose();
_pageController.dispose();
super.dispose();
}
@@ -57,7 +61,17 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
mqttHost: mqttBroker?.host,
mqttPort: mqttBroker?.port,
);
if (mounted) setState(() => _step = _Step.done);
await ref
.read(sensorRepositoryProvider)
.createSensor(_selected!.name, name: _selected!.name);
if (mounted) {
setState(() => _step = _Step.done);
_pageController.animateToPage(
2,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
} catch (e) {
if (mounted) setState(() => _error = e.toString());
} finally {
@@ -65,15 +79,46 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
}
}
void _selectDevice(BleScanResult r) {
setState(() {
_selected = r;
_step = _Step.configure;
});
_pageController.animateToPage(
1,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
void _goBack() {
setState(() {
_step = _Step.scan;
_selected = null;
_error = null;
_scanGeneration++;
});
_pageController.animateToPage(
0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
void _reset() {
setState(() {
_step = _Step.provision;
_step = _Step.scan;
_selected = null;
_error = null;
_ssidController.clear();
_wifiPasswordController.clear();
_scanStream = _provisioner.scan();
_scanGeneration++;
});
_pageController.animateToPage(
0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
@override
@@ -83,44 +128,185 @@ class _BleProvisionSheetState extends ConsumerState<BleProvisionSheet> {
initialChildSize: 0.6,
maxChildSize: 0.9,
builder: (context, scrollController) => Padding(
padding: EdgeInsets.fromLTRB(
24,
16,
24,
MediaQuery.of(context).viewInsets.bottom + 24,
),
child: _step == _Step.done
? _DoneStep(
onGoToFloorPlan: () {
final router = GoRouter.of(context);
Navigator.of(context).pop();
router.go('/floorplan');
},
onAddAnother: _reset,
onDone: () => Navigator.of(context).pop(),
)
: _ProvisionStep(
scrollController: scrollController,
scanStream: _scanStream,
selected: _selected,
onSelected: (r) => setState(() => _selected = r),
ssidController: _ssidController,
wifiPasswordController: _wifiPasswordController,
provisioning: _provisioning,
error: _error,
onProvision: _provision,
padding: const EdgeInsets.symmetric(horizontal: 0),
child: Column(
children: [
if (_step != _Step.done) ...[
Padding(
padding: const .fromLTRB(12, 12, 12, 0),
child: Column(
children: [
Padding(
padding: const .fromLTRB(0, 0, 12, 4),
child: Row(
children: [
if (_step == _Step.configure)
IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: _goBack,
)
else
const SizedBox(width: 0, height: 48),
Expanded(
child: Padding(
padding: const .only(left: 12),
child: Text(
_step == _Step.scan
? 'Add sensor'
: (_selected?.name ?? 'Configure'),
style: Theme.of(context).textTheme.titleLarge,
),
),
),
],
),
),
const Divider(height: 0),
],
),
),
],
Expanded(
child: PageView(
controller: _pageController,
physics: const NeverScrollableScrollPhysics(),
children:
[
_ScanPage(
scrollController: scrollController,
scanStream: _scanStream,
generation: _scanGeneration,
selected: _selected,
onSelected: _selectDevice,
),
_ConfigurePage(
ssidController: _ssidController,
wifiPasswordController: _wifiPasswordController,
provisioning: _provisioning,
error: _error,
onProvision: _provision,
),
_DoneStep(
onGoToFloorPlan: () {
final router = GoRouter.of(context);
Navigator.of(context).pop();
router.go('/floorplan');
},
onAddAnother: _reset,
onDone: () => Navigator.of(context).pop(),
),
]
.map(
(page) => Padding(
padding: const .symmetric(horizontal: 24),
child: page,
),
)
.toList(),
),
),
],
),
),
);
}
}
class _ProvisionStep extends StatefulWidget {
const _ProvisionStep({
class _ScanPage extends StatefulWidget {
const _ScanPage({
required this.scrollController,
required this.scanStream,
required this.generation,
required this.selected,
required this.onSelected,
});
final ScrollController scrollController;
final Stream<BleScanResult> scanStream;
final int generation;
final BleScanResult? selected;
final ValueChanged<BleScanResult> onSelected;
@override
State<_ScanPage> createState() => _ScanPageState();
}
class _ScanPageState extends State<_ScanPage>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
final _discovered = <String, BleScanResult>{};
@override
void didUpdateWidget(_ScanPage old) {
super.didUpdateWidget(old);
if (old.generation != widget.generation ||
old.scanStream != widget.scanStream) {
_discovered.clear();
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return StreamBuilder<BleScanResult>(
stream: widget.scanStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
_discovered[snapshot.data!.deviceId] = snapshot.data!;
}
return ListView(
controller: widget.scrollController,
padding: const EdgeInsets.only(top: 16, bottom: 24),
children: [
Row(
children: [
Text(
'Nearby sensor devices',
style: Theme.of(context).textTheme.labelLarge,
),
const SizedBox(width: 12),
const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 1.5),
),
],
),
const SizedBox(height: 4),
if (_discovered.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
'No devices found yet…',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
)
else
..._discovered.values.map((r) {
final selected = widget.selected?.deviceId == r.deviceId;
return ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.sensors),
title: Text(r.name),
subtitle: Text('${r.rssi} dBm'),
selected: selected,
onTap: () => widget.onSelected(r),
);
}),
],
);
},
);
}
}
class _ConfigurePage extends StatefulWidget {
const _ConfigurePage({
required this.ssidController,
required this.wifiPasswordController,
required this.provisioning,
@@ -128,10 +314,6 @@ class _ProvisionStep extends StatefulWidget {
required this.onProvision,
});
final ScrollController scrollController;
final Stream<BleScanResult> scanStream;
final BleScanResult? selected;
final ValueChanged<BleScanResult> onSelected;
final TextEditingController ssidController;
final TextEditingController wifiPasswordController;
final bool provisioning;
@@ -139,107 +321,83 @@ class _ProvisionStep extends StatefulWidget {
final VoidCallback onProvision;
@override
State<_ProvisionStep> createState() => _ProvisionStepState();
State<_ConfigurePage> createState() => _ConfigurePageState();
}
class _ProvisionStepState extends State<_ProvisionStep> {
final _discovered = <String, BleScanResult>{};
class _ConfigurePageState extends State<_ConfigurePage> {
bool _obscurePassword = true;
@override
Widget build(BuildContext context) {
return ListView(
controller: widget.scrollController,
children: [
Text('Add sensor', style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 16),
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
// scrollPadding ensures the field scrolls fully clear of the keyboard.
final fieldScrollPadding = EdgeInsets.only(bottom: bottomInset + 24);
Text('Nearby ESP32 devices',
style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 8),
StreamBuilder<BleScanResult>(
stream: widget.scanStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
final r = snapshot.data!;
_discovered[r.deviceId] = r;
}
if (_discovered.isEmpty) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Row(
children: [
SizedBox.square(
dimension: 16,
child: CircularProgressIndicator(strokeWidth: 2)),
SizedBox(width: 12),
Text('Scanning…'),
],
),
);
}
return Column(
children: _discovered.values.map((r) {
final selected = widget.selected?.deviceId == r.deviceId;
return ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.sensors),
title: Text(r.name),
subtitle: Text('${r.rssi} dBm'),
trailing: selected
? const Icon(Icons.check_circle,
color: Colors.green)
: null,
selected: selected,
onTap: () => widget.onSelected(r),
);
}).toList(),
);
},
),
const SizedBox(height: 24),
if (widget.selected != null) ...[
Text('Selected: ${widget.selected!.name}'),
const SizedBox(height: 16),
return SingleChildScrollView(
padding: EdgeInsets.only(top: 16, bottom: bottomInset + 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: widget.ssidController,
scrollPadding: fieldScrollPadding,
decoration: const InputDecoration(
labelText: 'WiFi SSID',
border: OutlineInputBorder(),
),
textInputAction: .next,
),
const SizedBox(height: 12),
TextField(
controller: widget.wifiPasswordController,
decoration: const InputDecoration(
labelText: 'WiFi password',
border: OutlineInputBorder(),
scrollPadding: fieldScrollPadding,
decoration: InputDecoration(
labelText: 'WiFi Password',
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off : Icons.visibility,
),
onPressed: () =>
setState(() => _obscurePassword = !_obscurePassword),
),
),
obscureText: true,
obscureText: _obscurePassword,
textInputAction: TextInputAction.done,
onSubmitted: (_) {
if (widget.ssidController.text.trim().isNotEmpty) {
widget.onProvision();
}
},
),
const SizedBox(height: 16),
],
if (widget.error != null)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(widget.error!,
style:
TextStyle(color: Theme.of(context).colorScheme.error)),
if (widget.error != null)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
widget.error!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
ListenableBuilder(
listenable: widget.ssidController,
builder: (context, _) {
final canProvision = widget.ssidController.text.trim().isNotEmpty;
return FilledButton(
onPressed: (widget.provisioning || !canProvision)
? null
: widget.onProvision,
child: widget.provisioning
? const SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Provision & add'),
);
},
),
FilledButton(
onPressed:
(widget.selected == null || widget.provisioning) ? null : widget.onProvision,
child: widget.provisioning
? const SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Provision & add'),
),
],
],
),
);
}
}
@@ -257,42 +415,42 @@ class _DoneStep extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Icon(Icons.check_circle_outline, size: 56),
const SizedBox(height: 16),
Text(
'Sensor provisioned!',
style: Theme.of(context).textTheme.titleLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
'The sensor will appear in the list once it connects to the network. '
'Open the floor plan to place it.',
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
FilledButton.icon(
icon: const Icon(Icons.map_outlined),
label: const Text('Place on floor plan'),
onPressed: onGoToFloorPlan,
),
const SizedBox(height: 12),
OutlinedButton.icon(
icon: const Icon(Icons.add),
label: const Text('Add another sensor'),
onPressed: onAddAnother,
),
const SizedBox(height: 8),
TextButton(
onPressed: onDone,
child: const Text('Done'),
),
],
return SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Icon(Icons.check_circle_outline, size: 56),
const SizedBox(height: 16),
Text(
'Sensor provisioned!',
style: Theme.of(context).textTheme.titleLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
'The sensor will appear in the list once it connects to the network. '
'Open the floor plan to place it.',
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
FilledButton.icon(
icon: const Icon(Icons.map_outlined),
label: const Text('Place on floor plan'),
onPressed: onGoToFloorPlan,
),
const SizedBox(height: 12),
OutlinedButton.icon(
icon: const Icon(Icons.add),
label: const Text('Add another sensor'),
onPressed: onAddAnother,
),
const SizedBox(height: 8),
TextButton(onPressed: onDone, child: const Text('Done')),
],
),
);
}
}
@@ -94,6 +94,21 @@ class _FloorPlanScreenState extends ConsumerState<FloorPlanScreen> {
ref.listen(sensorsProvider, (_, next) {
next.whenData((s) => _editorKey.currentState?.loadSensors(s));
});
ref.listen(sensorsChannelProvider, (_, next) {
next.whenData((msg) {
switch (msg['event'] as String?) {
case 'sensor_announced':
ref.invalidate(sensorsProvider);
case 'sensor_enrollment_timeout':
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Sensor did not come online in time. '
'Check WiFi credentials and try again.'),
),
);
}
});
});
ref.listen(tagPositionsProvider, (_, next) {
next.whenData((t) => _editorKey.currentState?.updateTags(t));
});
@@ -149,6 +149,7 @@ class FloorPlanEditorState extends State<FloorPlanEditor> {
'floor_x': s.x,
'floor_y': s.y,
'room_id': s.roomId,
'confirmed': s.confirmed,
},
)
.toList(),
+30 -10
View File
@@ -13,6 +13,22 @@ class SensorListScreen extends ConsumerWidget {
Widget build(BuildContext context, WidgetRef ref) {
final sensors = ref.watch(sensorsProvider);
ref.listen(sensorsChannelProvider, (_, next) {
next.whenData((msg) {
switch (msg['event'] as String?) {
case 'sensor_announced':
ref.invalidate(sensorsProvider);
case 'sensor_enrollment_timeout':
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Sensor did not come online in time. '
'Check WiFi credentials and try again.'),
),
);
}
});
});
return Scaffold(
appBar: AppBar(title: const Text('Sensors')),
body: Column(
@@ -35,16 +51,12 @@ class SensorListScreen extends ConsumerWidget {
if (unplaced.isNotEmpty) ...[
_SectionHeader(
label: 'Unplaced', count: unplaced.length),
...unplaced.map((s) => _SensorTile(
sensor: s,
)),
...unplaced.map((s) => _SensorTile(sensor: s)),
],
if (placed.isNotEmpty) ...[
_SectionHeader(
label: 'Placed', count: placed.length),
...placed.map((s) => _SensorTile(
sensor: s,
)),
...placed.map((s) => _SensorTile(sensor: s)),
],
],
);
@@ -87,22 +99,30 @@ class _SectionHeader extends StatelessWidget {
}
class _SensorTile extends StatelessWidget {
const _SensorTile({required this.sensor, this.isSelected = false});
const _SensorTile({required this.sensor});
final Sensor sensor;
final bool isSelected;
@override
Widget build(BuildContext context) {
return ListTile(
selected: isSelected,
leading: Icon(sensor.isPlaced
? Icons.sensors
: Icons.sensors_off_outlined),
title: Text(sensor.displayName),
subtitle: Text(
sensor.isPlaced ? 'Placed' : 'Not placed on floor plan'),
trailing: const Icon(Icons.chevron_right),
textColor: sensor.confirmed ? null : Colors.grey,
trailing: sensor.confirmed
? const Icon(Icons.chevron_right)
: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.access_time, color: Colors.amber, size: 18),
SizedBox(width: 4),
Icon(Icons.chevron_right),
],
),
onTap: () => showSensorDetailSheet(context, sensor.id),
);
}