feat(#780): manual fake radio runner (tool/fake_radio.dart)

dart run tool/fake_radio.dart --profile offband|stock --port 5000
[--seed file] serves the fake on TCP so the desktop app can connect
with no hardware. Its clock follows real time, so ACKs and remote
replies arrive. Console: dm, chan, drop, status, quit. --seed takes an
offband-fake-radio-seed file (contacts with types and routes, channels
with secrets, remote nodes with passwords and firmware flavor) or a
captured trace. Format and the capture/manifest tools documented in
tool/fake_radio/README.md.

The TCP server moves to its own pure-Dart file (fake_radio_tcp.dart)
so dart run can load it; fake_radio_adapters re-exports it. Tests: the
README's example seed parses (docs can't drift), bad seeds are refused,
a trace works as a seed, the real connector connects and a console dm
lands, and the actual dart run process serves a client and quits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat/758-fake-radio-ci
diffwireauto 2 months ago
parent 2d3304cff4
commit 134304280c

@ -0,0 +1,189 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.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_runner.dart';
import '../support/fake_radio/fake_radio_trace.dart';
// #780 (C3 of #755): the manual runner, its seed files and its console.
/// The example seed in tool/fake_radio/README.md, so the docs stay valid.
Map<String, dynamic> _readmeSeed() {
final readme = File('tool/fake_radio/README.md').readAsStringSync();
final block = RegExp(r'```json\r?\n([\s\S]*?)\r?\n```').firstMatch(readme)!;
return jsonDecode(block.group(1)!) as Map<String, dynamic>;
}
void main() {
group('seed files', () {
test('the README example parses into the radio it describes', () {
final radio = parseFakeRadioSeedFile(
_readmeSeed(),
profile: FakeRadioProfile.offband(),
);
expect(radio.contacts.map((c) => c.name), ['Alpha', 'Routed', 'Hilltop']);
expect(radio.contacts[1].outPathLength, 1);
expect(radio.contacts[2].type, fwAdvTypeRepeater);
expect(radio.channels.keys, [0, 1]);
expect(radio.channels[1]!.secret, List<int>.filled(16, 0x5A));
expect(radio.remoteNodes.single.contact.name, 'Hilltop');
});
test('a wrong format, a bad type, or an unknown node is refused', () {
final p = FakeRadioProfile.offband();
expect(
() => parseFakeRadioSeedFile({'format': 'x'}, profile: p),
throwsFormatException,
);
final badType = _readmeSeed()
..['contacts'] = [
{'name': 'X', 'key': '11', 'type': 'toaster'},
];
expect(
() => parseFakeRadioSeedFile(badType, profile: p),
throwsFormatException,
);
final badNode = _readmeSeed()
..['remote_nodes'] = [
{'contact': 'Nobody'},
];
expect(
() => parseFakeRadioSeedFile(badNode, profile: p),
throwsFormatException,
);
});
test('a captured trace works as a seed', () {
final source = FakeRadio(profile: FakeRadioProfile.stock());
final file =
File('${Directory.systemTemp.createTempSync('trace').path}/t.json')
..writeAsStringSync(
FakeRadioTrace.record(source, captureRequests()).toJson(),
);
final radio = fakeRadioFromFile(file.path, profile: 'offband');
expect(radio.profile.offband, isFalse); // the trace decides
expect(radio.name, source.name);
});
});
group('runner against the real connector', () {
late OffbandDatabase db;
late MeshCoreConnector connector;
late FakeRadioRunner runner;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
runner = await FakeRadioRunner.start(
radio: parseFakeRadioSeedFile(
_readmeSeed(),
profile: FakeRadioProfile.offband(),
),
address: InternetAddress.loopbackIPv4,
port: 0,
);
});
tearDown(() async {
await connector.disconnect();
await runner.close();
BlobStore.clearTestOverride();
await db.close();
});
Future<void> until(bool Function() done, String what) async {
final sw = Stopwatch()..start();
while (!done()) {
if (sw.elapsed > const Duration(seconds: 10)) fail('timed out: $what');
await Future<void>.delayed(const Duration(milliseconds: 10));
}
}
test(
'the app connects over TCP and console "dm" delivers',
() async {
await connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: runner.server.port,
);
await until(() => connector.contacts.length == 3, 'contacts');
expect(runner.command('dm Alpha from the console'), contains('queued'));
final alpha = connector.contacts.firstWhere((c) => c.name == 'Alpha');
await until(
() => connector
.getMessages(alpha)
.any((m) => m.text == 'from the console'),
'the console DM',
);
expect(runner.command('status'), contains('1 client(s)'));
expect(runner.command('dm Nobody hi'), contains('no contact'));
expect(runner.command('frob'), contains('unknown'));
},
timeout: const Timeout(Duration(seconds: 30)),
);
});
test(
'`dart run tool/fake_radio.dart` serves a client and quits',
() async {
final root = Platform.environment['FLUTTER_ROOT'];
if (root == null) {
markTestSkipped('FLUTTER_ROOT not set: not under flutter test');
return;
}
final dart = '$root/bin/dart${Platform.isWindows ? '.bat' : ''}';
final probe = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = probe.port;
await probe.close();
final proc = await Process.start(dart, [
'run',
'tool/fake_radio.dart',
'--profile',
'stock',
'--port',
'$port',
], runInShell: Platform.isWindows);
addTearDown(proc.kill);
final out = proc.stdout.transform(utf8.decoder).asBroadcastStream();
await out
.firstWhere((l) => l.contains('on port $port'))
.timeout(const Duration(seconds: 60));
final socket = await Socket.connect(InternetAddress.loopbackIPv4, port);
addTearDown(socket.destroy);
final reply = Completer<List<int>>();
final buf = <int>[];
socket.listen((data) {
buf.addAll(data);
if (buf.length >= 3 && buf.length >= 3 + (buf[1] | buf[2] << 8)) {
if (!reply.isCompleted) reply.complete(buf.sublist(3));
}
});
socket.add(Uint8List.fromList([0x3c, 2, 0, fwCmdDeviceQuery, 3]));
final info = await reply.future.timeout(const Duration(seconds: 20));
expect(info[0], fwRespDeviceInfo);
expect(info[1], 13); // stock profile
proc.stdin.writeln('quit');
expect(await proc.exitCode.timeout(const Duration(seconds: 20)), 0);
},
timeout: const Timeout(Duration(minutes: 2)),
);
}

