// dashPi companion app: Health (with Cycle + Food), Work, Weather — works offline, keeps its own // copy of the data and syncs it through your dash-sync mailbox (server/) with the dashboard. // First start: Connect (device token + passphrase); then the app (app/shell.dart). // // A build may prefill the server: --dart-define=DEV_SERVER=https://sync.example.com (tool/publish.env); // dev runs also DEV_TOKEN=… DEV_PASS=… (only ever with a local test mailbox). import 'dart:io'; import 'package:flutter/foundation.dart' show kDebugMode; import 'package:flutter/material.dart'; import 'package:flutter_zxing/flutter_zxing.dart' show Format; import 'app/background.dart'; import 'app/scanner.dart'; import 'app/shell.dart'; import 'app/sync_service.dart'; import 'app/theme.dart'; import 'health/food_model.dart' show FoodDb; import 'sync/client.dart'; import 'sync/store.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(const DashApp()); } class DashApp extends StatelessWidget { const DashApp({super.key}); @override Widget build(BuildContext context) => MaterialApp(title: 'dashPi', debugShowCheckedModeBanner: false, theme: appTheme(), home: const Start()); } /// Connected → the app, else the connect form. class Start extends StatefulWidget { const Start({super.key}); @override State createState() => _StartState(); } class _StartState extends State { SyncService? sync; bool loading = true; @override void initState() { super.initState(); _load(); } Future _load() async { final s = await SyncSettings.load(); if (s != null) { sync = SyncService(s, SyncStore(await dataPath(), s.device)); FoodDb.store = sync!.store; // products kept from the archive (food_model.dart) scheduleBackground(); } setState(() => loading = false); } Future _connected(SyncSettings s) async { await s.save(); final st = SyncStore(await dataPath(), s.device); FoodDb.store = st; setState(() => sync = SyncService(s, st)); scheduleBackground(); } /// Disconnect: the settings are gone already; drop this phone's copy of the data too. Future _forget() async { final old = sync; await stopBackground(); setState(() => sync = null); old?.store.db.close(); old?.dispose(); final p = await dataPath(); for (final f in [p, '$p-wal', '$p-shm']) { if (File(f).existsSync()) File(f).deleteSync(); } } @override Widget build(BuildContext context) { if (loading) return const Scaffold(body: Center(child: CircularProgressIndicator())); if (sync == null) return ConnectPage(onConnected: _connected); return Shell(sync: sync!, onForget: _forget); } } class ConnectPage extends StatefulWidget { const ConnectPage({super.key, required this.onConnected}); final Future Function(SyncSettings) onConnected; @override State createState() => _ConnectPageState(); } class _ConnectPageState extends State { final server = TextEditingController(text: const String.fromEnvironment('DEV_SERVER')); final token = TextEditingController(text: const String.fromEnvironment('DEV_TOKEN')); final pass = TextEditingController(text: const String.fromEnvironment('DEV_PASS')); final recovery = TextEditingController(); bool busy = false, useRecovery = false; String? error; /// The QR code from the dashboard's Settings ▸ General ▸ Add a device: dashpi://connect?server=…&token=… bool _takeLink(String text) { final u = Uri.tryParse(text.trim()); if (u == null || u.scheme != 'dashpi' || u.host != 'connect') return false; final s = u.queryParameters['server'], t = u.queryParameters['token']; if (s == null || t == null || s.isEmpty || t.isEmpty) return false; setState(() { server.text = s; token.text = t; error = null; }); return true; } Future _scan() async { final v = await scanCode(context, title: 'Scan the code from the dashboard', format: Format.qrCode, accept: (v) => v.startsWith('dashpi://connect?')); if (v != null && !_takeLink(v)) setState(() => error = "That's not a code from the dashboard."); } Future _go() async { if (_takeLink(token.text) || _takeLink(server.text)) return; // the link pasted into a field setState(() { busy = true; error = null; }); try { if (!kDebugMode && !server.text.trim().startsWith('https://')) { throw 'The server needs an https:// address (the token travels with every request).'; } final s = await join(server.text.trim(), token.text.trim(), passphrase: pass.text, recovery: useRecovery ? recovery.text : null); await widget.onConnected(s); } catch (e) { setState(() => error = '$e'); } finally { if (mounted) setState(() => busy = false); } } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Connect to your dashboard')), body: ListView(padding: const EdgeInsets.all(16), children: [ const Text('On the dashboard: Settings ▸ General ▸ Devices ▸ Add a device shows a code — scan it, then type ' 'the passphrase you chose when you set up sync there.', style: TextStyle(color: muted)), const SizedBox(height: 12), OutlinedButton.icon(onPressed: busy ? null : _scan, icon: const Icon(Icons.qr_code_scanner), label: const Text('Scan the code from the dashboard')), const SizedBox(height: 8), TextField(controller: server, keyboardType: TextInputType.url, decoration: const InputDecoration(labelText: 'Server', hintText: 'https://sync.example.com')), TextField(controller: token, obscureText: true, decoration: const InputDecoration(labelText: 'Device token')), if (!useRecovery) TextField(controller: pass, obscureText: true, decoration: const InputDecoration(labelText: 'Sync passphrase')) else TextField(controller: recovery, decoration: const InputDecoration(labelText: 'Recovery key (ABCD-EFGH-…)')), TextButton( onPressed: () => setState(() => useRecovery = !useRecovery), child: Text(useRecovery ? 'Use the passphrase instead' : 'Forgot it? Use the recovery key')), const SizedBox(height: 12), if (error != null) Text(error!, style: const TextStyle(color: bad)), const SizedBox(height: 12), FilledButton( onPressed: busy ? null : _go, child: busy ? const SizedBox(height: 18, width: 18, child: CircularProgressIndicator(strokeWidth: 2)) : const Text('Connect')), ]), ); }