diff --git a/test/fake_radio/fake_radio_trace_test.dart b/test/fake_radio/fake_radio_trace_test.dart new file mode 100644 index 00000000..6f74dd1c --- /dev/null +++ b/test/fake_radio/fake_radio_trace_test.dart @@ -0,0 +1,128 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../support/fake_radio/fake_radio.dart'; +import '../support/fake_radio/fake_radio_codes.dart'; +import '../support/fake_radio/fake_radio_profile.dart'; +import '../support/fake_radio/fake_radio_seed.dart'; +import '../support/fake_radio/fake_radio_trace.dart'; + +// #776 (B5 of #755): record a session, seed a fake from it, replay it. +// Real-radio traces arrive at D1 (#783/#784); here the recording is the fake's. + +FakeRadio _richRadio({FakeRadioProfile? profile}) { + final routed = FakeContact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + name: 'Routed', + type: fwAdvTypeRepeater, + outPathLength: 2, + outPath: Uint8List.fromList([0xAB, 0xCD]), + latE6: 39100000, + lonE6: -84500000, + lastmod: 1790000500, + ); + return FakeRadio( + profile: profile, + seed: FakeRadioSeed( + name: 'Base Station', + freqKhz: 909750, + bwHz: 500000, + sf: 10, + latE6: 39200000, + lonE6: -84400000, + customVars: {'gps': '1'}, + autoAddConfig: 5, + autoAddMaxHops: 3, + contacts: [FakeContact.keyed(0x11, 'Alpha'), routed], + channels: [ + FakeChannel(index: 0, name: 'Public'), + FakeChannel( + index: 2, + name: '#oki', + secret: Uint8List.fromList(List.filled(16, 0x5A)), + ), + ], + ), + )..blockedKeys.add(Uint8List.fromList(List.filled(32, 0x99))); +} + +void main() { + for (final profile in [FakeRadioProfile.offband, FakeRadioProfile.stock]) { + test( + '${profile().name}: a fake seeded from a recording replays it exactly', + () { + final recording = FakeRadioTrace.record( + _richRadio(profile: profile()), + captureRequests(), + ); + // Through the file format, as a real capture would arrive. + final trace = FakeRadioTrace.parse(recording.toJson()); + expect(trace.replay(trace.radio()), isEmpty); + }, + ); + } + + test('a recorded reply the fake disagrees with is reported, by step', () { + final trace = FakeRadioTrace.record(_richRadio(), captureRequests()); + // The unknown-command reply: nothing in the seed comes from it, so the + // fake can't absorb the change. + final step = trace.steps.indexWhere((s) => s.request[0] == 0x7E); + trace.steps[step].replies[0][1] = fwErrBadState; + final diffs = trace.replay(trace.radio()); + expect(diffs, hasLength(1)); + expect(diffs.single, startsWith('step $step ')); + }); + + test('a missing or extra reply is reported', () { + final trace = FakeRadioTrace.record(_richRadio(), captureRequests()); + trace.steps.first.replies.add(Uint8List.fromList([fwRespOk])); + expect(trace.replay(trace.radio()).single, contains('recorded 2')); + }); + + test( + "bytes past a channel name's NUL are firmware leftovers, not a diff", + () { + final trace = FakeRadioTrace.record(_richRadio(), captureRequests()); + final info = trace.steps + .expand((s) => s.replies) + .firstWhere((r) => r[0] == fwRespChannelInfo); + info[2 + 'Public'.length + 3] = 0xEE; // stale byte from an earlier frame + expect(trace.replay(trace.radio()), isEmpty); + }, + ); + + test('the profile comes from what DEVICE_INFO recorded', () { + final offband = FakeRadioTrace.record(_richRadio(), captureRequests()); + final p = offband.profile(); + expect(p.offband, isTrue); + expect(p.firmwareVerCode, 22); + expect(p.versionString, '1.5.0-1.17.0'); + expect(p.offbandCaps, 0x22); + expect(p.deviceInfoTailBytes, 5); + + final stock = FakeRadioTrace.record( + _richRadio(profile: FakeRadioProfile.stock()), + captureRequests(), + ).profile(); + expect(stock.offband, isFalse); + expect(stock.deviceInfoTailBytes, 0); + }); + + test('an older Offband build with a shorter tail replays too', () { + final old = FakeRadioProfile( + name: 'offband-v16', + firmwareVerCode: 16, + versionString: '1.2.0-1.15.0', + offband: true, + offbandCaps: 0x02, + deviceInfoTailBytes: 2, // caps + FEM state only + ); + final trace = FakeRadioTrace.record( + _richRadio(profile: old), + captureRequests(), + ); + expect(trace.steps.first.replies.single.length, 84); + expect(trace.replay(trace.radio()), isEmpty); + }); +} diff --git a/test/support/fake_radio/fake_radio.dart b/test/support/fake_radio/fake_radio.dart index 0ce6571f..b4472b53 100644 --- a/test/support/fake_radio/fake_radio.dart +++ b/test/support/fake_radio/fake_radio.dart @@ -721,12 +721,16 @@ class FakeRadio { ..addByte(clientRepeat ? 1 : 0) ..addByte(pathHashMode); if (profile.offband) { - b - ..addByte(profile.offbandCaps) - ..addByte(profile.femLnaEnabled ? 1 : 0) - ..addByte(profile.offbandCaps2) - ..addByte(profile.ledEnabled) - ..addByte(profile.displayMode); + // Older Offband builds send a shorter tail: v14 caps, v16 FEM state, + // v18 caps2, v21 led/display (MyMesh.cpp:2454-2504). + final tail = [ + profile.offbandCaps, + profile.femLnaEnabled ? 1 : 0, + profile.offbandCaps2, + profile.ledEnabled, + profile.displayMode, + ]; + b.add(tail.take(profile.deviceInfoTailBytes).toList()); } return b.toBytes(); } diff --git a/test/support/fake_radio/fake_radio_profile.dart b/test/support/fake_radio/fake_radio_profile.dart index 58c22443..63b9d78d 100644 --- a/test/support/fake_radio/fake_radio_profile.dart +++ b/test/support/fake_radio/fake_radio_profile.dart @@ -16,6 +16,7 @@ class FakeRadioProfile { this.ledEnabled = 0, this.displayMode = 0, this.gpsStatusText = 'detected=0', + this.deviceInfoTailBytes = 5, }); /// A companion build of [manifest]'s firmware. @@ -69,4 +70,8 @@ class FakeRadioProfile { /// What `sensors.getGpsStatusText` adds after `enabled=N ` in the 0xC1 /// reply. Board-specific in firmware; a seed value here. final String gpsStatusText; + + /// How many Offband bytes follow path_hash_mode in DEVICE_INFO (5 on code + /// 21+; fewer on older builds). A trace sets it from what it recorded. + final int deviceInfoTailBytes; } diff --git a/test/support/fake_radio/fake_radio_trace.dart b/test/support/fake_radio/fake_radio_trace.dart new file mode 100644 index 00000000..cb65f97c --- /dev/null +++ b/test/support/fake_radio/fake_radio_trace.dart @@ -0,0 +1,282 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'fake_radio.dart'; +import 'fake_radio_codes.dart'; +import 'fake_radio_profile.dart'; +import 'fake_radio_seed.dart'; + +/// A recorded session with a radio (#776): each request and the reply frames +/// it got, from `tool/fake_radio/capture_trace.py` on real hardware or from +/// [FakeRadioTrace.record] on the fake. +class FakeRadioTrace { + FakeRadioTrace({required this.label, required this.steps}); + + factory FakeRadioTrace.parse(String text) { + final json = jsonDecode(text) as Map; + if (json['format'] != 'offband-radio-trace' || + json['format_version'] != 1) { + throw FormatException('not a v1 radio trace: ${json['format']}'); + } + Uint8List hex(Object? s) { + final str = s as String; + return Uint8List.fromList([ + for (var i = 0; i < str.length; i += 2) + int.parse(str.substring(i, i + 2), radix: 16), + ]); + } + + return FakeRadioTrace( + label: json['label'] as String, + steps: [ + for (final s in json['steps'] as List) + FakeTraceStep( + request: hex((s as Map)['request']), + replies: [for (final r in s['replies'] as List) hex(r)], + ), + ], + ); + } + + factory FakeRadioTrace.load(String path) => + FakeRadioTrace.parse(File(path).readAsStringSync()); + + /// Runs [requests] through [radio] and records what it answers. + factory FakeRadioTrace.record( + FakeRadio radio, + List requests, { + String label = 'fake', + }) => FakeRadioTrace( + label: label, + steps: [ + for (final r in requests) + FakeTraceStep(request: r, replies: radio.handle(r)), + ], + ); + + final String label; + final List steps; + + String toJson() => const JsonEncoder.withIndent(' ').convert({ + 'format': 'offband-radio-trace', + 'format_version': 1, + 'label': label, + 'steps': [ + for (final s in steps) + { + 'request': _hex(s.request), + 'replies': [for (final r in s.replies) _hex(r)], + 'pushes': [], + }, + ], + }); + + static String _hex(List b) => + b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); + + Iterable _replies(int code) => + steps.expand((s) => s.replies).where((r) => r.isNotEmpty && r[0] == code); + + /// The profile the recorded radio reported in DEVICE_INFO. + FakeRadioProfile profile() { + final info = _replies(fwRespDeviceInfo).first; + final offband = info.length > 82; + int at(int i) => i < info.length ? info[i] : 0; + final gps = _replies(fwOffbandGps).firstOrNull; + var gpsText = 'detected=0'; + if (gps != null) { + final text = _cstr(gps, 1, gps.length - 1); + final space = text.indexOf(' '); + gpsText = space < 0 ? '' : text.substring(space + 1); + } + return FakeRadioProfile( + name: label, + firmwareVerCode: info[1], + versionString: _cstr(info, 60, 20), + offband: offband, + offbandCaps: at(82), + femLnaEnabled: at(83) != 0, + offbandCaps2: at(84), + ledEnabled: at(85), + displayMode: at(86), + gpsStatusText: gpsText, + deviceInfoTailBytes: offband ? info.length - 82 : 0, + ); + } + + /// A seed that makes the fake hold what the recorded radio held. + FakeRadioSeed seed() { + final info = _replies(fwRespDeviceInfo).first; + final self = _replies(fwRespSelfInfo).first; + final bd = ByteData.sublistView(self); + final batt = _replies(fwRespBattAndStorage).firstOrNull; + final time = _replies(fwRespCurrTime).firstOrNull; + final vars = _replies(fwRespCustomVars).firstOrNull; + final auto = _replies(fwRespAutoAddConfig).firstOrNull; + return FakeRadioSeed( + name: utf8.decode(self.sublist(58), allowMalformed: true), + publicKey: self.sublist(4, 36), + txPowerDbm: bd.getInt8(2), + maxTxPowerDbm: bd.getInt8(3), + latE6: bd.getInt32(36, Endian.little), + lonE6: bd.getInt32(40, Endian.little), + multiAcks: self[44], + advertLocPolicy: self[45], + telemetryModes: self[46], + manualAddContacts: self[47], + freqKhz: bd.getUint32(48, Endian.little), + bwHz: bd.getUint32(52, Endian.little), + sf: self[56], + cr: self[57], + maxContacts: info[2] * 2, + maxChannels: info[3], + blePin: ByteData.sublistView(info).getUint32(4, Endian.little), + buildDate: _cstr(info, 8, 12), + manufacturer: _cstr(info, 20, 40), + clientRepeat: info.length > 80 && info[80] != 0, + pathHashMode: info.length > 81 ? info[81] : 0, + batteryMillivolts: batt == null + ? 4100 + : ByteData.sublistView(batt).getUint16(1, Endian.little), + storageUsedKb: batt == null + ? 12 + : ByteData.sublistView(batt).getUint32(3, Endian.little), + storageTotalKb: batt == null + ? 256 + : ByteData.sublistView(batt).getUint32(7, Endian.little), + deviceTime: time == null + ? 1790000000 + : ByteData.sublistView(time).getUint32(1, Endian.little), + customVars: vars == null ? const {} : _vars(vars), + autoAddConfig: auto?[1] ?? 0, + autoAddMaxHops: auto?[2] ?? 0, + contacts: [for (final c in _replies(fwRespContact)) _contact(c)], + channels: [ + for (final c in _replies(fwRespChannelInfo)) + FakeChannel( + index: c[1], + name: _cstr(c, 2, 32), + secret: c.sublist(34, 50), + ), + ], + ); + } + + /// Keys the recorded radio listed in its Offband block list. + List blockedKeys() => [ + for (final f in _replies(fwOffbandBlock)) + if (f.length >= 3 + fwPubKeySize && f[1] == fwBlockList && f[2] < 0xFE) + f.sublist(3, 3 + fwPubKeySize), + ]; + + /// A fake radio holding what the recorded radio held. + FakeRadio radio() => + FakeRadio(seed: seed(), profile: profile()) + ..blockedKeys.addAll(blockedKeys()); + + /// Replays every request into [radio] and lists where its replies differ + /// from the recorded ones. Channel names are compared up to their NUL: + /// firmware fills that field with `strcpy`, so bytes past it are leftovers. + List replay(FakeRadio radio) { + final diffs = []; + for (var i = 0; i < steps.length; i++) { + final s = steps[i]; + final got = radio.handle(s.request); + final want = s.replies; + final name = 'step $i (request ${_hex(s.request.take(2).toList())})'; + if (got.length != want.length) { + diffs.add('$name: ${got.length} replies, recorded ${want.length}'); + continue; + } + for (var j = 0; j < got.length; j++) { + if (_hex(_normalize(got[j])) != _hex(_normalize(want[j]))) { + diffs.add( + '$name reply $j:\n fake ${_hex(got[j])}\n' + ' recorded ${_hex(want[j])}', + ); + } + } + } + return diffs; + } + + static Uint8List _normalize(Uint8List f) { + if (f.isEmpty || f[0] != fwRespChannelInfo || f.length < 34) return f; + final out = Uint8List.fromList(f); + final nul = out.indexOf(0, 2); + if (nul >= 0 && nul < 34) out.fillRange(nul, 34, 0); + return out; + } + + static FakeContact _contact(Uint8List c) { + final bd = ByteData.sublistView(c); + final pathLen = c[35]; + return FakeContact( + publicKey: c.sublist(1, 33), + type: c[33], + flags: c[34], + outPathLength: pathLen == 0xFF ? -1 : pathLen, + outPath: c.sublist(36, 36 + fwMaxPathSize), + name: _cstr(c, 100, 32), + lastAdvert: bd.getUint32(132, Endian.little), + latE6: bd.getInt32(136, Endian.little), + lonE6: bd.getInt32(140, Endian.little), + lastmod: bd.getUint32(144, Endian.little), + ); + } + + static Map _vars(Uint8List f) { + final text = utf8.decode(f.sublist(1), allowMalformed: true); + return { + for (final pair in text.split(',').where((p) => p.contains(':'))) + pair.substring(0, pair.indexOf(':')): pair.substring( + pair.indexOf(':') + 1, + ), + }; + } + + static String _cstr(Uint8List b, int at, int width) { + final end = at + width > b.length ? b.length : at + width; + final field = b.sublist(at, end); + final nul = field.indexOf(0); + return utf8.decode( + nul < 0 ? field : field.sublist(0, nul), + allowMalformed: true, + ); + } +} + +class FakeTraceStep { + FakeTraceStep({required this.request, required this.replies}); + + final Uint8List request; + final List replies; +} + +/// The read-only requests `capture_trace.py` sends, in the same order, so a +/// fake session and a real capture line up step for step. +List captureRequests({int channels = 8}) => [ + Uint8List.fromList([fwCmdDeviceQuery, 3]), + Uint8List.fromList([ + fwCmdAppStart, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ...utf8.encode('offband-trace'), + ]), + Uint8List.fromList([fwCmdGetDeviceTime]), + Uint8List.fromList([fwCmdGetBattAndStorage]), + Uint8List.fromList([fwCmdGetCustomVars]), + Uint8List.fromList([fwCmdGetAutoAddConfig]), + Uint8List.fromList([fwCmdGetContacts]), + for (var i = 0; i < channels; i++) Uint8List.fromList([fwCmdGetChannel, i]), + Uint8List.fromList([0x7E]), + Uint8List.fromList([fwOffbandGps]), + Uint8List.fromList([fwOffbandBlock, fwBlockList]), + Uint8List.fromList([fwOffbandPktHash, fwPktHashGet]), +]; diff --git a/tool/fake_radio/capture_trace.py b/tool/fake_radio/capture_trace.py new file mode 100644 index 00000000..a8afb6fc --- /dev/null +++ b/tool/fake_radio/capture_trace.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Record a real companion radio's replies to a fixed request script (#776). + +Feature #755 checks the fake radio against real firmware: this talks to a +radio over USB serial, sends the same read-only requests a client sends on +connect, and writes every reply frame to a trace file. The fake radio, seeded +from the trace, must then produce the same replies. + + pip install pyserial + python tool/fake_radio/capture_trace.py --port COM12 --label "RAK4631 offband-v1.5.0-beta7" \ + --out test/fake_radio/traces/offband-rak4631.json + +Read-only by default: nothing is set or sent over the air. --drain-queue also +syncs queued messages, which REMOVES them from the radio (the app won't get +them), so only use it on a test radio. + +Close the Offband app first: only one program can hold the serial port. +""" +import argparse +import datetime +import json +import sys +import time + +try: + import serial +except ImportError: + sys.exit("needs pyserial: pip install pyserial") + +APP_TO_RADIO = 0x3C # '<' +RADIO_TO_APP = 0x3E # '>' + +CMD_DEVICE_QUERY = 22 +CMD_APP_START = 1 +CMD_GET_BATT = 20 +CMD_GET_CUSTOM_VARS = 40 +CMD_GET_AUTOADD = 59 +CMD_GET_DEVICE_TIME = 5 +CMD_GET_CONTACTS = 4 +CMD_GET_CHANNEL = 31 +CMD_SYNC_NEXT = 10 +RESP_END_OF_CONTACTS = 4 +RESP_DEVICE_INFO = 13 +RESP_NO_MORE_MESSAGES = 10 + + +class Link: + def __init__(self, port, baud, dtr): + # Set the lines before opening so pyserial doesn't pulse them. RTS stays + # low always; DTR high suits nRF52 boards (USB-CDC writes wait for it), + # while ESP32 USB-Serial/JTAG boards can reset into download mode on a + # DTR change, so use --no-dtr for those (the app's #244 VID gate). + self.port = serial.Serial() + self.port.port = port + self.port.baudrate = baud + self.port.timeout = 0.05 + self.port.rts = False + self.port.dtr = dtr + self.port.open() + self.buf = bytearray() + time.sleep(1.0) + self.port.reset_input_buffer() + + def send(self, payload): + self.port.write(bytes([APP_TO_RADIO, len(payload) & 0xFF, len(payload) >> 8]) + payload) + self.port.flush() + + def frames(self, quiet=0.4, until=None, limit=5.0): + """Reply frames until [quiet] s without a frame, [until] says stop, or [limit] s.""" + out = [] + start = last = time.time() + while time.time() - start < limit: + self.buf += self.port.read(512) + got = False + while True: + at = self.buf.find(bytes([RADIO_TO_APP])) + if at < 0: + self.buf.clear() + break + del self.buf[:at] + if len(self.buf) < 3: + break + n = self.buf[1] | (self.buf[2] << 8) + if len(self.buf) < 3 + n: + break + out.append(bytes(self.buf[3:3 + n])) + del self.buf[:3 + n] + got = True + last = time.time() + if until and until(out[-1]): + return out + if not got and out and time.time() - last > quiet: + return out + if not got and not out and time.time() - start > max(quiet, 1.5): + return out + return out + + +def split(frames): + """Pushes (code >= 0x80) arrive whenever the radio likes; keep them apart.""" + replies = [f for f in frames if f and f[0] < 0x80] + pushes = [f for f in frames if f and f[0] >= 0x80] + return replies, pushes + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", required=True) + ap.add_argument("--baud", type=int, default=115200) + ap.add_argument("--label", required=True, help="radio and firmware, e.g. 'RAK4631 offband-v1.5.0-beta7'") + ap.add_argument("--out", required=True) + ap.add_argument("--drain-queue", action="store_true", + help="also sync queued messages (REMOVES them from the radio)") + ap.add_argument("--no-dtr", action="store_true", + help="keep DTR low: for ESP32 USB-Serial/JTAG boards (VID 303A)") + args = ap.parse_args() + + link = Link(args.port, args.baud, dtr=not args.no_dtr) + steps = [] + + def step(payload, **kw): + link.send(payload) + replies, pushes = split(link.frames(**kw)) + steps.append({ + "request": payload.hex(), + "replies": [r.hex() for r in replies], + "pushes": [p.hex() for p in pushes], + }) + return replies + + info = step(bytes([CMD_DEVICE_QUERY, 3])) + channels = info[0][3] if info and info[0][0] == RESP_DEVICE_INFO and len(info[0]) > 3 else 8 + step(bytes([CMD_APP_START, 0, 0, 0, 0, 0, 0, 0]) + b"offband-trace") + step(bytes([CMD_GET_DEVICE_TIME])) + step(bytes([CMD_GET_BATT])) + step(bytes([CMD_GET_CUSTOM_VARS])) + step(bytes([CMD_GET_AUTOADD])) + step(bytes([CMD_GET_CONTACTS]), until=lambda f: f and f[0] == RESP_END_OF_CONTACTS, limit=60.0) + for index in range(channels): + step(bytes([CMD_GET_CHANNEL, index])) + step(bytes([0x7E])) # an unknown command: firmware's ERR reply + # Offband extensions; stock firmware answers each with ERR UNSUPPORTED. + step(bytes([0xC1])) # GPS status + step(bytes([0xC2, 0x03]), until=lambda f: len(f) >= 3 and f[0] == 0xC2 and f[2] == 0xFE) # block LIST + step(bytes([0xC6, 0x01])) # packet hash, malformed on purpose: read-only + if args.drain_queue: + for _ in range(200): + replies = step(bytes([CMD_SYNC_NEXT])) + if not replies or replies[0][0] == RESP_NO_MORE_MESSAGES: + break + + trace = { + "format": "offband-radio-trace", + "format_version": 1, + "label": args.label, + "captured": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), + "port": args.port, + "steps": steps, + } + with open(args.out, "w", encoding="utf-8") as f: + json.dump(trace, f, indent=1) + f.write("\n") + print(f"{len(steps)} steps, {sum(len(s['replies']) for s in steps)} replies -> {args.out}") + + +if __name__ == "__main__": + main()