@ -1,105 +1,11 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'fake_radio.dart';
/// Serial framing the TCP companion link uses (firmware
/// `ArduinoSerialInterface`; client `usb_serial_frame_codec.dart`): the app
/// sends `0x3c len_lo len_hi payload`, the radio answers `0x3e len_lo len_hi
/// payload`. Written here independently of the client's codec.
const int _appToRadioStart = 0x3c;
const int _radioToAppStart = 0x3e;
/// The fake radio on a loopback TCP port, for the client's real
/// `connectTcp` path and for the desktop app (#768).
class FakeRadioTcpServer {
FakeRadioTcpServer._(this.radio, this._server) {
_server.listen(_accept);
_pushSub = radio.pushes.listen((frame) {
for (final s in _sockets) {
s.add(_wrap(frame));
}
});
_dropSub = radio.drops.listen((_) async {
for (final s in List<Socket>.of(_sockets)) {
await s.flush();
s.destroy();
}
_sockets.clear();
});
}
late final StreamSubscription<void> _dropSub;
static Future<FakeRadioTcpServer> start(
FakeRadio radio, {
InternetAddress? address,
int port = 0,
}) async {
final server = await ServerSocket.bind(
address ?? InternetAddress.loopbackIPv4,
port,
);
return FakeRadioTcpServer._(radio, server);
}
final FakeRadio radio;
final ServerSocket _server;
final List<Socket> _sockets = [];
late final StreamSubscription<Uint8List> _pushSub;
String get host => _server.address.address;
int get port => _server.port;
void _accept(Socket socket) {
_sockets.add(socket);
final buffer = <int>[];
socket.listen(
(data) {
buffer.addAll(data);
while (true) {
final start = buffer.indexOf(_appToRadioStart);
if (start < 0) {
buffer.clear();
return;
}
if (start > 0) buffer.removeRange(0, start);
if (buffer.length < 3) return;
final len = buffer[1] | (buffer[2] << 8);
if (buffer.length < 3 + len) return;
final payload = Uint8List.fromList(buffer.sublist(3, 3 + len));
buffer.removeRange(0, 3 + len);
for (final reply in radio.handle(payload)) {
socket.add(_wrap(reply));
}
}
},
onDone: () => _sockets.remove(socket),
onError: (_) => _sockets.remove(socket),
);
}
static Uint8List _wrap(Uint8List payload) {
final out = Uint8List(3 + payload.length);
out[0] = _radioToAppStart;
out[1] = payload.length & 0xFF;
out[2] = (payload.length >> 8) & 0xFF;
out.setRange(3, out.length, payload);
return out;
}
Future<void> close() async {
await _pushSub.cancel();
await _dropSub.cancel();
for (final s in List<Socket>.of(_sockets)) {
s.destroy();
}
await _server.close();
}
}
export 'fake_radio_tcp.dart';
/// The fake radio plugged straight into the connector's test seam: no
/// sockets, so widget tests stay fast (#768). Replies arrive on a later

