Add OTA firmware updates of meshcore-tth nodes, with a side channel
A "Firmware update (OTA)" tile in the repeater hub (admins, tth fork switch kOtaUpdate) pushes a delta of a meshcore-tth -ota image over the mesh: the package that starts from the node's image is picked from the chosen .mcfw files, binary chunks with text as the fallback, an airtime budget, verify and apply. Optionally on a side channel: the node goes to another preset by tempradio, the companion follows (checked), the chunks go zero-hop and both come back at the end. A port of the reference engine of the tth.meshcore Ansible collection (module_utils/meshcore_ota_engine.py); test/services/ota/ota_vectors.json is its test-vector file. Bench 16. 11. 2026: the connector over TCP to a USB companion, side channel 866.0/SF7, applied a 2.7 kB delta, 20 s airtime, companion back on its preset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5a53e45e9a
commit
1b2e0ccdfc
7 files changed
+1711
No files matched your search
@@ -0,0 +1,262 @@
|
||||
/// Radio-free parts of the admin-pushed OTA firmware update of meshcore-tth
|
||||
/// (src/helpers/FwUpdate): packages, the chunk framing, replies, airtime.
|
||||
///
|
||||
/// A port of module_utils/meshcore_ota.py of the tth.meshcore Ansible
|
||||
/// collection (git.rfa.cz/tth-pub/meshcore-ansible), which is the reference;
|
||||
/// test/services/ota/ota_vectors.json is its test-vector file, and
|
||||
/// test/services/ota/ota_protocol_test.dart holds this code to it.
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
const int otaChunk = 96; // FW_OTA_CHUNK: text chunk `fw w <off> <base64>`
|
||||
const int otaBinaryChunk =
|
||||
128; // FW_OTA_BCHUNK: REQ_TYPE_FW_OTA 'w', unanswered
|
||||
const int otaUnit = 32; // FW_OTA_UNIT: what the missing-units bitmap counts
|
||||
const int otaManifest = 256;
|
||||
const int reqTypeFwOta = 0xF0;
|
||||
const int otaReplyText = 40; // typical reply length, for the airtime estimate
|
||||
|
||||
String _hex(List<int> b) =>
|
||||
b.map((x) => x.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
/// One `.mcfw` file: a 256 B manifest and a payload.
|
||||
/// 0 "MCFW" | 4 format 1 (full) / 2 (delta) | 16 image sha256 |
|
||||
/// 128 version | 160 base sha256 (delta) | 192 Ed25519 signature
|
||||
class OtaPackage {
|
||||
OtaPackage(this.name, this.data) {
|
||||
if (data.length < otaManifest ||
|
||||
data[0] != 0x4D ||
|
||||
data[1] != 0x43 ||
|
||||
data[2] != 0x46 ||
|
||||
data[3] != 0x57) {
|
||||
throw FormatException('$name: not an OTA package (no MCFW manifest)');
|
||||
}
|
||||
}
|
||||
|
||||
final String name;
|
||||
final Uint8List data;
|
||||
|
||||
int get format => data[4];
|
||||
bool get delta => format == 2;
|
||||
String get imageSha => _hex(data.sublist(16, 48));
|
||||
String? get baseSha => delta ? _hex(data.sublist(160, 192)) : null;
|
||||
String get version {
|
||||
final raw = data.sublist(128, 156);
|
||||
final end = raw.indexOf(0);
|
||||
return String.fromCharCodes(end < 0 ? raw : raw.sublist(0, end));
|
||||
}
|
||||
}
|
||||
|
||||
enum OtaPickKind { current, delta, full, none }
|
||||
|
||||
class OtaPick {
|
||||
const OtaPick(this.kind, this.package);
|
||||
final OtaPickKind kind;
|
||||
final OtaPackage? package;
|
||||
}
|
||||
|
||||
/// current: the node already runs the image these packages install. delta: the
|
||||
/// one that starts from its image. full: no delta fits and a full image may go
|
||||
/// (never over the mesh -- the node refuses one there).
|
||||
OtaPick otaPick(List<OtaPackage> packages, String base, {bool fullOk = false}) {
|
||||
for (final p in packages) {
|
||||
if (p.imageSha.startsWith(base)) return OtaPick(OtaPickKind.current, p);
|
||||
}
|
||||
OtaPackage? full;
|
||||
for (final p in packages) {
|
||||
if (p.delta && p.baseSha!.startsWith(base)) {
|
||||
return OtaPick(OtaPickKind.delta, p);
|
||||
}
|
||||
if (!p.delta) full = p;
|
||||
}
|
||||
if (full != null && fullOk) return OtaPick(OtaPickKind.full, full);
|
||||
return const OtaPick(OtaPickKind.none, null);
|
||||
}
|
||||
|
||||
/// `fw status` -> (image size, sha256 prefix); null when it shows none: not an
|
||||
/// -ota build, or a transfer state (failed/ready/rx) -- then ask `fw base`.
|
||||
(int, String)? otaParseStatus(String text) {
|
||||
final m = RegExp(r'\bbase (\d+) ([0-9a-f]{8})').firstMatch(text);
|
||||
return m == null ? null : (int.parse(m.group(1)!), m.group(2)!);
|
||||
}
|
||||
|
||||
/// `fw base` -> sha256 prefix of the running image, in any transfer state.
|
||||
String? otaParseBase(String text) =>
|
||||
RegExp(r'^>\s*([0-9a-f]{64})').firstMatch(text)?.group(1)!.substring(0, 8);
|
||||
|
||||
/// Nordic crc16_compute (CCITT, init 0xFFFF) -- FwUpdate.cpp crc16_update.
|
||||
int otaCrc16(List<int> data, [int crc = 0xFFFF]) {
|
||||
for (final b in data) {
|
||||
crc = ((crc >> 8) | (crc << 8)) & 0xFFFF;
|
||||
crc ^= b;
|
||||
crc ^= (crc & 0xFF) >> 4;
|
||||
crc ^= (crc << 12) & 0xFFFF;
|
||||
crc ^= ((crc & 0xFF) << 5) & 0xFFFF;
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
/// REQ_TYPE_FW_OTA 'w': [F0]['w'][sid u16][off u32][len u8][crc16][data]; the
|
||||
/// crc binds the data to this session and offset.
|
||||
Uint8List otaWritePayload(int sid, int off, List<int> chunk) {
|
||||
final head = [
|
||||
sid & 0xFF,
|
||||
(sid >> 8) & 0xFF,
|
||||
off & 0xFF,
|
||||
(off >> 8) & 0xFF,
|
||||
(off >> 16) & 0xFF,
|
||||
(off >> 24) & 0xFF,
|
||||
chunk.length,
|
||||
];
|
||||
final crc = otaCrc16(chunk, otaCrc16(head));
|
||||
return Uint8List.fromList([
|
||||
reqTypeFwOta,
|
||||
0x77, // 'w'
|
||||
...head,
|
||||
crc & 0xFF,
|
||||
crc >> 8,
|
||||
...chunk,
|
||||
]);
|
||||
}
|
||||
|
||||
/// Reply to REQ_TYPE_FW_OTA 'm': (state, missing unit indices); state 3 =
|
||||
/// refused, 4 = busy checking.
|
||||
(int, List<int>)? otaParseMissing(List<int> data) {
|
||||
if (data.length < 5) return null;
|
||||
final count = data[3] | (data[4] << 8);
|
||||
final units = <int>[];
|
||||
for (var i = 0; i < count && 6 + 2 * i < data.length; i++) {
|
||||
units.add(data[5 + 2 * i] | (data[6 + 2 * i] << 8));
|
||||
}
|
||||
return (data[0], units);
|
||||
}
|
||||
|
||||
/// `fw missing` -> chunk offsets ([] for none), null for a reply that is no list.
|
||||
List<int>? otaTextMissing(String reply) {
|
||||
if (!reply.startsWith('>')) return null;
|
||||
final body = reply.substring(1).trim();
|
||||
if (body == 'none') return [];
|
||||
return body.split(RegExp(r'\s+')).map(int.parse).toList();
|
||||
}
|
||||
|
||||
/// A radio preset: MHz, kHz, SF, CR 5..8 -- the ranges `tempradio` takes.
|
||||
class OtaPreset {
|
||||
const OtaPreset(this.freq, this.bw, this.sf, this.cr);
|
||||
final double freq;
|
||||
final double bw;
|
||||
final int sf;
|
||||
final int cr;
|
||||
|
||||
static OtaPreset parse(String text) {
|
||||
final parts = text.trim().split(',');
|
||||
if (parts.length != 4) {
|
||||
throw FormatException('preset "$text": freq,bw,sf,cr');
|
||||
}
|
||||
final f = double.tryParse(parts[0]);
|
||||
final bw = double.tryParse(parts[1]);
|
||||
final sf = int.tryParse(parts[2]);
|
||||
final cr = int.tryParse(parts[3]);
|
||||
if (f == null || bw == null || sf == null || cr == null) {
|
||||
throw FormatException('preset "$text": freq,bw,sf,cr');
|
||||
}
|
||||
if (f < 150 ||
|
||||
f > 2500 ||
|
||||
bw < 7 ||
|
||||
bw > 500 ||
|
||||
sf < 5 ||
|
||||
sf > 12 ||
|
||||
cr < 5 ||
|
||||
cr > 8) {
|
||||
throw FormatException('preset "$text": out of range');
|
||||
}
|
||||
return OtaPreset(f, bw, sf, cr);
|
||||
}
|
||||
|
||||
/// `get radio` ('> 869.432,62.5,7,5') -> preset, or null.
|
||||
static OtaPreset? fromReply(String reply) {
|
||||
final m = RegExp(
|
||||
r'^>\s*([\d.]+),([\d.]+),(\d+),(\d+)$',
|
||||
).firstMatch(reply.trim());
|
||||
return m == null ? null : parse('${m[1]},${m[2]},${m[3]},${m[4]}');
|
||||
}
|
||||
|
||||
/// As the companion frame carries it: freq in kHz, bw in Hz.
|
||||
int get freqField => (freq * 1000).round();
|
||||
int get bwField => (bw * 1000).round();
|
||||
|
||||
bool matchesFields(int? freqField, int? bwField, int? sf, int? cr) =>
|
||||
freqField == this.freqField &&
|
||||
bwField == this.bwField &&
|
||||
sf == this.sf &&
|
||||
cr == this.cr;
|
||||
|
||||
static String _num(double v) {
|
||||
final s = v.toString();
|
||||
return s.endsWith('.0') ? s.substring(0, s.length - 2) : s;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => '${_num(freq)},${_num(bw)},$sf,$cr';
|
||||
}
|
||||
|
||||
/// Seconds on air for an n-byte LoRa frame (explicit header, CRC on, preamble
|
||||
/// 16); cr is 1..4 for 4/5..4/8. The engine's own budget model, kept equal to
|
||||
/// the reference (lib/utils/lora_airtime.dart answers other questions).
|
||||
double otaAirtime(int n, int sf, double bwKhz, int cr) {
|
||||
final tsym = math.pow(2, sf) / (bwKhz * 1000);
|
||||
final de = tsym > 0.016 ? 1 : 0;
|
||||
final payload =
|
||||
8 +
|
||||
math.max(
|
||||
((8 * n - 4 * sf + 28 + 16) / (4 * (sf - 2 * de))).ceil() * (cr + 4),
|
||||
0,
|
||||
);
|
||||
return (16 + 4.25) * tsym + payload * tsym;
|
||||
}
|
||||
|
||||
/// Direct REQ: header+path_len, dest/src hash, MAC, timestamp+payload in AES blocks.
|
||||
int otaReqFrameLen(int payloadLen) => 6 + 16 * ((4 + payloadLen) / 16).ceil();
|
||||
|
||||
/// Direct text frame: as a REQ, with flags and the text.
|
||||
int otaTextFrameLen(String text) =>
|
||||
6 + 16 * ((5 + text.codeUnits.length) / 16).ceil();
|
||||
|
||||
/// Airtime budget: a token bucket of [duty] % of an hour. It counts what the
|
||||
/// transfer puts on the channel, request and reply times (hops + 1).
|
||||
class OtaBucket {
|
||||
OtaBucket(double duty, {DateTime Function()? clock})
|
||||
: rate = duty / 100,
|
||||
_clock = clock ?? DateTime.now {
|
||||
if (duty <= 0 || duty > 100) {
|
||||
throw ArgumentError('duty $duty % is not in (0, 100]');
|
||||
}
|
||||
cap = rate * 3600;
|
||||
level = cap;
|
||||
_t = _clock();
|
||||
}
|
||||
|
||||
final double rate;
|
||||
late final double cap;
|
||||
late double level;
|
||||
double used = 0;
|
||||
final DateTime Function() _clock;
|
||||
late DateTime _t;
|
||||
|
||||
/// Seconds to wait before [secs] may be spent (0 = now; spent then).
|
||||
double waitFor(double secs) {
|
||||
final now = _clock();
|
||||
level = math.min(
|
||||
cap,
|
||||
level + now.difference(_t).inMicroseconds / 1e6 * rate,
|
||||
);
|
||||
_t = now;
|
||||
if (level >= secs) {
|
||||
level -= secs;
|
||||
used += secs;
|
||||
return 0;
|
||||
}
|
||||
return (secs - level) / rate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
/// 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 <side>,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 <its
|
||||
/// preset>,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';
|
||||
|
||||
class OtaError implements Exception {
|
||||
OtaError(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class OtaCancelled extends OtaError {
|
||||
OtaCancelled() : super('cancelled');
|
||||
}
|
||||
|
||||
enum OtaState { current, noPackage, staged, applied }
|
||||
|
||||
class OtaResult {
|
||||
OtaResult(this.state, {this.package, this.versionAfter, this.airtime = 0});
|
||||
final OtaState state;
|
||||
final OtaPackage? package;
|
||||
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),
|
||||
}) : _bucket = OtaBucket(duty);
|
||||
|
||||
final MeshCoreConnector connector;
|
||||
final Contact node;
|
||||
final String password;
|
||||
final List<OtaPackage> 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;
|
||||
|
||||
final OtaBucket _bucket;
|
||||
late final RepeaterCommandService _cli = RepeaterCommandService(connector);
|
||||
StreamSubscription<Uint8List>? _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<void> _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<void>.delayed(
|
||||
left < const Duration(milliseconds: 500)
|
||||
? left
|
||||
: const Duration(milliseconds: 500),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _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<String> _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<Uint8List?> _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<Uint8List?>();
|
||||
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<void> _write(int sid, int off, List<int> 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<int>)?> _missing() async {
|
||||
for (var attempt = 0; attempt < 2; attempt++) {
|
||||
await _keepSide();
|
||||
await _spend(_reqCost(2, 160));
|
||||
final got = Completer<Uint8List>();
|
||||
Uint8List? tag;
|
||||
final early = <Uint8List>[];
|
||||
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<int>)?> _settled() async {
|
||||
var lost = 0;
|
||||
(int, List<int>)? 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<void> _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<bool>();
|
||||
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<void> _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<bool> _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<void>.delayed(const Duration(milliseconds: 250));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<void> _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<void> _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<List<int>?> _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<int>.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<void> _textRounds(Uint8List data, List<int> 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<OtaResult> 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 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, airtime: airtime);
|
||||
}
|
||||
final pick = otaPick(packages, base);
|
||||
if (pick.kind == OtaPickKind.current) {
|
||||
log('the node already runs ${pick.package!.name}');
|
||||
return OtaResult(
|
||||
OtaState.current,
|
||||
package: pick.package,
|
||||
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, airtime: airtime);
|
||||
}
|
||||
final pkg = pick.package!;
|
||||
final data = pkg.data;
|
||||
log('package ${pkg.name} (delta, ${data.length} B)');
|
||||
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<int>.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user