// tth fork: admin-pushed OTA firmware update of a meshcore-tth `-ota` node, // over the mesh (lib/services/ota). Strings are English and local to this // file on purpose: the fork keeps upstream's .arb files untouched. import 'dart:typed_data'; import 'package:file_selector/file_selector.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../models/contact.dart'; import '../services/ota/ota_protocol.dart'; import '../services/ota/ota_transfer.dart'; import '../theme/mesh_theme.dart'; import '../utils/radio_guard.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/radio_disconnected_banner.dart'; const String kOtaDefaultSidePreset = '869.525,62.5,7,5'; class RepeaterOtaScreen extends StatefulWidget { const RepeaterOtaScreen({ super.key, required this.repeater, required this.password, }); final Contact repeater; final String password; @override State createState() => _RepeaterOtaScreenState(); } class _RepeaterOtaScreenState extends State { final List _packages = []; final List _log = []; final ScrollController _logScroll = ScrollController(); final TextEditingController _duty = TextEditingController(text: '3'); final TextEditingController _gap = TextEditingController(text: '5'); final TextEditingController _preset = TextEditingController( text: kOtaDefaultSidePreset, ); final TextEditingController _window = TextEditingController(text: '15'); bool _apply = true; bool _side = false; OtaTransfer? _transfer; (int, int)? _progress; String? _outcome; bool get _running => _transfer != null; @override void dispose() { _transfer?.cancel(); _logScroll.dispose(); _duty.dispose(); _gap.dispose(); _preset.dispose(); _window.dispose(); super.dispose(); } void _addLog(String line) { if (!mounted) return; final t = TimeOfDay.now().format(context); setState(() => _log.add('$t $line')); WidgetsBinding.instance.addPostFrameCallback((_) { if (_logScroll.hasClients) { _logScroll.jumpTo(_logScroll.position.maxScrollExtent); } }); } Future _pickPackages() async { // .mcfw is no known MIME type: any file, checked by its MCFW manifest final files = await openFiles(); if (files.isEmpty) return; final picked = []; final skipped = []; for (final f in files) { try { picked.add( OtaPackage(f.name, Uint8List.fromList(await f.readAsBytes())), ); } on FormatException { skipped.add(f.name); } } setState(() { _packages ..clear() ..addAll(picked); _outcome = null; }); if (skipped.isNotEmpty) _addLog('not OTA packages: ${skipped.join(', ')}'); } Future _start({bool checkOnly = false}) async { if (!ensureRadioConnected(context)) return; final duty = double.tryParse(_duty.text.replaceAll(',', '.')); final gap = double.tryParse(_gap.text.replaceAll(',', '.')); final window = int.tryParse(_window.text); OtaPreset? side; try { if (_side) side = OtaPreset.parse(_preset.text); } on FormatException catch (e) { _addLog(e.message); return; } if (duty == null || duty <= 0 || duty > 100 || gap == null || gap < 0) { _addLog('duty must be in (0, 100] % and the gap >= 0 s'); return; } if (_side && (window == null || window < 3)) { _addLog('the side channel window must be at least 3 min'); return; } final transfer = OtaTransfer( connector: context.read(), node: widget.repeater, password: widget.password, packages: List.of(_packages), log: _addLog, progress: (done, total) { if (mounted) setState(() => _progress = (done, total)); }, duty: duty, gap: gap, side: side, window: window ?? 15, apply: _apply, checkOnly: checkOnly, ); setState(() { _transfer = transfer; _progress = null; _outcome = null; }); String outcome; try { final r = await transfer.run(); final release = r.tag ?? 'this release'; outcome = switch (r.state) { OtaState.applied => 'applied: ${r.versionAfter ?? r.package?.version}', OtaState.staged => 'staged ${r.package?.name} (not applied)', OtaState.current => 'up to date: the node already runs $release, no update needed', OtaState.available => 'update available: $release, delta ${r.package?.data.length} B', OtaState.noPackage => 'no delta fits the node\'s image', }; if (r.versionBefore != null) { outcome = 'node: ${r.versionBefore}\n$outcome'; } outcome += ', airtime ${r.airtime.toStringAsFixed(1)} s'; } on OtaCancelled { outcome = 'cancelled (the node keeps what it got until the next begin)'; } catch (e) { outcome = 'failed: $e'; } _addLog(outcome); if (mounted) { setState(() { _transfer = null; _outcome = outcome; }); } } @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; final progress = _progress; return Scaffold( appBar: AppBar( title: const Text('Firmware update (OTA)'), centerTitle: true, ), body: SafeArea( top: false, child: Column( children: [ const RadioDisconnectedBanner(), Expanded( child: ListView( padding: const EdgeInsets.only(bottom: 16), children: [ Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: Text( 'For nodes that run an -ota image of meshcore-tth. The ' 'delta that starts from the node\'s image is taken; only ' 'deltas go over the mesh. Keep the app open until it is ' 'done.', style: textTheme.bodySmall?.copyWith( color: scheme.onSurfaceVariant, ), ), ), const SectionHeader('Packages'), MeshCard( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_packages.isEmpty) const Text( 'The latest release from git.rfa.cz/tth-pub/' 'meshcore-tth, the delta for the node\'s image. ' 'Or choose .mcfw files (your own builds).', ) else for (final p in _packages) Text( '${p.name} · ${p.delta ? 'delta from ${p.baseSha!.substring(0, 8)}' : 'full image'}' ' · ${p.data.length} B', style: textTheme.bodySmall, ), const SizedBox(height: 8), OutlinedButton.icon( onPressed: _running ? null : _pickPackages, icon: const Icon(Icons.folder_open), label: const Text('Choose .mcfw files'), ), if (_packages.isNotEmpty) TextButton( onPressed: _running ? null : () => setState(_packages.clear), child: const Text('Use the latest release'), ), ], ), ), const SectionHeader('Options'), MeshCard( child: Column( children: [ SwitchListTile( contentPadding: EdgeInsets.zero, title: const Text('Apply after verify'), subtitle: const Text( 'fw apply: the node rewrites itself and reboots', ), value: _apply, onChanged: _running ? null : (v) => setState(() => _apply = v), ), Row( children: [ Expanded( child: TextField( controller: _duty, enabled: !_running, keyboardType: const TextInputType.numberWithOptions( decimal: true, ), decoration: const InputDecoration( labelText: 'Airtime budget % / h', ), ), ), const SizedBox(width: 12), Expanded( child: TextField( controller: _gap, enabled: !_running, keyboardType: const TextInputType.numberWithOptions( decimal: true, ), decoration: const InputDecoration( labelText: 'Pause per reply (s)', ), ), ), ], ), SwitchListTile( contentPadding: EdgeInsets.zero, title: const Text('Side channel'), subtitle: const Text( 'Send the chunks on another preset (tempradio), ' 'off the shared mesh. The companion must be a ' 'MeshCore firmware in direct range of the node.', ), value: _side, onChanged: _running ? null : (v) => setState(() { _side = v; if (v) _gap.text = '1'; }), ), if (_side) Row( children: [ Expanded( flex: 3, child: TextField( controller: _preset, enabled: !_running, decoration: const InputDecoration( labelText: 'freq,bw,sf,cr', ), ), ), const SizedBox(width: 12), Expanded( child: TextField( controller: _window, enabled: !_running, keyboardType: TextInputType.number, decoration: const InputDecoration( labelText: 'Window min', ), ), ), ], ), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: Row( children: [ OutlinedButton.icon( onPressed: _running ? null : () => _start(checkOnly: true), icon: const Icon(Icons.manage_search), label: const Text('Check'), ), const SizedBox(width: 12), Expanded( child: FilledButton.icon( onPressed: _running ? null : _start, icon: const Icon(Icons.system_update_alt), label: const Text('Update'), ), ), const SizedBox(width: 12), OutlinedButton( onPressed: _running ? () => _transfer?.cancel() : null, child: const Text('Cancel'), ), ], ), ), if (_running) Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: LinearProgressIndicator( value: progress == null ? null : progress.$1 / progress.$2, ), ), if (_outcome != null) Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: Text(_outcome!, style: textTheme.titleSmall), ), const SectionHeader('Log'), Container( height: 280, margin: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: scheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(MeshRadii.md), ), child: ListView.builder( controller: _logScroll, itemCount: _log.length, itemBuilder: (context, i) => Text( _log[i], style: textTheme.bodySmall?.copyWith( fontFamily: 'monospace', ), ), ), ), ], ), ), ], ), ), ); } }