@ -0,0 +1,183 @@
import 'dart:async';
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';
import 'fake_radio_tcp.dart';
import 'fake_radio_trace.dart';
import 'fake_remote_node.dart';
// Pure Dart: what `dart run tool/fake_radio.dart` runs (#780). Format of seed
// files: tool/fake_radio/README.md.
/// A fake radio serving TCP, with its clock following real time so ACKs and
/// remote replies arrive while someone uses the app against it.
class FakeRadioRunner {
FakeRadioRunner._(this.radio, this.server, this._ticker);
static Future<FakeRadioRunner> start({
required FakeRadio radio,
InternetAddress? address,
int port = 5000,
Duration tick = const Duration(milliseconds: 100),
}) async {
final server = await FakeRadioTcpServer.start(
radio,
address: address ?? InternetAddress.anyIPv4,
port: port,
);
final ticker = Timer.periodic(tick, (_) => radio.clock.advance(tick));
return FakeRadioRunner._(radio, server, ticker);
}
final FakeRadio radio;
final FakeRadioTcpServer server;
final Timer _ticker;
/// Handles one console line; returns what to print.
String command(String line) {
final parts = line.trim().split(RegExp(r'\s+'));
if (parts.isEmpty || parts.first.isEmpty) return '';
switch (parts.first) {
case 'dm' when parts.length >= 3:
final name = parts[1];
final from = radio.contacts.where((c) => c.name == name).firstOrNull;
if (from == null) return 'no contact named "$name"';
radio.receiveDirect(from, parts.sublist(2).join(' '));
return 'queued a DM from $name';
case 'chan' when parts.length >= 3:
final index = int.tryParse(parts[1]);
if (index == null || !radio.channels.containsKey(index)) {
return 'no channel ${parts[1]}';
}
radio.receiveChannel(index, parts.sublist(2).join(' '));
return 'queued a message on channel $index';
case 'drop':
radio.dropConnection();
return 'dropped the link';
case 'status':
return '${radio.profile.name} on ${server.host}:${server.port}, '
'${server.clients} client(s), ${radio.received.length} commands, '
'${radio.offlineQueue.length} queued';
case 'help':
return 'dm <contact> <text> | chan <index> <text> | drop | status | quit';
default:
return 'unknown: "$line" (try help)';
}
}
Future<void> close() async {
_ticker.cancel();
await server.close();
await radio.close();
}
}
/// Builds the radio from a seed file or a captured trace (see README), or
/// the default seed when [path] is null.
FakeRadio fakeRadioFromFile(String? path, {required String profile}) {
FakeRadioProfile pick() => switch (profile) {
'offband' => FakeRadioProfile.offband(),
'stock' => FakeRadioProfile.stock(),
_ => throw ArgumentError('profile must be offband or stock: $profile'),
};
if (path == null) {
return FakeRadio(
profile: pick(),
seed: FakeRadioSeed(
contacts: [FakeContact.keyed(0x11, 'Alpha')],
channels: [FakeChannel(index: 0, name: 'Public')],
),
);
}
final text = File(path).readAsStringSync();
final json = jsonDecode(text) as Map<String, dynamic>;
if (json['format'] == 'offband-radio-trace') {
return FakeRadioTrace.parse(text).radio();
}
return parseFakeRadioSeedFile(json, profile: pick());
}
/// `offband-fake-radio-seed` v1 (tool/fake_radio/README.md).
FakeRadio parseFakeRadioSeedFile(
Map<String, dynamic> json, {
required FakeRadioProfile profile,
}) {
if (json['format'] != 'offband-fake-radio-seed' ||
json['format_version'] != 1) {
throw FormatException('not a v1 fake radio seed: ${json['format']}');
}
Uint8List hex(String s) => Uint8List.fromList([
for (var i = 0; i + 1 < s.length; i += 2)
int.parse(s.substring(i, i + 2), radix: 16),
]);
Uint8List key(String s) => s.length == 2
? Uint8List.fromList(
List<int>.filled(fwPubKeySize, int.parse(s, radix: 16)),
)
: hex(s);
const types = {
'chat': fwAdvTypeChat,
'repeater': fwAdvTypeRepeater,
'room': fwAdvTypeRoom,
'sensor': fwAdvTypeSensor,
};
final contacts = <FakeContact>[
for (final c
in (json['contacts'] as List? ?? []).cast<Map<String, dynamic>>())
FakeContact(
publicKey: key(c['key'] as String),
name: c['name'] as String,
type:
types[c['type'] ?? 'chat'] ??
(throw FormatException('unknown contact type ${c['type']}')),
outPathLength: c['path'] == null
? -1
: (c['path'] as String).length ~/ 2,
outPath: c['path'] == null ? null : hex(c['path'] as String),
),
];
final radio = FakeRadio(
profile: profile,
seed: FakeRadioSeed(
name: json['name'] as String? ?? 'Fake Radio',
freqKhz: json['freq_khz'] as int? ?? 910525,
bwHz: json['bw_hz'] as int? ?? 62500,
sf: json['sf'] as int? ?? 7,
cr: json['cr'] as int? ?? 5,
txPowerDbm: json['tx_power'] as int? ?? 20,
contacts: contacts,
channels: [
for (final c
in (json['channels'] as List? ?? []).cast<Map<String, dynamic>>())
FakeChannel(
index: c['index'] as int,
name: c['name'] as String,
secret: c['secret'] == null ? null : hex(c['secret'] as String),
),
],
),
);
for (final n
in (json['remote_nodes'] as List? ?? []).cast<Map<String, dynamic>>()) {
final contact = contacts.firstWhere(
(c) => c.name == n['contact'],
orElse: () =>
throw FormatException('remote node ${n['contact']} is not a contact'),
);
radio.addRemoteNode(
FakeRemoteNode(
contact: contact,
adminPassword: n['admin_password'] as String? ?? 'password',
guestPassword: n['guest_password'] as String? ?? '',
offband: (n['firmware'] as String? ?? 'offband') == 'offband',
),
);
}
return radio;
}

