/// The OTA transfer over the mesh, as remote admin through the connected /// companion -- a port of meshcore_ota_engine.py (Radio, Side, update) of the /// tth.meshcore Ansible collection, which is the reference. Change the /// protocol there first. /// /// Deltas only (the node refuses a full image over the mesh). Binary chunks /// (REQ_TYPE_FW_OTA, 128 B, unanswered, missing ones found by a bitmap query), /// text chunks (`fw w`) as the fallback, paced by an airtime budget. /// /// [side]: carry the transfer on a side channel, off the shared mesh. Login and /// `fw status` go over the mesh, then the node gets `tempradio ,3`, the /// companion is retuned to the same preset (checked: an openHop virtual /// companion acks and stays put), a fresh login goes zero-hop and the chunks /// follow. The window grows to [window] minutes once the link is proven and is /// renewed. The node comes back on `fw apply` (reboot), on `tempradio ,1` at the end, or by its own timer if the phone goes away. library; import 'dart:async'; import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import '../../connector/meshcore_connector.dart'; import '../../connector/meshcore_protocol.dart'; import '../../models/contact.dart'; import '../repeater_command_service.dart'; import 'ota_protocol.dart'; import 'ota_release.dart'; class OtaError implements Exception { OtaError(this.message); final String message; @override String toString() => message; } class OtaCancelled extends OtaError { OtaCancelled() : super('cancelled'); } /// [available]: only with [OtaTransfer.checkOnly] -- a delta for the node's /// image exists, nothing was sent. enum OtaState { current, available, noPackage, staged, applied } class OtaResult { OtaResult( this.state, { this.package, this.tag, this.versionBefore, this.versionAfter, this.airtime = 0, }); final OtaState state; final OtaPackage? package; final String? tag; // the release, when the package came from one final String? versionBefore; // `ver`, with checkOnly final String? versionAfter; final double airtime; } const int _sideFirstMinutes = 3; const Duration _sideMargin = Duration(seconds: 150); class OtaTransfer { OtaTransfer({ required this.connector, required this.node, required this.password, required this.packages, required this.log, this.progress, this.duty = 3, this.gap = 5, this.side, this.window = 15, this.apply = true, this.applyWait = const Duration(seconds: 60), this.release, this.checkOnly = false, }) : _bucket = OtaBucket(duty); final MeshCoreConnector connector; final Contact node; final String password; final List packages; final void Function(String line) log; final void Function(int done, int total)? progress; final double duty; final double gap; final OtaPreset? side; final int window; final bool apply; final Duration applyWait; /// Where the package comes from when [packages] is empty (default: the /// latest public release). final OtaRelease? release; /// Only find out whether an update exists: login, `ver`, `fw status`, the /// release lookup -- and stop before `fw begin`. final bool checkOnly; final OtaBucket _bucket; late final RepeaterCommandService _cli = RepeaterCommandService(connector); StreamSubscription? _frames; bool _cancelled = false; (int, double, int)? _radio; // (sf, bw kHz, cr 1..4) of the channel in use // side channel state OtaPreset? _nodeMain; OtaPreset? _compMain; bool? _compRepeat; bool _nodeOnSide = false; (int, DateTime)? _renew; // (window min, deadline) while the node is there int? _savedOverride; Uint8List? _savedOverrideBytes; bool _overrideTaken = false; double get airtime => _bucket.used; void cancel() => _cancelled = true; void _check() { if (_cancelled) throw OtaCancelled(); } Contact get _node { for (final c in connector.contacts) { if (c.publicKeyHex == node.publicKeyHex) return c; } return node; } int get _hops => math.max(_node.pathLength, 0); Future _sleep(double secs) async { final end = DateTime.now().add( Duration(milliseconds: (secs * 1000).round()), ); while (DateTime.now().isBefore(end)) { _check(); final left = end.difference(DateTime.now()); await Future.delayed( left < const Duration(milliseconds: 500) ? left : const Duration(milliseconds: 500), ); } } Future _spend(double secs) async { while (true) { final wait = _bucket.waitFor(secs); if (wait == 0) return; log('airtime budget: waiting ${wait.toStringAsFixed(0)} s'); await _sleep(wait); } } (int, double, int) _companionRadio() { final sf = connector.currentSf ?? 8; final bw = (connector.currentBwHz ?? 62500) / 1000; final cr = (connector.currentCr ?? 5) - 4; return (sf, bw, cr); } // ── CLI ────────────────────────────────────────────────────────────────── Future _ask(String line, {int tries = 4, bool quiet = false}) async { _check(); await _keepSide(); final r = _radio!; final one = otaAirtime(otaTextFrameLen(line), r.$1, r.$2, r.$3) + otaAirtime(otaTextFrameLen('x' * otaReplyText), r.$1, r.$2, r.$3); // RepeaterCommandService retries on its own: the budget sees the first try await _spend(one * (_hops + 1)); String reply; try { reply = (await _cli.sendCommand(_node, line, retries: tries)).trim(); } catch (e) { throw OtaError('no reply to `${_short(line)}`: $e'); } if (!quiet) log('\$ ${_short(line)} -> $reply'); if (gap > 0) await _sleep(gap); return reply; } static String _short(String line) => line.length > 32 ? '${line.substring(0, 32)}...' : line; // ── binary requests (REQ_TYPE_FW_OTA) ──────────────────────────────────── double _reqCost(int payloadLen, [int replyLen = 0]) { final r = _radio!; var t = otaAirtime(otaReqFrameLen(payloadLen), r.$1, r.$2, r.$3); if (replyLen > 0) { t += otaAirtime(otaReqFrameLen(replyLen), r.$1, r.$2, r.$3); } return t * (_hops + 1); } /// Sends a binary request; returns its tag (RESP_CODE_SENT), or null. Future _sendReq(Uint8List payload) async { final frame = buildSendBinaryReq(_node.publicKey, payload: payload); if (frame.length > maxFrameSize) { throw OtaError('binary request of ${payload.length} B exceeds the frame'); } final sent = Completer(); final sub = connector.receivedFrames.listen((f) { if (f.isNotEmpty && f[0] == respCodeSent && f.length >= 6) { if (!sent.isCompleted) sent.complete(f.sublist(2, 6)); } }); try { await connector.sendFrame(frame); return await sent.future.timeout( const Duration(seconds: 5), onTimeout: () => null, ); } finally { await sub.cancel(); } } Future _write(int sid, int off, List chunk) async { await _keepSide(); final payload = otaWritePayload(sid, off, chunk); final c = _reqCost(payload.length); await _spend(c); await _sendReq(payload); // no reply comes: give the packet time to go out along the whole path await _sleep(math.max(gap, c + 1)); } Future<(int, List)?> _missing() async { for (var attempt = 0; attempt < 2; attempt++) { await _keepSide(); await _spend(_reqCost(2, 160)); final got = Completer(); Uint8List? tag; final early = []; final sub = connector.receivedFrames.listen((f) { if (f.isEmpty || f[0] != pushCodeBinaryResponse || f.length < 6) { return; } if (tag == null) { early.add(f); } else if (listEquals(f.sublist(2, 6), tag) && !got.isCompleted) { got.complete(f.sublist(6)); } }); try { tag = await _sendReq(Uint8List.fromList([reqTypeFwOta, 0x6D])); // 'm' for (final f in early) { if (tag != null && listEquals(f.sublist(2, 6), tag)) { if (!got.isCompleted) got.complete(f.sublist(6)); } } final data = await got.future.timeout(const Duration(seconds: 20)); final st = otaParseMissing(data); if (st == null) continue; if (gap > 0) await _sleep(gap); return st; } on TimeoutException { continue; } finally { await sub.cancel(); } } return null; } /// The bitmap once the node is done checking (state 4 = busy); a lost query /// after a long round must not throw the round away. Future<(int, List)?> _settled() async { var lost = 0; (int, List)? st; for (var q = 0; q < 10; q++) { st = await _missing(); if (st == null && lost < 4) { lost++; await _sleep(10); continue; } if (st == null || st.$1 != 4) return st; await _sleep(3); } return st; } // ── login ──────────────────────────────────────────────────────────────── Future _login() async { for (var attempt = 0; attempt < 4; attempt++) { _check(); await connector.preparePathForContactSend(_node); await _spend(otaAirtime(48, _radio!.$1, _radio!.$2, _radio!.$3)); final done = Completer(); final prefix = _node.publicKey.sublist(0, 6); final sub = connector.receivedFrames.listen((f) { if (f.length < 8) return; if (f[0] != pushCodeLoginSuccess && f[0] != pushCodeLoginFail) return; if (!listEquals(f.sublist(2, 8), prefix)) return; if (!done.isCompleted) done.complete(f[0] == pushCodeLoginSuccess); }); try { await connector.sendFrame( buildSendLoginFrame(_node.publicKey, password), ); final ok = await done.future.timeout( const Duration(seconds: 45), onTimeout: () => false, ); if (ok) { log('login ok (attempt ${attempt + 1}), ${_hopsLabel()}'); return; } } finally { await sub.cancel(); } } throw OtaError('login refused or no reply'); } String _hopsLabel() => _node.pathLength < 0 ? 'flood' : '${_node.pathLength} hops'; // ── side channel ───────────────────────────────────────────────────────── Future _keepSide() async { final renew = _renew; if (renew == null || DateTime.now().isBefore(renew.$2.subtract(_sideMargin))) { return; } final win = renew.$1; _renew = (win, DateTime.now().add(Duration(minutes: win))); final r = await _ask('tempradio $side,$win'); if (!r.startsWith('OK')) throw OtaError('tempradio renewal: $r'); await _sleep(3); // the node re-applies the preset 2 s after its reply } Future _companionOn(OtaPreset p) async { await connector.refreshDeviceInfo(); for (var i = 0; i < 20; i++) { if (p.matchesFields( connector.currentFreqHz, connector.currentBwHz, connector.currentSf, connector.currentCr, )) { return true; } await Future.delayed(const Duration(milliseconds: 250)); } return false; } Future _enterSide() async { final s = side!; final main = OtaPreset.fromReply(await _ask('get radio')); if (main == null) throw OtaError('`get radio` gave no preset'); _nodeMain = main; final reply = await _ask('tempradio $s,$_sideFirstMinutes'); if (!reply.startsWith('OK')) throw OtaError('tempradio: $reply'); _nodeOnSide = true; _renew = ( _sideFirstMinutes, DateTime.now().add(const Duration(minutes: _sideFirstMinutes)), ); log('node $main -> side channel $s for $_sideFirstMinutes min'); await _sleep(3); // the node switches 2 s after its reply final compMain = OtaPreset( (connector.currentFreqHz ?? 0) / 1000, (connector.currentBwHz ?? 0) / 1000, connector.currentSf ?? 0, connector.currentCr ?? 0, ); final repeat = connector.clientRepeat; final accepted = await connector.setRadioParams( s.freqField, s.bwField, s.sf, s.cr, clientRepeat: repeat == null ? null : false, ); if (!accepted || !await _companionOn(s)) { throw OtaError( 'the companion did not retune (an openHop virtual companion acks the ' 'change and keeps its radio): a side channel needs a MeshCore ' 'companion firmware. The node returns within $_sideFirstMinutes min.', ); } _compMain = compMain; _compRepeat = repeat; _radio = (s.sf, s.bw, s.cr - 4); log('companion on $s'); // Zero-hop from here: a mesh path means nothing on the side channel, and // the node answers along the path of the last login -- log in again. final c = _node; _savedOverride = c.pathOverride; _savedOverrideBytes = c.pathOverrideBytes; _overrideTaken = true; await connector.setPathOverride(c, pathLen: -1); try { await _login(); } on OtaError catch (e) { throw OtaError('login on the side channel: $e (out of direct range?)'); } _renew = (window, DateTime.now()); // the link works: the full window now await _keepSide(); } Future _leaveSide() async { _renew = null; if (_nodeOnSide && _compMain != null && _nodeMain != null) { final saved = _cancelled; _cancelled = false; // the way back must run even after a cancel try { final r = await _ask('tempradio $_nodeMain,1', tries: 2); log('node back to $_nodeMain: $r'); } on OtaError { log( 'node does not answer: it returns by itself when its window runs out', ); } finally { _cancelled = saved; } } _nodeOnSide = false; final main = _compMain; if (main != null) { _compMain = null; await connector.setRadioParams( main.freqField, main.bwField, main.sf, main.cr, clientRepeat: _compRepeat, ); final ok = await _companionOn(main); log('companion back on $main: ${ok ? 'ok' : 'CHECK IT'}'); _radio = (main.sf, main.bw, main.cr - 4); } if (_overrideTaken) { _overrideTaken = false; await connector.setPathOverride( _node, pathLen: _savedOverride, pathBytes: _savedOverrideBytes, ); } } // ── the transfer ───────────────────────────────────────────────────────── Future?> _binaryRounds(Uint8List data, int sid) async { if (await _missing() == null) { log('node does not answer binary requests: text chunks'); return null; } final total = (data.length + otaBinaryChunk - 1) ~/ otaBinaryChunk; var todo = List.generate(total, (i) => i); var lastMiss = 1 << 30; var manifestChecked = false; for (var rnd = 0; rnd < 6; rnd++) { for (var k = 0; k < todo.length; k++) { final off = todo[k] * otaBinaryChunk; await _write( sid, off, data.sublist(off, math.min(off + otaBinaryChunk, data.length)), ); progress?.call(k + 1, todo.length); if (!manifestChecked && off + otaBinaryChunk >= otaManifest && k + 1 < todo.length) { // the node checks the manifest as soon as it is in: ask before the // rest goes on air, a refused package would cost the round manifestChecked = true; final st = await _settled(); if (st != null && st.$1 == 3) { throw OtaError( 'node refused the package: ${await _ask('fw status')}', ); } } } final st = await _settled(); if (st == null) { throw OtaError('no answer to the missing-units query'); } final (state, miss) = st; log( 'binary round ${rnd + 1}: ${todo.length} sent, ${miss.length} units missing', ); if (state == 3) { throw OtaError('node refused the package: ${await _ask('fw status')}'); } if (miss.isEmpty) return []; if (rnd > 0 && miss.length >= lastMiss) { log('binary chunks do not arrive: text chunks for the rest'); return {for (final u in miss) u * otaUnit ~/ otaChunk}.toList()..sort(); } lastMiss = miss.length; todo = {for (final u in miss) u * otaUnit ~/ otaBinaryChunk}.toList() ..sort(); } throw OtaError('binary transfer did not converge in 6 rounds'); } Future _textRounds(Uint8List data, List todo) async { var stuck = 0; for (var rnd = 0; rnd < 40; rnd++) { for (var k = 0; k < todo.length; k++) { final off = todo[k] * otaChunk; final b64 = base64Encode( data.sublist(off, math.min(off + otaChunk, data.length)), ); final r = await _ask('fw w $off $b64', quiet: true); if (r != 'ok') throw OtaError('chunk $off: $r'); progress?.call(k + 1, todo.length); } final reply = await _ask('fw missing'); final next = otaTextMissing(reply); log('text round ${rnd + 1}: ${todo.length} sent'); if (next != null && next.isEmpty) return; if (next == null) { if (++stuck > 3) throw OtaError('`fw missing` does not answer: $reply'); todo = []; continue; } final chunks = next.map((o) => o ~/ otaChunk).toList(); stuck = listEquals(chunks, todo) ? stuck + 1 : 0; if (stuck > 3) throw OtaError('the same chunks keep missing'); todo = chunks; } throw OtaError('text transfer did not converge in 40 rounds'); } Future run() async { _radio = _companionRadio(); _frames = connector.receivedFrames.listen((frame) { final parsed = parseContactMessageText(frame); if (parsed == null) return; if (!listEquals(parsed.senderPrefix, node.publicKey.sublist(0, 6))) { return; } _cli.handleResponse(_node, parsed.text); }); try { await _login(); final before = checkOnly ? await _ask('ver') : null; final status = await _ask('fw status'); var base = otaParseStatus(status)?.$2; if (base == null && status.startsWith('>')) { // `fw status` shows the base only when idle (not failed/ready/rx) base = otaParseBase(await _ask('fw base')); } if (base == null) { log('no base image: not an -ota build'); return OtaResult( OtaState.noPackage, versionBefore: before, airtime: airtime, ); } var pkgs = packages; String? tag; if (pkgs.isEmpty) { final target = otaParseTarget(await _ask('fw ver')); if (target == null) { log('`fw ver` names no target: not an -ota build'); return OtaResult( OtaState.noPackage, versionBefore: before, airtime: airtime, ); } log('looking for $target from $base in the latest release'); final OtaReleaseMatch m; try { m = await (release ?? OtaRelease()).find(target, base); } on OtaReleaseError catch (e) { throw OtaError('release: $e'); } catch (e) { throw OtaError('release: cannot download ($e)'); } tag = m.tag; if (m.current) { log('the node already runs ${m.tag}'); return OtaResult( OtaState.current, tag: tag, versionBefore: before, airtime: airtime, ); } if (m.package == null) { log( '${m.tag} has no delta from $base (too old: a full image over USB/BLE)', ); return OtaResult( OtaState.noPackage, tag: tag, versionBefore: before, airtime: airtime, ); } log('${m.tag}: ${m.package!.name}, sha256 ok'); pkgs = [m.package!]; } final pick = otaPick(pkgs, base); if (pick.kind == OtaPickKind.current) { log('the node already runs ${pick.package!.name}'); return OtaResult( OtaState.current, package: pick.package, tag: tag, versionBefore: before, airtime: airtime, ); } if (pick.kind != OtaPickKind.delta) { log( 'no delta starts from $base (a full image does not go over the mesh)', ); return OtaResult( OtaState.noPackage, tag: tag, versionBefore: before, airtime: airtime, ); } final pkg = pick.package!; final data = pkg.data; log('package ${pkg.name} (delta, ${data.length} B)'); if (checkOnly) { return OtaResult( OtaState.available, package: pkg, tag: tag, versionBefore: before, airtime: airtime, ); } if (side != null) await _enterSide(); final sid = 1 + math.Random().nextInt(0xFFFF); final r = await _ask('fw begin ${data.length} $sid'); if (!r.startsWith('OK')) throw OtaError('fw begin: $r'); var todo = await _binaryRounds(data, sid); todo ??= List.generate( (data.length + otaChunk - 1) ~/ otaChunk, (i) => i, ); if (todo.isNotEmpty) await _textRounds(data, todo); var v = await _ask('fw verify'); for (var i = 0; i < 20 && v.contains('verifying'); i++) { await _sleep(3); v = await _ask('fw status'); } if (!v.startsWith('>') || !v.contains('ready')) { throw OtaError('fw verify: $v'); } await _ask('fw bl'); if (!apply) { return OtaResult(OtaState.staged, package: pkg, airtime: airtime); } final a = await _ask('fw apply', tries: 1); if (!a.startsWith('OK')) throw OtaError('fw apply: $a'); // the reboot takes the node back to its own preset: follow it _nodeOnSide = false; await _leaveSide(); log( 'waiting ${applyWait.inSeconds} s for the node to rewrite itself and boot', ); await _sleep(applyWait.inSeconds.toDouble()); String? after; try { await _login(); after = await _ask('ver'); await _ask('fw status'); } on OtaError catch (e) { log('after the apply: $e'); } return OtaResult( OtaState.applied, package: pkg, versionAfter: after, airtime: airtime, ); } finally { try { await _leaveSide(); } finally { await _frames?.cancel(); _cli.dispose(); } } } }