feat(#601): fake radio core (frame codec, dispatch, seeded state, clock)
A MeshCore companion radio in software under test/support/fake_radio. handle() answers the handshake set the client sends (DEVICE_QUERY, APP_START, GET_CONTACTS with 'since', GET_CHANNEL, SYNC_NEXT_MESSAGE, time, battery, custom vars, auto-add, other params, advert name); every reply cites the firmware function it copies. Unknown commands get ERR_CODE_UNSUPPORTED_CMD, as MyMesh.cpp:3561 does. Codes are copied from firmware, not imported from the client, so A5 can catch client drift. Stock and Offband differ already: the DEVICE_INFO tail (82 vs 87 bytes) and set-time (stock refuses going backwards; Offband #607 accepts). All delays run on FakeClock, never wall time. 14 unit tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>feat/756-fake-radio-core
parent
426067f39a
commit
d770cef887
@ -0,0 +1,210 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../support/fake_radio/fake_clock.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';
|
||||
|
||||
Uint8List _cmd(List<int> b) => Uint8List.fromList(b);
|
||||
|
||||
int _u32(Uint8List b, int at) =>
|
||||
ByteData.sublistView(b, at, at + 4).getUint32(0, Endian.little);
|
||||
|
||||
Uint8List _le32(int v) =>
|
||||
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
|
||||
|
||||
String _cstr(Uint8List b, int at, int width) {
|
||||
final field = b.sublist(at, at + width);
|
||||
final end = field.indexOf(0);
|
||||
return utf8.decode(end < 0 ? field : field.sublist(0, end));
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('device info (#601)', () {
|
||||
test('Offband: 87 bytes with the capability tail', () {
|
||||
final f = FakeRadio().handle(_cmd([fwCmdDeviceQuery, 4])).single;
|
||||
expect(f[0], fwRespDeviceInfo);
|
||||
expect(f[1], 22);
|
||||
expect(f[2], 175); // 350 / 2
|
||||
expect(f[3], 8);
|
||||
expect(_cstr(f, 8, 12), '1 Oct 2026');
|
||||
expect(_cstr(f, 20, 40), 'Fake Radio Board');
|
||||
expect(_cstr(f, 60, 20), '1.5.0-1.17.1');
|
||||
expect(f.length, 87);
|
||||
expect(f[82], 0x22); // BLOCK | CAPLOG
|
||||
expect(f[84], 0x08); // PKT_HASH
|
||||
});
|
||||
|
||||
test('stock: ends after path hash mode (82 bytes), no Offband tail', () {
|
||||
final f = FakeRadio(
|
||||
profile: FakeRadioProfile.stockDefault,
|
||||
).handle(_cmd([fwCmdDeviceQuery, 4])).single;
|
||||
expect(f[1], 13);
|
||||
expect(_cstr(f, 60, 20), 'v1.17.1');
|
||||
expect(f.length, 82);
|
||||
});
|
||||
});
|
||||
|
||||
test('self info carries the seeded identity and radio settings', () {
|
||||
final radio = FakeRadio(
|
||||
seed: FakeRadioSeed(name: 'Base', freqKhz: 909750, bwHz: 500000, sf: 10),
|
||||
);
|
||||
final f = radio.handle(_cmd([fwCmdAppStart, ...List.filled(7, 0)])).single;
|
||||
expect(f[0], fwRespSelfInfo);
|
||||
expect(f.sublist(4, 36), radio.seed.publicKey);
|
||||
expect(_u32(f, 48), 909750);
|
||||
expect(_u32(f, 52), 500000);
|
||||
expect(f[56], 10);
|
||||
expect(f[57], 5);
|
||||
expect(utf8.decode(f.sublist(58)), 'Base');
|
||||
});
|
||||
|
||||
group('contacts', () {
|
||||
final radio = FakeRadio(
|
||||
seed: FakeRadioSeed(
|
||||
contacts: [
|
||||
FakeContact.keyed(0x11, 'Alpha', lastmod: 100),
|
||||
FakeContact.keyed(0x22, 'Bravo', lastmod: 200),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
test('start (total), one frame per contact, end (latest lastmod)', () {
|
||||
final out = radio.handle(_cmd([fwCmdGetContacts]));
|
||||
expect(out.map((f) => f[0]), [
|
||||
fwRespContactsStart,
|
||||
fwRespContact,
|
||||
fwRespContact,
|
||||
fwRespEndOfContacts,
|
||||
]);
|
||||
expect(_u32(out.first, 1), 2);
|
||||
expect(out[1].length, 148);
|
||||
expect(_cstr(out[1], 100, 32), 'Alpha');
|
||||
expect(_u32(out.last, 1), 200);
|
||||
});
|
||||
|
||||
test("'since' filters the list but START still reports the total", () {
|
||||
final out = radio.handle(_cmd([fwCmdGetContacts, ..._le32(100)]));
|
||||
expect(out.length, 3);
|
||||
expect(_u32(out.first, 1), 2);
|
||||
expect(_cstr(out[1], 100, 32), 'Bravo');
|
||||
});
|
||||
});
|
||||
|
||||
test('channels: info for a seeded slot, NOT_FOUND for an empty one', () {
|
||||
final radio = FakeRadio(
|
||||
seed: FakeRadioSeed(channels: [FakeChannel(index: 0, name: 'Public')]),
|
||||
);
|
||||
final info = radio.handle(_cmd([fwCmdGetChannel, 0])).single;
|
||||
expect(info[0], fwRespChannelInfo);
|
||||
expect(_cstr(info, 2, 32), 'Public');
|
||||
expect(info.length, 50);
|
||||
expect(radio.handle(_cmd([fwCmdGetChannel, 1])).single, [
|
||||
fwRespErr,
|
||||
fwErrNotFound,
|
||||
]);
|
||||
});
|
||||
|
||||
test('message queue drains, then NO_MORE_MESSAGES', () {
|
||||
final radio = FakeRadio()..offlineQueue.add(_cmd([0x10, 1, 2]));
|
||||
expect(radio.handle(_cmd([fwCmdSyncNextMessage])).single, [0x10, 1, 2]);
|
||||
expect(radio.handle(_cmd([fwCmdSyncNextMessage])).single, [
|
||||
fwRespNoMoreMessages,
|
||||
]);
|
||||
});
|
||||
|
||||
group('device time', () {
|
||||
test('Offband accepts a time in either direction (#607)', () {
|
||||
final radio = FakeRadio();
|
||||
expect(radio.handle(_cmd([fwCmdSetDeviceTime, ..._le32(1000)])).single, [
|
||||
fwRespOk,
|
||||
]);
|
||||
expect(radio.clock.epochSeconds, 1000);
|
||||
});
|
||||
|
||||
test('stock refuses a time earlier than its clock', () {
|
||||
final radio = FakeRadio(profile: FakeRadioProfile.stockDefault);
|
||||
expect(radio.handle(_cmd([fwCmdSetDeviceTime, ..._le32(1000)])).single, [
|
||||
fwRespErr,
|
||||
fwErrIllegalArg,
|
||||
]);
|
||||
expect(
|
||||
radio.handle(_cmd([fwCmdSetDeviceTime, ..._le32(1790000500)])).single,
|
||||
[fwRespOk],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('battery, custom vars and auto-add replies', () {
|
||||
final radio = FakeRadio(
|
||||
seed: FakeRadioSeed(customVars: {'gps': '1'}, autoAddConfig: 3),
|
||||
);
|
||||
final batt = radio.handle(_cmd([fwCmdGetBattAndStorage])).single;
|
||||
expect(batt.length, 11);
|
||||
expect(ByteData.sublistView(batt).getUint16(1, Endian.little), 4100);
|
||||
expect(
|
||||
utf8.decode(radio.handle(_cmd([fwCmdGetCustomVars])).single.sublist(1)),
|
||||
'gps:1',
|
||||
);
|
||||
expect(radio.handle(_cmd([fwCmdGetAutoAddConfig])).single, [
|
||||
fwRespAutoAddConfig,
|
||||
3,
|
||||
0,
|
||||
]);
|
||||
});
|
||||
|
||||
test('an unknown command is UNSUPPORTED, and every command is logged', () {
|
||||
final radio = FakeRadio();
|
||||
expect(radio.handle(_cmd([0x7E])).single, [fwRespErr, fwErrUnsupportedCmd]);
|
||||
expect(radio.received.single, [0x7E]);
|
||||
});
|
||||
|
||||
test('same seed, same replies', () {
|
||||
List<List<int>> run() {
|
||||
final radio = FakeRadio(
|
||||
seed: FakeRadioSeed(contacts: [FakeContact.keyed(0x11, 'Alpha')]),
|
||||
);
|
||||
return [
|
||||
for (final c in [
|
||||
[fwCmdDeviceQuery, 4],
|
||||
[fwCmdAppStart, ...List.filled(7, 0)],
|
||||
[fwCmdGetContacts],
|
||||
])
|
||||
for (final f in radio.handle(_cmd(c))) f.toList(),
|
||||
];
|
||||
}
|
||||
|
||||
expect(run(), run());
|
||||
});
|
||||
|
||||
group('fake clock', () {
|
||||
test('runs scheduled work in due order, only when advanced', () {
|
||||
final clock = FakeClock(epochSeconds: 100);
|
||||
final ran = <String>[];
|
||||
clock
|
||||
..schedule(const Duration(seconds: 2), () => ran.add('b'))
|
||||
..schedule(const Duration(seconds: 1), () => ran.add('a'));
|
||||
expect(ran, isEmpty);
|
||||
clock.advance(const Duration(seconds: 1));
|
||||
expect(ran, ['a']);
|
||||
clock.advance(const Duration(seconds: 5));
|
||||
expect(ran, ['a', 'b']);
|
||||
expect(clock.epochSeconds, 106);
|
||||
});
|
||||
|
||||
test('work scheduled while advancing runs if it falls due', () {
|
||||
final clock = FakeClock();
|
||||
final ran = <int>[];
|
||||
clock.schedule(const Duration(seconds: 1), () {
|
||||
ran.add(1);
|
||||
clock.schedule(const Duration(seconds: 1), () => ran.add(2));
|
||||
});
|
||||
clock.advance(const Duration(seconds: 3));
|
||||
expect(ran, [1, 2]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
/// The fake radio's only notion of time. Nothing it does waits on the wall
|
||||
/// clock: scheduled work runs when a test calls [advance], so the same seed and
|
||||
/// the same steps always give the same result.
|
||||
class FakeClock {
|
||||
FakeClock({int epochSeconds = 1790000000}) : _baseEpoch = epochSeconds;
|
||||
|
||||
int _baseEpoch;
|
||||
Duration _elapsed = Duration.zero;
|
||||
final List<_Scheduled> _queue = [];
|
||||
int _sequence = 0;
|
||||
|
||||
Duration get elapsed => _elapsed;
|
||||
|
||||
/// Seconds since the Unix epoch, as the radio's RTC reports it.
|
||||
int get epochSeconds => _baseEpoch + _elapsed.inSeconds;
|
||||
|
||||
/// Sets the RTC (CMD_SET_DEVICE_TIME) without moving scheduled work.
|
||||
set epochSeconds(int value) => _baseEpoch = value - _elapsed.inSeconds;
|
||||
|
||||
/// Runs [action] once [after] has elapsed on this clock.
|
||||
void schedule(Duration after, void Function() action) {
|
||||
_queue.add(_Scheduled(_elapsed + after, _sequence++, action));
|
||||
}
|
||||
|
||||
/// Moves time forward, running everything that falls due, in order. Work
|
||||
/// scheduled while advancing runs too, if it falls due before the target.
|
||||
void advance(Duration by) {
|
||||
final target = _elapsed + by;
|
||||
while (true) {
|
||||
_queue.sort((a, b) {
|
||||
final byTime = a.due.compareTo(b.due);
|
||||
return byTime != 0 ? byTime : a.sequence.compareTo(b.sequence);
|
||||
});
|
||||
if (_queue.isEmpty || _queue.first.due > target) break;
|
||||
final next = _queue.removeAt(0);
|
||||
_elapsed = next.due;
|
||||
next.action();
|
||||
}
|
||||
_elapsed = target;
|
||||
}
|
||||
|
||||
int get pending => _queue.length;
|
||||
}
|
||||
|
||||
class _Scheduled {
|
||||
_Scheduled(this.due, this.sequence, this.action);
|
||||
|
||||
final Duration due;
|
||||
final int sequence;
|
||||
final void Function() action;
|
||||
}
|
||||
@ -0,0 +1,304 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'fake_clock.dart';
|
||||
import 'fake_radio_codes.dart';
|
||||
import 'fake_radio_profile.dart';
|
||||
import 'fake_radio_seed.dart';
|
||||
|
||||
/// A MeshCore companion radio in software, for tests (#755).
|
||||
///
|
||||
/// [handle] takes one command frame (the payload the client writes) and
|
||||
/// returns the radio's immediate reply frames, in firmware order. Frames the
|
||||
/// radio sends on its own (pushes) go to [pushes]. Every reply is built the way
|
||||
/// the named firmware function builds it, in
|
||||
/// OffbandMesh/meshcore-firmware `examples/companion_radio/MyMesh.cpp`.
|
||||
class FakeRadio {
|
||||
FakeRadio({
|
||||
FakeRadioSeed? seed,
|
||||
this.profile = FakeRadioProfile.offbandDefault,
|
||||
FakeClock? clock,
|
||||
}) : seed = seed ?? FakeRadioSeed(),
|
||||
clock = clock ?? FakeClock() {
|
||||
final s = this.seed;
|
||||
name = s.name;
|
||||
txPowerDbm = s.txPowerDbm;
|
||||
freqKhz = s.freqKhz;
|
||||
bwHz = s.bwHz;
|
||||
sf = s.sf;
|
||||
cr = s.cr;
|
||||
clientRepeat = s.clientRepeat;
|
||||
pathHashMode = s.pathHashMode;
|
||||
latE6 = s.latE6;
|
||||
lonE6 = s.lonE6;
|
||||
multiAcks = s.multiAcks;
|
||||
advertLocPolicy = s.advertLocPolicy;
|
||||
telemetryModes = s.telemetryModes;
|
||||
manualAddContacts = s.manualAddContacts;
|
||||
autoAddConfig = s.autoAddConfig;
|
||||
autoAddMaxHops = s.autoAddMaxHops;
|
||||
customVars.addAll(s.customVars);
|
||||
contacts.addAll(s.contacts);
|
||||
for (final c in s.channels) {
|
||||
channels[c.index] = c;
|
||||
}
|
||||
this.clock.epochSeconds = s.deviceTime;
|
||||
}
|
||||
|
||||
final FakeRadioSeed seed;
|
||||
final FakeRadioProfile profile;
|
||||
final FakeClock clock;
|
||||
|
||||
// Live state, starting from the seed. Commands change it as firmware would.
|
||||
late String name;
|
||||
late int txPowerDbm;
|
||||
late int freqKhz;
|
||||
late int bwHz;
|
||||
late int sf;
|
||||
late int cr;
|
||||
late bool clientRepeat;
|
||||
late int pathHashMode;
|
||||
late int latE6;
|
||||
late int lonE6;
|
||||
late int multiAcks;
|
||||
late int advertLocPolicy;
|
||||
late int telemetryModes;
|
||||
late int manualAddContacts;
|
||||
late int autoAddConfig;
|
||||
late int autoAddMaxHops;
|
||||
final Map<String, String> customVars = {};
|
||||
final List<FakeContact> contacts = [];
|
||||
final Map<int, FakeChannel> channels = {};
|
||||
|
||||
/// Frames waiting for CMD_SYNC_NEXT_MESSAGE (the firmware's offline queue).
|
||||
final List<Uint8List> offlineQueue = [];
|
||||
|
||||
/// Every command frame received, in order, for assertions.
|
||||
final List<Uint8List> received = [];
|
||||
|
||||
final StreamController<Uint8List> _pushes =
|
||||
StreamController<Uint8List>.broadcast(sync: true);
|
||||
|
||||
/// Frames the radio sends unprompted.
|
||||
Stream<Uint8List> get pushes => _pushes.stream;
|
||||
|
||||
void push(Uint8List frame) => _pushes.add(frame);
|
||||
|
||||
Future<void> close() => _pushes.close();
|
||||
|
||||
/// Replies to one command frame, in the order the firmware writes them.
|
||||
List<Uint8List> handle(Uint8List cmd) {
|
||||
received.add(Uint8List.fromList(cmd));
|
||||
if (cmd.isEmpty) return [];
|
||||
final len = cmd.length;
|
||||
switch (cmd[0]) {
|
||||
case fwCmdDeviceQuery when len >= 2:
|
||||
return [deviceInfoFrame()];
|
||||
case fwCmdAppStart when len >= 8:
|
||||
return [selfInfoFrame()];
|
||||
case fwCmdGetContacts:
|
||||
return _contacts(len >= 5 ? _u32At(cmd, 1) : 0);
|
||||
case fwCmdGetDeviceTime:
|
||||
return [_concat(fwRespCurrTime, _u32(clock.epochSeconds))];
|
||||
case fwCmdSetDeviceTime when len >= 5:
|
||||
// Offband (MyMesh.cpp:2765, #607) accepts any time; stock (upstream
|
||||
// a366955c MyMesh.cpp:1240) refuses one earlier than its clock.
|
||||
final t = _u32At(cmd, 1);
|
||||
if (profile.offband || t >= clock.epochSeconds) {
|
||||
clock.epochSeconds = t;
|
||||
return [okFrame()];
|
||||
}
|
||||
return [errFrame(fwErrIllegalArg)];
|
||||
case fwCmdSyncNextMessage:
|
||||
return [
|
||||
offlineQueue.isNotEmpty
|
||||
? offlineQueue.removeAt(0)
|
||||
: Uint8List.fromList([fwRespNoMoreMessages]),
|
||||
];
|
||||
case fwCmdGetBattAndStorage:
|
||||
return [
|
||||
Uint8List.fromList([
|
||||
fwRespBattAndStorage,
|
||||
..._u16(seed.batteryMillivolts),
|
||||
..._u32(seed.storageUsedKb),
|
||||
..._u32(seed.storageTotalKb),
|
||||
]),
|
||||
];
|
||||
case fwCmdGetChannel when len >= 2:
|
||||
return [_channelInfo(cmd[1])];
|
||||
case fwCmdGetCustomVars:
|
||||
return [customVarsFrame()];
|
||||
case fwCmdGetAutoAddConfig:
|
||||
return [
|
||||
Uint8List.fromList([
|
||||
fwRespAutoAddConfig,
|
||||
autoAddConfig,
|
||||
autoAddMaxHops,
|
||||
]),
|
||||
];
|
||||
case fwCmdSetAutoAddConfig when len >= 2:
|
||||
autoAddConfig = cmd[1];
|
||||
if (len >= 3) autoAddMaxHops = cmd[2] > 64 ? 64 : cmd[2];
|
||||
return [okFrame()];
|
||||
case fwCmdSetOtherParams when len >= 2:
|
||||
// MyMesh.cpp:2974.
|
||||
manualAddContacts = cmd[1];
|
||||
if (len >= 3) telemetryModes = cmd[2];
|
||||
if (len >= 4) advertLocPolicy = cmd[3];
|
||||
if (len >= 5) multiAcks = cmd[4];
|
||||
return [okFrame()];
|
||||
case fwCmdSetAdvertName when len >= 2:
|
||||
name = utf8.decode(cmd.sublist(1), allowMalformed: true);
|
||||
if (name.length > 31) name = name.substring(0, 31);
|
||||
return [okFrame()];
|
||||
default:
|
||||
// MyMesh.cpp:3561: anything else, including Offband commands on a radio
|
||||
// that doesn't answer them, is an unsupported command.
|
||||
return [errFrame(fwErrUnsupportedCmd)];
|
||||
}
|
||||
}
|
||||
|
||||
/// `writeOKFrame` (MyMesh.cpp:258).
|
||||
static Uint8List okFrame() => Uint8List.fromList([fwRespOk]);
|
||||
|
||||
/// `writeErrFrame` (MyMesh.cpp:263).
|
||||
static Uint8List errFrame(int code) => Uint8List.fromList([fwRespErr, code]);
|
||||
|
||||
/// The CMD_DEVICE_QUERY reply (MyMesh.cpp:2420-2505). Stock firmware ends
|
||||
/// after path_hash_mode (byte 81); Offband appends its capability tail.
|
||||
Uint8List deviceInfoFrame() {
|
||||
final b = BytesBuilder()
|
||||
..addByte(fwRespDeviceInfo)
|
||||
..addByte(profile.firmwareVerCode)
|
||||
..addByte(seed.maxContacts ~/ 2)
|
||||
..addByte(seed.maxChannels)
|
||||
..add(_u32(seed.blePin))
|
||||
..add(_fixed(seed.buildDate, 12))
|
||||
..add(_fixed(seed.manufacturer, 40))
|
||||
..add(_fixed(profile.versionString, 20))
|
||||
..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);
|
||||
}
|
||||
return b.toBytes();
|
||||
}
|
||||
|
||||
/// The CMD_APP_START reply (MyMesh.cpp:2553-2586).
|
||||
Uint8List selfInfoFrame() {
|
||||
final b = BytesBuilder()
|
||||
..addByte(fwRespSelfInfo)
|
||||
..addByte(fwAdvTypeChat)
|
||||
..addByte(txPowerDbm & 0xFF)
|
||||
..addByte(seed.maxTxPowerDbm & 0xFF)
|
||||
..add(seed.publicKey)
|
||||
..add(_i32(latE6))
|
||||
..add(_i32(lonE6))
|
||||
..addByte(multiAcks)
|
||||
..addByte(advertLocPolicy)
|
||||
..addByte(telemetryModes)
|
||||
..addByte(manualAddContacts)
|
||||
..add(_u32(freqKhz))
|
||||
..add(_u32(bwHz))
|
||||
..addByte(sf)
|
||||
..addByte(cr)
|
||||
..add(utf8.encode(name));
|
||||
return b.toBytes();
|
||||
}
|
||||
|
||||
/// CMD_GET_CONTACTS (MyMesh.cpp:2716-2736) and the iterator that streams the
|
||||
/// list (MyMesh.cpp:3867-3879). The firmware sends one contact per loop
|
||||
/// tick; the order is the same, so the fake sends them together.
|
||||
List<Uint8List> _contacts(int since) {
|
||||
final out = <Uint8List>[
|
||||
_concat(
|
||||
fwRespContactsStart,
|
||||
_u32(contacts.length),
|
||||
), // total, not filtered
|
||||
];
|
||||
var mostRecent = 0;
|
||||
for (final c in contacts) {
|
||||
if (c.lastmod > since) {
|
||||
out.add(contactFrame(fwRespContact, c));
|
||||
if (c.lastmod > mostRecent) mostRecent = c.lastmod;
|
||||
}
|
||||
}
|
||||
out.add(_concat(fwRespEndOfContacts, _u32(mostRecent)));
|
||||
return out;
|
||||
}
|
||||
|
||||
/// `writeContactRespFrame` (MyMesh.cpp:276-297).
|
||||
static Uint8List contactFrame(int code, FakeContact c) {
|
||||
final path = Uint8List(fwMaxPathSize)
|
||||
..setRange(
|
||||
0,
|
||||
c.outPath.length > fwMaxPathSize ? fwMaxPathSize : c.outPath.length,
|
||||
c.outPath,
|
||||
);
|
||||
return (BytesBuilder()
|
||||
..addByte(code)
|
||||
..add(c.publicKey)
|
||||
..addByte(c.type)
|
||||
..addByte(c.flags)
|
||||
..addByte(c.outPathLength < 0 ? 0xFF : c.outPathLength)
|
||||
..add(path)
|
||||
..add(_fixed(c.name, 32))
|
||||
..add(_u32(c.lastAdvert))
|
||||
..add(_i32(c.latE6))
|
||||
..add(_i32(c.lonE6))
|
||||
..add(_u32(c.lastmod)))
|
||||
.toBytes();
|
||||
}
|
||||
|
||||
/// CMD_GET_CHANNEL (MyMesh.cpp:3234-3248).
|
||||
Uint8List _channelInfo(int index) {
|
||||
final c = channels[index];
|
||||
if (c == null || index >= seed.maxChannels) {
|
||||
return errFrame(fwErrNotFound);
|
||||
}
|
||||
return (BytesBuilder()
|
||||
..addByte(fwRespChannelInfo)
|
||||
..addByte(index)
|
||||
..add(_fixed(c.name, 32))
|
||||
..add(c.secret))
|
||||
.toBytes();
|
||||
}
|
||||
|
||||
/// CMD_GET_CUSTOM_VARS (MyMesh.cpp:3354-3367): `name:value` pairs, comma
|
||||
/// separated, no terminator.
|
||||
Uint8List customVarsFrame() {
|
||||
final text = customVars.entries.map((e) => '${e.key}:${e.value}').join(',');
|
||||
return _concat(fwRespCustomVars, utf8.encode(text));
|
||||
}
|
||||
|
||||
static Uint8List _concat(int code, List<int> body) =>
|
||||
Uint8List.fromList([code, ...body]);
|
||||
|
||||
static int _u32At(Uint8List b, int offset) =>
|
||||
ByteData.sublistView(b, offset, offset + 4).getUint32(0, Endian.little);
|
||||
|
||||
static Uint8List _u16(int v) =>
|
||||
Uint8List(2)..buffer.asByteData().setUint16(0, v, Endian.little);
|
||||
|
||||
static Uint8List _u32(int v) =>
|
||||
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
|
||||
|
||||
static Uint8List _i32(int v) =>
|
||||
Uint8List(4)..buffer.asByteData().setInt32(0, v, Endian.little);
|
||||
|
||||
/// A NUL-padded fixed-width string field (`StrHelper::strzcpy`), always
|
||||
/// leaving room for the terminator.
|
||||
static Uint8List _fixed(String s, int width) {
|
||||
final out = Uint8List(width);
|
||||
final bytes = utf8.encode(s);
|
||||
final n = bytes.length < width ? bytes.length : width - 1;
|
||||
out.setRange(0, n, bytes);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
// Companion protocol codes the fake radio speaks, copied from firmware
|
||||
// (OffbandMesh/meshcore-firmware `examples/companion_radio/MyMesh.cpp`
|
||||
// #defines, lines 47-209). Deliberately NOT imported from the client's
|
||||
// `meshcore_protocol.dart`: the fake is an independent copy of the firmware,
|
||||
// so a client constant that drifts from it shows up as a failing test.
|
||||
|
||||
const int fwCmdAppStart = 1;
|
||||
const int fwCmdSendTxtMsg = 2;
|
||||
const int fwCmdSendChannelTxtMsg = 3;
|
||||
const int fwCmdGetContacts = 4;
|
||||
const int fwCmdGetDeviceTime = 5;
|
||||
const int fwCmdSetDeviceTime = 6;
|
||||
const int fwCmdSendSelfAdvert = 7;
|
||||
const int fwCmdSetAdvertName = 8;
|
||||
const int fwCmdAddUpdateContact = 9;
|
||||
const int fwCmdSyncNextMessage = 10;
|
||||
const int fwCmdSetRadioParams = 11;
|
||||
const int fwCmdSetRadioTxPower = 12;
|
||||
const int fwCmdResetPath = 13;
|
||||
const int fwCmdSetAdvertLatLon = 14;
|
||||
const int fwCmdRemoveContact = 15;
|
||||
const int fwCmdGetBattAndStorage = 20;
|
||||
const int fwCmdDeviceQuery = 22;
|
||||
const int fwCmdSendLogin = 26;
|
||||
const int fwCmdGetChannel = 31;
|
||||
const int fwCmdSetChannel = 32;
|
||||
const int fwCmdSetOtherParams = 38;
|
||||
const int fwCmdGetCustomVars = 40;
|
||||
const int fwCmdSetCustomVar = 41;
|
||||
const int fwCmdGetStats = 56;
|
||||
const int fwCmdSetAutoAddConfig = 58;
|
||||
const int fwCmdGetAutoAddConfig = 59;
|
||||
const int fwCmdSetPathHashMode = 61;
|
||||
|
||||
const int fwRespOk = 0;
|
||||
const int fwRespErr = 1;
|
||||
const int fwRespContactsStart = 2;
|
||||
const int fwRespContact = 3;
|
||||
const int fwRespEndOfContacts = 4;
|
||||
const int fwRespSelfInfo = 5;
|
||||
const int fwRespSent = 6;
|
||||
const int fwRespCurrTime = 9;
|
||||
const int fwRespNoMoreMessages = 10;
|
||||
const int fwRespBattAndStorage = 12;
|
||||
const int fwRespDeviceInfo = 13;
|
||||
const int fwRespChannelInfo = 18;
|
||||
const int fwRespCustomVars = 21;
|
||||
const int fwRespAutoAddConfig = 25;
|
||||
|
||||
const int fwErrUnsupportedCmd = 1;
|
||||
const int fwErrNotFound = 2;
|
||||
const int fwErrTableFull = 3;
|
||||
const int fwErrBadState = 4;
|
||||
const int fwErrIllegalArg = 6;
|
||||
|
||||
/// `ADV_TYPE_*` (src/helpers/AdvertDataHelpers.h).
|
||||
const int fwAdvTypeChat = 1;
|
||||
const int fwAdvTypeRepeater = 2;
|
||||
const int fwAdvTypeRoom = 3;
|
||||
const int fwAdvTypeSensor = 4;
|
||||
|
||||
/// `PUB_KEY_SIZE` and `MAX_PATH_SIZE` (src/MeshCore.h:8,22).
|
||||
const int fwPubKeySize = 32;
|
||||
const int fwMaxPathSize = 64;
|
||||
@ -0,0 +1,57 @@
|
||||
/// Which firmware the fake radio plays. The difference is what DEVICE_INFO
|
||||
/// reports and whether Offband (0xC0-0xCF) commands are answered.
|
||||
///
|
||||
/// A4 (#769) builds these from the firmware's protocol manifests; until then
|
||||
/// [offband] and [stock] carry the values read from firmware source:
|
||||
/// - Offband: `examples/companion_radio/MyMesh.h:22` (FIRMWARE_VER_CODE 22) and
|
||||
/// the DEVICE_INFO tail at MyMesh.cpp:2437-2504.
|
||||
/// - Stock: upstream meshcore-dev/MeshCore `a366955c` (v1.17.1,
|
||||
/// FIRMWARE_VER_CODE 13), whose DEVICE_INFO ends after path_hash_mode.
|
||||
class FakeRadioProfile {
|
||||
const FakeRadioProfile({
|
||||
required this.name,
|
||||
required this.firmwareVerCode,
|
||||
required this.versionString,
|
||||
required this.offband,
|
||||
this.offbandCaps = 0,
|
||||
this.femLnaEnabled = false,
|
||||
this.offbandCaps2 = 0,
|
||||
this.ledEnabled = 0,
|
||||
this.displayMode = 0,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final int firmwareVerCode;
|
||||
|
||||
/// The 20-byte version field of DEVICE_INFO.
|
||||
final String versionString;
|
||||
|
||||
/// True for Offband firmware: the extended DEVICE_INFO tail is sent and
|
||||
/// Offband commands are answered. Stock rejects them as unknown commands.
|
||||
final bool offband;
|
||||
final int offbandCaps;
|
||||
final bool femLnaEnabled;
|
||||
final int offbandCaps2;
|
||||
final int ledEnabled;
|
||||
final int displayMode;
|
||||
|
||||
static const FakeRadioProfile offbandDefault = FakeRadioProfile(
|
||||
name: 'offband',
|
||||
firmwareVerCode: 22,
|
||||
versionString: '1.5.0-1.17.1',
|
||||
offband: true,
|
||||
// OFFBAND_CAP_BLOCK (0x02) | OFFBAND_CAP_CAPLOG (0x20), always set on the
|
||||
// companion (MyMesh.cpp:2448,2453; OffbandConfigProtocol.h:301,305); no
|
||||
// observer, no FEM LNA.
|
||||
offbandCaps: 0x02 | 0x20,
|
||||
// OFFBAND_CAP2_PKT_HASH, advertised unconditionally (MyMesh.cpp:2499).
|
||||
offbandCaps2: 0x08,
|
||||
);
|
||||
|
||||
static const FakeRadioProfile stockDefault = FakeRadioProfile(
|
||||
name: 'stock',
|
||||
firmwareVerCode: 13,
|
||||
versionString: 'v1.17.1',
|
||||
offband: false,
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,141 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'fake_radio_codes.dart';
|
||||
|
||||
/// A contact as the firmware stores it (`ContactInfo`), written back by
|
||||
/// `writeContactRespFrame` (MyMesh.cpp:276).
|
||||
class FakeContact {
|
||||
FakeContact({
|
||||
required this.publicKey,
|
||||
required this.name,
|
||||
this.type = fwAdvTypeChat,
|
||||
this.flags = 0,
|
||||
this.outPathLength = -1,
|
||||
Uint8List? outPath,
|
||||
this.lastAdvert = 1790000000,
|
||||
this.latE6 = 0,
|
||||
this.lonE6 = 0,
|
||||
this.lastmod = 1790000000,
|
||||
}) : outPath = outPath ?? Uint8List(0) {
|
||||
if (publicKey.length != fwPubKeySize) {
|
||||
throw ArgumentError('publicKey must be $fwPubKeySize bytes');
|
||||
}
|
||||
}
|
||||
|
||||
/// A contact whose key is [keyByte] repeated, for readable seeds.
|
||||
factory FakeContact.keyed(
|
||||
int keyByte,
|
||||
String name, {
|
||||
int type = fwAdvTypeChat,
|
||||
int lastmod = 1790000000,
|
||||
}) => FakeContact(
|
||||
publicKey: Uint8List.fromList(List<int>.filled(fwPubKeySize, keyByte)),
|
||||
name: name,
|
||||
type: type,
|
||||
lastmod: lastmod,
|
||||
);
|
||||
|
||||
final Uint8List publicKey;
|
||||
final String name;
|
||||
final int type;
|
||||
final int flags;
|
||||
|
||||
/// -1 for flood (sent as 0xFF), otherwise the path length byte.
|
||||
final int outPathLength;
|
||||
final Uint8List outPath;
|
||||
final int lastAdvert;
|
||||
final int latE6;
|
||||
final int lonE6;
|
||||
final int lastmod;
|
||||
}
|
||||
|
||||
/// A group channel slot (`ChannelDetails`), 128-bit secret only.
|
||||
class FakeChannel {
|
||||
FakeChannel({required this.index, required this.name, Uint8List? secret})
|
||||
: secret = secret ?? Uint8List(16) {
|
||||
if (this.secret.length != 16) {
|
||||
throw ArgumentError('secret must be 16 bytes (128-bit)');
|
||||
}
|
||||
}
|
||||
|
||||
final int index;
|
||||
final String name;
|
||||
final Uint8List secret;
|
||||
}
|
||||
|
||||
/// Everything the fake radio starts from. Same seed, same replies.
|
||||
class FakeRadioSeed {
|
||||
FakeRadioSeed({
|
||||
this.name = 'Fake Radio',
|
||||
Uint8List? publicKey,
|
||||
this.txPowerDbm = 20,
|
||||
this.maxTxPowerDbm = 22,
|
||||
this.latE6 = 0,
|
||||
this.lonE6 = 0,
|
||||
this.multiAcks = 0,
|
||||
this.advertLocPolicy = 0,
|
||||
this.telemetryModes = 0,
|
||||
this.manualAddContacts = 0,
|
||||
this.freqKhz = 910525,
|
||||
this.bwHz = 62500,
|
||||
this.sf = 7,
|
||||
this.cr = 5,
|
||||
this.maxContacts = 350,
|
||||
this.maxChannels = 8,
|
||||
this.blePin = 0,
|
||||
this.buildDate = '1 Oct 2026',
|
||||
this.manufacturer = 'Fake Radio Board',
|
||||
this.clientRepeat = false,
|
||||
this.pathHashMode = 0,
|
||||
this.batteryMillivolts = 4100,
|
||||
this.storageUsedKb = 12,
|
||||
this.storageTotalKb = 256,
|
||||
this.customVars = const {},
|
||||
this.autoAddConfig = 0,
|
||||
this.autoAddMaxHops = 0,
|
||||
this.deviceTime = 1790000000,
|
||||
List<FakeContact>? contacts,
|
||||
List<FakeChannel>? channels,
|
||||
}) : publicKey =
|
||||
publicKey ??
|
||||
Uint8List.fromList(
|
||||
List<int>.generate(fwPubKeySize, (i) => 0xA0 + i),
|
||||
),
|
||||
contacts = contacts ?? const [],
|
||||
channels = channels ?? const [];
|
||||
|
||||
final String name;
|
||||
final Uint8List publicKey;
|
||||
final int txPowerDbm;
|
||||
final int maxTxPowerDbm;
|
||||
final int latE6;
|
||||
final int lonE6;
|
||||
final int multiAcks;
|
||||
final int advertLocPolicy;
|
||||
final int telemetryModes;
|
||||
final int manualAddContacts;
|
||||
|
||||
/// `_prefs.freq * 1000` as SELF_INFO reports it (MyMesh.cpp:2574).
|
||||
final int freqKhz;
|
||||
|
||||
/// `_prefs.bw * 1000` as SELF_INFO reports it (MyMesh.cpp:2577).
|
||||
final int bwHz;
|
||||
final int sf;
|
||||
final int cr;
|
||||
final int maxContacts;
|
||||
final int maxChannels;
|
||||
final int blePin;
|
||||
final String buildDate;
|
||||
final String manufacturer;
|
||||
final bool clientRepeat;
|
||||
final int pathHashMode;
|
||||
final int batteryMillivolts;
|
||||
final int storageUsedKb;
|
||||
final int storageTotalKb;
|
||||
final Map<String, String> customVars;
|
||||
final int autoAddConfig;
|
||||
final int autoAddMaxHops;
|
||||
final int deviceTime;
|
||||
final List<FakeContact> contacts;
|
||||
final List<FakeChannel> channels;
|
||||
}
|
||||
Loading…
Reference in new issue