@ -0,0 +1,106 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'fake_radio.dart';
// Pure Dart (no Flutter imports), so `dart run tool/fake_radio.dart` can serve
// the fake radio to the desktop app (#780).
/// Serial framing the TCP companion link uses (firmware
/// `ArduinoSerialInterface`; client `usb_serial_frame_codec.dart`): the app
/// sends `0x3c len_lo len_hi payload`, the radio answers `0x3e len_lo len_hi
/// payload`. Written here independently of the client's codec.
const int _appToRadioStart = 0x3c;
const int _radioToAppStart = 0x3e;
/// The fake radio on a TCP port, for the client's real `connectTcp` path and
/// for the desktop app (#768, #780).
class FakeRadioTcpServer {
FakeRadioTcpServer._(this.radio, this._server) {
_server.listen(_accept);
_pushSub = radio.pushes.listen((frame) {
for (final s in _sockets) {
s.add(_wrap(frame));
}
});
_dropSub = radio.drops.listen((_) async {
for (final s in List<Socket>.of(_sockets)) {
await s.flush();
s.destroy();
}
_sockets.clear();
});
}
late final StreamSubscription<void> _dropSub;
static Future<FakeRadioTcpServer> start(
FakeRadio radio, {
InternetAddress? address,
int port = 0,
}) async {
final server = await ServerSocket.bind(
address ?? InternetAddress.loopbackIPv4,
port,
);
return FakeRadioTcpServer._(radio, server);
}
final FakeRadio radio;
final ServerSocket _server;
final List<Socket> _sockets = [];
late final StreamSubscription<Uint8List> _pushSub;
String get host => _server.address.address;
int get port => _server.port;
/// Connected clients, for the runner's status line.
int get clients => _sockets.length;
void _accept(Socket socket) {
_sockets.add(socket);
final buffer = <int>[];
socket.listen(
(data) {
buffer.addAll(data);
while (true) {
final start = buffer.indexOf(_appToRadioStart);
if (start < 0) {
buffer.clear();
return;
}
if (start > 0) buffer.removeRange(0, start);
if (buffer.length < 3) return;
final len = buffer[1] | (buffer[2] << 8);
if (buffer.length < 3 + len) return;
final payload = Uint8List.fromList(buffer.sublist(3, 3 + len));
buffer.removeRange(0, 3 + len);
for (final reply in radio.handle(payload)) {
socket.add(_wrap(reply));
}
}
},
onDone: () => _sockets.remove(socket),
onError: (_) => _sockets.remove(socket),
);
}
static Uint8List _wrap(Uint8List payload) {
final out = Uint8List(3 + payload.length);
out[0] = _radioToAppStart;
out[1] = payload.length & 0xFF;
out[2] = (payload.length >> 8) & 0xFF;
out.setRange(3, out.length, payload);
return out;
}
Future<void> close() async {
await _pushSub.cancel();
await _dropSub.cancel();
for (final s in List<Socket>.of(_sockets)) {
s.destroy();
}
await _server.close();
}
}

