/// 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 ` 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 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 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 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 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)? otaParseMissing(List data) { if (data.length < 5) return null; final count = data[3] | (data[4] << 8); final units = []; 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? 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; } }