@ -0,0 +1,54 @@
// A fake MeshCore companion radio on TCP, for using the desktop app with no
// hardware (#780, Feature #755). Run from the repo root:
//
// dart run tool/fake_radio.dart --profile offband --port 5000
// dart run tool/fake_radio.dart --profile stock --seed my-mesh.json
// dart run tool/fake_radio.dart --seed test/fake_radio/traces/rak.json
//
// Then in the app: connect over TCP to this PC's address, port 5000. Seed
// files and console commands: tool/fake_radio/README.md. Test code only: it
// lives under test/ and tool/ and never ships in the app.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../test/support/fake_radio/fake_radio_runner.dart';
Future<void> main(List<String> args) async {
var profile = 'offband';
var port = 5000;
String? seed;
for (var i = 0; i < args.length; i++) {
switch (args[i]) {
case '--profile' when i + 1 < args.length:
profile = args[++i];
case '--port' when i + 1 < args.length:
port = int.parse(args[++i]);
case '--seed' when i + 1 < args.length:
seed = args[++i];
default:
stderr.writeln(
'usage: dart run tool/fake_radio.dart '
'[--profile offband|stock] [--port 5000] [--seed file.json]',
);
exit(64);
}
}
final radio = fakeRadioFromFile(seed, profile: profile);
final runner = await FakeRadioRunner.start(radio: radio, port: port);
stdout.writeln(
'Fake radio "${radio.name}" (${radio.profile.name}) on port '
'${runner.server.port}. ${radio.contacts.length} contact(s), '
'${radio.channels.length} channel(s). Type "help" for commands.',
);
await for (final line
in stdin.transform(utf8.decoder).transform(const LineSplitter())) {
if (line.trim() == 'quit') break;
final out = runner.command(line);
if (out.isNotEmpty) stdout.writeln(out);
}
await runner.close();
}

@ -0,0 +1,83 @@
# Fake radio tools
A software MeshCore companion radio for tests and for using the app with no hardware (Feature #755). The fake itself lives in `test/support/fake_radio/`; it never ships in the app.
## Run it for the desktop app
From the repo root:
```bash
dart run tool/fake_radio.dart --profile offband --port 5000
```
In the app, connect over TCP to this PC's address (`127.0.0.1` on the same machine) and port `5000`.
| Option | Default | Meaning |
|---|---|---|
| `--profile` | `offband` | `offband` (pinned to `offband-v1.5.0-beta7`) or `stock` (MeshCore `companion-v1.17.1`) |
| `--port` | `5000` | TCP port |
| `--seed` | built-in | a seed file (below) or a captured trace |
The radio's clock follows real time, so ACKs and remote-node replies arrive on their own.
Console commands while it runs:
| Command | Does |
|---|---|
| `dm <contact> <text>` | a DM arrives from that contact |
| `chan <index> <text>` | a channel message arrives (MeshCore puts the sender in the text: `Name: hi`) |
| `drop` | drops the link, as a radio losing power would |
| `status` | profile, port, clients, commands received |
| `quit` | stops |
## Seed file
```json
{
"format": "offband-fake-radio-seed",
"format_version": 1,
"name": "Fake Radio",
"freq_khz": 910525,
"bw_hz": 62500,
"sf": 7,
"cr": 5,
"tx_power": 20,
"contacts": [
{ "name": "Alpha", "key": "11" },
{ "name": "Routed", "key": "22", "path": "9a" },
{ "name": "Hilltop", "key": "51", "type": "repeater" }
],
"channels": [
{ "index": 0, "name": "Public" },
{ "index": 1, "name": "#oki", "secret": "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" }
],
"remote_nodes": [
{ "contact": "Hilltop", "admin_password": "password", "firmware": "offband" }
]
}
```
- `key`: two hex digits (repeated to a 32-byte key) or the full 64-hex key.
- `type`: `chat` (default), `repeater`, `room`, `sensor`.
- `path`: hex route bytes; leave it out for a contact reached by flood.
- `secret`: 16-byte channel secret in hex; zeros if left out.
- `remote_nodes`: contacts that answer login and CLI. `firmware` is `offband` or `stock`; their CLI replies differ where the firmware does (`version`, extra `set radio` parts).
Everything is optional except `format`, `format_version` and each entry's `name` and `key`.
## Capture a real radio
`capture_trace.py` records a radio's replies to the requests a client sends on connect, so the fake can be checked against real firmware:
```bash
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
```
Close the app first: only one program can hold the serial port. The capture is read-only. `--drain-queue` also syncs queued messages, which removes them from the radio. Use `--no-dtr` for ESP32 boards with USB-Serial/JTAG (vendor ID 303A).
A trace works as a seed too: `--seed` with a trace file makes the fake hold what the recorded radio held.
## Protocol manifests
`gen_protocol_manifest.py` reads companion firmware source at a git ref and writes the codes, capability bits and version it defines. The pinned copies in `test/support/fake_radio/manifests/` came from it. OffbandMesh/meshcore-firmware#1318 will publish them from firmware CI instead.
Loading…
Cancel
Save

Powered by TurnKey Linux.