Benjamin Wiechel 4 weeks ago committed by GitHub
commit 781b988afd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -3825,28 +3825,7 @@ class MeshCoreConnector extends ChangeNotifier {
},
);
_setState(MeshCoreConnectionState.connected);
_pendingInitialChannelSync = true;
_pendingInitialQueuedMessageSync = true;
_pendingInitialContactsSync = true;
await _requestDeviceInfo();
_startBatteryPolling();
if (_radioStatsPollRefCount > 0) _startRadioStatsPolling();
var gotSelfInfo = await _waitForSelfInfo(
timeout: const Duration(seconds: 3),
);
if (!gotSelfInfo) {
await refreshDeviceInfo();
gotSelfInfo = await _waitForSelfInfo(
timeout: const Duration(seconds: 3),
);
}
if (!gotSelfInfo) {
throw StateError('Timed out waiting for SELF_INFO during TCP connect');
}
await syncTime();
await _runConnectedHandshake();
} catch (error) {
_appDebugLogService?.error('TCP connection error: $error', tag: 'TCP');
final tcpConnectCancelledBeforeHandshake =
@ -3868,6 +3847,43 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
/// What TCP runs once frames flow: connected, device info, SELF_INFO (one
/// retry), then the clock. Shared with [connectInProcessForTest] so tests
/// drive the same sequence. (#768)
Future<void> _runConnectedHandshake() async {
_setState(MeshCoreConnectionState.connected);
_pendingInitialChannelSync = true;
_pendingInitialQueuedMessageSync = true;
_pendingInitialContactsSync = true;
await _requestDeviceInfo();
_startBatteryPolling();
if (_radioStatsPollRefCount > 0) _startRadioStatsPolling();
var gotSelfInfo = await _waitForSelfInfo(
timeout: const Duration(seconds: 3),
);
if (!gotSelfInfo) {
await refreshDeviceInfo();
gotSelfInfo = await _waitForSelfInfo(timeout: const Duration(seconds: 3));
}
if (!gotSelfInfo) {
throw StateError('Timed out waiting for SELF_INFO during TCP connect');
}
await syncTime();
}
/// Runs the TCP handshake with frames going to [sendFrameOverrideForTest]
/// and replies arriving through [handleFrameForTest]: the fake radio's
/// in-process path (#768). No socket is opened.
@visibleForTesting
Future<void> connectInProcessForTest() async {
_manualDisconnect = false;
_resetConnectionHandshakeState();
_activeTransport = MeshCoreTransportType.tcp;
await _runConnectedHandshake();
}
@visibleForTesting
static bool shouldIgnoreLateTcpConnectError({
required bool manualDisconnect,

@ -0,0 +1,159 @@
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_adapters.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';
// #767 (A1 of #755): the real connector against a radio, over both the real
// TCP path and the in-process seam (#768), under both firmware profiles
// (#769). Epic A verification (#771) adds the determinism run.
FakeRadioSeed _seed() => FakeRadioSeed(
channels: [FakeChannel(index: 0, name: 'Public')],
contacts: [
FakeContact.keyed(0x11, 'Alpha'),
FakeContact.keyed(0x22, 'Bravo'),
],
);
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 waiting for ${what ?? 'condition'}');
}
await Future<void>.delayed(const Duration(milliseconds: 10));
}
}
void main() {
late OffbandDatabase db;
late MeshCoreConnector connector;
Future<void> freshConnector() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
}
Future<void> dropConnector() async {
await connector.disconnect();
BlobStore.clearTestOverride();
await db.close();
}
setUp(freshConnector);
tearDown(dropConnector);
Future<void> expectSynced(FakeRadio radio) async {
expect(connector.isConnected, isTrue);
expect(connector.selfName, 'Fake Radio');
await _until(
() => connector.channels.any((c) => c.name == 'Public'),
what: 'channels',
);
await _until(
() => connector.contacts.map((c) => c.name).toSet().containsAll({
'Alpha',
'Bravo',
}),
what: 'contacts',
);
// The data came from the radio: the handshake really ran against it.
// Waited for, not sampled: over TCP a sent frame is only queued, so the
// closing SET_DEVICE_TIME can land just after the sync data does.
const handshake = [
fwCmdDeviceQuery,
fwCmdAppStart,
fwCmdSetDeviceTime,
fwCmdGetChannel,
fwCmdSyncNextMessage,
fwCmdGetContacts,
];
await _until(
() => radio.received.map((f) => f[0]).toSet().containsAll(handshake),
what: 'the handshake commands at the radio',
);
final codes = radio.received.map((f) => f[0]).toSet();
// What the client concluded about the firmware matches the profile.
if (radio.profile.offband) {
expect(connector.offbandCaps, radio.profile.offbandCaps);
expect(connector.offbandCaps2, radio.profile.offbandCaps2);
} else {
expect(connector.offbandCaps, isNull);
expect(connector.offbandCaps2, isNull);
expect(codes.where((c) => c >= fwOffbandConfig && c <= 0xCF), isEmpty);
}
}
final profiles = {
'Offband': FakeRadioProfile.offband,
'stock': FakeRadioProfile.stock,
};
for (final entry in profiles.entries) {
group(entry.key, () {
test(
'over TCP: connects, loads self info, channels and contacts',
() async {
final radio = FakeRadio(seed: _seed(), profile: entry.value());
final server = await FakeRadioTcpServer.start(radio);
addTearDown(server.close);
await connector.connectTcp(host: server.host, port: server.port);
await expectSynced(radio);
},
timeout: const Timeout(Duration(seconds: 30)),
);
test(
'in-process: connects, loads self info, channels and contacts',
() async {
final radio = FakeRadio(seed: _seed(), profile: entry.value());
final link = await FakeRadioInProcess.connect(connector, radio);
addTearDown(link.close);
await expectSynced(radio);
},
timeout: const Timeout(Duration(seconds: 30)),
);
});
}
test(
'same seed, same result over 20 connects (#771)',
() async {
String outcome() => [
connector.selfName,
connector.offbandCaps,
(connector.channels.map((c) => c.name).toList()..sort()).join(','),
(connector.contacts.map((c) => c.name).toList()..sort()).join(','),
].join('|');
String? first;
for (var run = 0; run < 20; run++) {
if (run > 0) {
await dropConnector();
await freshConnector();
}
final radio = FakeRadio(seed: _seed());
final link = await FakeRadioInProcess.connect(connector, radio);
await expectSynced(radio);
final now = outcome();
first ??= now;
expect(now, first, reason: 'run $run differed');
await link.close();
}
},
timeout: const Timeout(Duration(minutes: 2)),
);
}

@ -0,0 +1,211 @@
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');
// offband-v1.5.0-beta7 is built on MeshCore v1.17.0.
expect(_cstr(f, 60, 20), '1.5.0-1.17.0');
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.stock(),
).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.stock());
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,163 @@
import 'dart:convert';
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_manifest.dart';
import '../support/fake_radio/fake_radio_profile.dart';
Uint8List _cmd(List<int> b) => Uint8List.fromList(b);
void main() {
group('pinned manifests (#769)', () {
test('Offband: offband-v1.5.0-beta7 on MeshCore v1.17.0, code 22', () {
final m = FakeRadioManifest.pinnedOffband();
expect(m.isOffband, isTrue);
expect(m.ref, 'offband-v1.5.0-beta7');
expect(m.firmwareVerCode, 22);
expect(m.firmwareVersion, 'v1.17.0');
expect(m.deviceInfoVersion, '1.5.0-1.17.0');
expect(m.offbandCaps['OFFBAND_CAP_CAPLOG'], 0x20);
expect(m.offbandCommands['CMD_OFFBAND_PKT_HASH'], 0xC6);
});
test('stock: companion-v1.17.1, code 13, no Offband anything', () {
final m = FakeRadioManifest.pinnedStock();
expect(m.isOffband, isFalse);
expect(m.firmwareVerCode, 13);
expect(m.deviceInfoVersion, 'v1.17.1');
expect(m.offbandCaps, isEmpty);
expect(m.offbandCommands, isEmpty);
});
test('a wrong format or a newer format_version is refused', () {
expect(
() => FakeRadioManifest.parse(jsonEncode({'format': 'x'})),
throwsFormatException,
);
expect(
() => FakeRadioManifest.parse(
jsonEncode({
'format': 'offband-protocol-manifest',
'format_version': 2,
}),
),
throwsFormatException,
);
});
test('a capability the manifest lacks fails loudly, never reads as 0', () {
final m = FakeRadioManifest.pinnedOffband();
expect(() => m.capsOf(['OFFBAND_CAP_NOPE']), throwsStateError);
expect(
() => FakeRadioProfile.fromManifest(m, caps: ['OFFBAND_CAP_NOPE']),
throwsStateError,
);
});
});
group('profiles', () {
test('Offband defaults to the bits every companion sets', () {
final p = FakeRadioProfile.offband();
expect(p.offbandCaps, 0x02 | 0x20); // BLOCK | CAPLOG
expect(p.offbandCaps2, 0x08); // PKT_HASH
});
test('board bits can be named', () {
final p = FakeRadioProfile.fromManifest(
FakeRadioManifest.pinnedOffband(),
caps: ['OFFBAND_CAP_BLOCK', 'OFFBAND_CAP_FEM_LNA'],
caps2: ['OFFBAND_CAP2_NOTIFY_SCOPE'],
);
expect(p.offbandCaps, 0x06);
expect(p.offbandCaps2, 0x01);
});
test('stock rejects every Offband command as unsupported', () {
final radio = FakeRadio(profile: FakeRadioProfile.stock());
for (final code in [
fwOffbandConfig,
fwOffbandGps,
fwOffbandBlock,
fwOffbandPktHash,
]) {
expect(radio.handle(_cmd([code, fwBlockList])).single, [
fwRespErr,
fwErrUnsupportedCmd,
]);
}
});
});
group('Offband commands', () {
final key = List<int>.filled(fwPubKeySize, 0x42);
final other = List<int>.filled(fwPubKeySize, 0x43);
test('block: add dedups, remove swaps, list streams start/keys/end', () {
final radio = FakeRadio();
expect(radio.handle(_cmd([fwOffbandBlock, fwBlockAdd, ...key])).single, [
fwOffbandBlock,
fwBlockAdd,
1,
]);
// A repeat is still OK (BlockStore dedup).
expect(
radio.handle(_cmd([fwOffbandBlock, fwBlockAdd, ...key])).single[2],
1,
);
radio.handle(_cmd([fwOffbandBlock, fwBlockAdd, ...other]));
final list = radio.handle(_cmd([fwOffbandBlock, fwBlockList]));
expect(list.first, [fwOffbandBlock, fwBlockList, 0xFF, 2]);
expect(list[1].sublist(3), key);
expect(list.last, [fwOffbandBlock, fwBlockList, 0xFE]);
expect(
radio.handle(_cmd([fwOffbandBlock, fwBlockRemove, ...key])).single[2],
1,
);
expect(radio.blockedKeys.single, other);
expect(
radio.handle(_cmd([fwOffbandBlock, fwBlockRemove, ...key])).single[2],
0,
);
});
test('GPS status reply is "enabled=N " plus board text, NUL-ended', () {
final f = FakeRadio().handle(_cmd([fwOffbandGps])).single;
expect(f[0], fwOffbandGps);
expect(f.last, 0);
expect(utf8.decode(f.sublist(1, f.length - 1)), 'enabled=0 detected=0');
});
test('packet hash: unknown key, or malformed when not 7 bytes', () {
final radio = FakeRadio();
expect(
radio.handle(_cmd([fwOffbandPktHash, fwPktHashGet, 1, 2, 3, 4, 0])),
[
[fwOffbandPktHash, fwPktHashErr, fwPktHashErrUnknownKey],
],
);
expect(radio.handle(_cmd([fwOffbandPktHash, fwPktHashGet, 1])).single, [
fwOffbandPktHash,
fwPktHashErr,
fwPktHashErrMalformed,
]);
});
test('commands needing unadvertised bits are unsupported', () {
final radio = FakeRadio();
for (final code in [
fwOffbandConfig,
fwOffbandFemLna,
fwOffbandDeviceUi,
]) {
expect(radio.handle(_cmd([code, 0])).single, [
fwRespErr,
fwErrUnsupportedCmd,
]);
}
});
});
}

@ -0,0 +1,194 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import '../support/fake_radio/fake_radio.dart';
import '../support/fake_radio/fake_radio_manifest.dart';
import '../support/fake_radio/fake_radio_profile.dart';
// #770 (A5 of #755): the client's protocol constants must agree with the
// firmware's protocol manifest. Dart tests have no reflection, so both the
// client file and the fake's code table are read as source.
/// `const int name = value;`, across line breaks and trailing comments.
final _constInt = RegExp(
r'^const int (\w+)\s*=\s*(0x[0-9A-Fa-f]+|\d+)\s*;',
multiLine: true,
);
Map<String, int> _constants(String path) => {
for (final m in _constInt.allMatches(File(path).readAsStringSync()))
m.group(1)!: int.parse(m.group(2)!),
};
/// `cmdGetAutoAddConfig` and `CMD_GET_AUTOADD_CONFIG` both become
/// `cmdgetautoaddconfig`.
String _key(String name) => name.toLowerCase().replaceAll('_', '');
const _sections = [
'commands',
'responses',
'pushes',
'errors',
'offband_commands',
'offband_responses',
'offband_caps',
'offband_caps2',
];
/// Client names that spell a firmware name differently.
const _clientAliases = {'cmdGetCustomVar': 'CMD_GET_CUSTOM_VARS'};
/// Client constants no firmware release defines yet, with why. If the
/// manifest ever defines one under the same name, it is compared like any
/// other.
const _clientOnly = {
// #429 part A: the client re-polls channels on this push, but no firmware
// defines PUSH_CODE_CHANNELS_CHANGED (checked offband-v1.5.0-beta7).
'pushCodeChannelsChanged',
};
class _Report {
final matched = <String>[];
final mismatched = <String>[];
final unknown = <String>[];
}
/// Compares [client] constants with [manifest]; protocol-looking client names
/// the manifest lacks are reported unless allowed.
_Report _compare(Map<String, int> client, FakeRadioManifest manifest) {
final byKey = <String, MapEntry<String, int>>{};
for (final s in _sections) {
for (final e in manifest.section(s).entries) {
byKey[_key(e.key)] = e;
}
}
final report = _Report();
client.forEach((name, value) {
final fw = byKey[_key(_clientAliases[name] ?? name)];
if (fw == null) {
final protocolName = RegExp(
r'^(cmd|respCode|pushCode|offbandCap)',
).hasMatch(name);
if (protocolName && !_clientOnly.contains(name)) report.unknown.add(name);
return;
}
report.matched.add(name);
if (fw.value != value) {
report.mismatched.add('$name = $value, firmware ${fw.key} = ${fw.value}');
}
});
return report;
}
void main() {
final offband = FakeRadioManifest.pinnedOffband();
final client = _constants('lib/connector/meshcore_protocol.dart');
group('client protocol constants vs firmware manifest (#770)', () {
test('every shared code and capability bit has the firmware value', () {
final r = _compare(client, offband);
expect(
r.mismatched,
isEmpty,
reason: 'client disagrees with ${offband.ref}',
);
// Guard against a check that silently matches nothing.
expect(r.matched.length, greaterThanOrEqualTo(85));
});
test('no protocol constant is unknown to the firmware unless listed', () {
expect(_compare(client, offband).unknown, isEmpty);
});
test('no two names reduce to the same comparison key', () {
// `_key` drops case and underscores. If two names collapsed together,
// one of them would never be compared.
List<String> collisions(Iterable<String> names) {
final seen = <String, String>{};
return [
for (final n in names)
if (seen.putIfAbsent(_key(n), () => n) != n)
'$n and ${seen[_key(n)]}',
];
}
expect(collisions(client.keys), isEmpty);
expect(
collisions([for (final s in _sections) ...offband.section(s).keys]),
isEmpty,
);
expect(collisions(['CMD_FOO_BAR', 'cmdFooBar']), hasLength(1));
});
test('a deliberately wrong constant is caught', () {
final doctored = Map<String, int>.of(client)
..['offbandCapCaplog'] = 0x08
..['cmdOffbandPktHash'] = 0xC7;
expect(_compare(doctored, offband).mismatched, hasLength(2));
});
test('the stock manifest agrees on every stock code', () {
final stock = FakeRadioManifest.pinnedStock();
final r = _compare(client, stock);
expect(
r.mismatched,
isEmpty,
reason: 'client disagrees with ${stock.ref}',
);
});
});
group("fake radio's own codes vs firmware manifest", () {
test('every fake code has the firmware value', () {
final fake = _constants('test/support/fake_radio/fake_radio_codes.dart');
String? fwName(String n) {
if (n.startsWith('fwCmd')) return 'cmd${n.substring(5)}';
if (n.startsWith('fwResp')) return 'respCode${n.substring(6)}';
if (n.startsWith('fwErr')) return 'errCode${n.substring(5)}';
if (RegExp(r'^fwOffband[A-Z]').hasMatch(n)) {
return 'cmdOffband${n.substring(9)}';
}
return null; // sub-codes, sizes and advert types aren't in manifests
}
final renamed = <String, int>{
for (final e in fake.entries)
if (fwName(e.key) != null) fwName(e.key)!: e.value,
};
final r = _compare(renamed, offband);
expect(r.mismatched, isEmpty);
expect(r.matched.length, renamed.length);
});
});
group('reported version and capability gates', () {
int? caps(List<int> f) => f.length >= 83 ? f[82] : null;
int? caps2(List<int> f) => f.length >= 85 ? f[84] : null;
test('the client enables every Offband feature the fake advertises', () {
final info = FakeRadio().deviceInfoFrame();
final ver = info[1];
expect(ver, offband.firmwareVerCode);
expect(firmwareSupportsOffbandBlock(caps(info), ver), isTrue);
expect(firmwareSupportsOffbandCaplog(caps(info), ver), isTrue);
expect(firmwareSupportsPktHash(caps2(info), ver), isTrue);
expect(firmwareSupportsOffbandGps(caps(info)), isTrue);
});
test('the client enables none of them on stock', () {
final info = FakeRadio(
profile: FakeRadioProfile.stock(),
).deviceInfoFrame();
final ver = info[1];
expect(ver, 13);
expect(caps(info), isNull);
expect(caps2(info), isNull);
expect(firmwareSupportsOffbandBlock(caps(info), ver), isFalse);
expect(firmwareSupportsOffbandCaplog(caps(info), ver), isFalse);
expect(firmwareSupportsPktHash(caps2(info), ver), isFalse);
expect(firmwareSupportsOffbandGps(caps(info)), isFalse);
});
});
}

@ -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,390 @@
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, FakeRadioProfile? profile, FakeClock? clock})
: seed = seed ?? FakeRadioSeed(),
profile = profile ?? FakeRadioProfile.offband(),
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 = {};
/// The Offband user-block list (0xC2), as public keys.
final List<Uint8List> blockedKeys = [];
/// `MAX_BLOCKED_KEYS` (src/helpers/BlockStore.h:20).
static const int maxBlockedKeys = 32;
/// 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;
if (profile.offband && cmd[0] >= fwOffbandConfig && cmd[0] <= 0xCF) {
return _offband(cmd);
}
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)];
}
}
/// Offband commands. The fake answers the ones a default companion's client
/// sends: GPS status, the block list and the packet-hash query. Config,
/// FEM LNA, caplog and device-UI need capability bits the default profile
/// doesn't advertise, so a client honoring the bits never sends them; the
/// fake rejects them as unsupported rather than invent a reply.
List<Uint8List> _offband(Uint8List cmd) {
final len = cmd.length;
switch (cmd[0]) {
case fwOffbandGps:
// MyMesh.cpp:1975-1983: "enabled=N " + board status, NUL-terminated.
final enabled = customVars['gps'] == '1' ? 1 : 0;
return [
Uint8List.fromList([
fwOffbandGps,
...utf8.encode('enabled=$enabled ${profile.gpsStatusText}'),
0,
]),
];
case fwOffbandBlock when len >= 2:
return _block(cmd);
case fwOffbandPktHash when len >= 2 && cmd[1] == fwPktHashGet:
// MyMesh.cpp:2114-2133: exactly 7 bytes; the fake keeps no send ring,
// so every well-formed query is an unknown key.
return [
Uint8List.fromList([
fwOffbandPktHash,
fwPktHashErr,
len != 7 ? fwPktHashErrMalformed : fwPktHashErrUnknownKey,
]),
];
default:
return [errFrame(fwErrUnsupportedCmd)];
}
}
/// 0xC2 (MyMesh.cpp:2074-2100) and its list drain (`blockListDrain`).
List<Uint8List> _block(Uint8List cmd) {
final sub = cmd[1];
Uint8List ack(bool ok) =>
Uint8List.fromList([fwOffbandBlock, sub, ok ? 1 : 0]);
bool same(Uint8List a, List<int> b) {
for (var i = 0; i < fwPubKeySize; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
if ((sub == fwBlockAdd || sub == fwBlockRemove) &&
cmd.length >= 2 + fwPubKeySize) {
// BlockStore (src/helpers/BlockStore.h:48-70): add dedups (a repeat is
// true), fails only when full; remove swaps the last entry into the gap.
final key = cmd.sublist(2, 2 + fwPubKeySize);
final at = blockedKeys.indexWhere((k) => same(k, key));
if (sub == fwBlockAdd) {
if (at >= 0) return [ack(true)];
if (blockedKeys.length >= maxBlockedKeys) return [ack(false)];
blockedKeys.add(Uint8List.fromList(key));
return [ack(true)];
}
if (at < 0) return [ack(false)];
final last = blockedKeys.removeLast();
if (at < blockedKeys.length) blockedKeys[at] = last;
return [ack(true)];
}
if (sub == fwBlockClear) {
blockedKeys.clear();
return [ack(true)];
}
if (sub == fwBlockList) {
return [
Uint8List.fromList([fwOffbandBlock, sub, 0xFF, blockedKeys.length]),
for (var i = 0; i < blockedKeys.length; i++)
Uint8List.fromList([fwOffbandBlock, sub, i, ...blockedKeys[i]]),
Uint8List.fromList([fwOffbandBlock, sub, 0xFE]),
];
}
return [errFrame(fwErrIllegalArg)];
}
/// `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,127 @@
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));
}
});
}
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();
for (final s in List<Socket>.of(_sockets)) {
s.destroy();
}
await _server.close();
}
}
/// The fake radio plugged straight into the connector's test seam: no
/// sockets, so widget tests stay fast (#768). Replies arrive on a later
/// microtask, like a transport delivers them.
class FakeRadioInProcess {
FakeRadioInProcess._(this.connector, this.radio) {
connector.sendFrameOverrideForTest = (frame) {
for (final reply in radio.handle(frame)) {
scheduleMicrotask(() => connector.handleFrameForTest(reply));
}
};
_pushSub = radio.pushes.listen(
(frame) => scheduleMicrotask(() => connector.handleFrameForTest(frame)),
);
}
/// Attaches [radio] and runs the connector's real handshake against it.
static Future<FakeRadioInProcess> connect(
MeshCoreConnector connector,
FakeRadio radio,
) async {
final link = FakeRadioInProcess._(connector, radio);
await connector.connectInProcessForTest();
return link;
}
final MeshCoreConnector connector;
final FakeRadio radio;
late final StreamSubscription<Uint8List> _pushSub;
Future<void> close() async {
await _pushSub.cancel();
connector.sendFrameOverrideForTest = null;
}
}

@ -0,0 +1,86 @@
// 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;
// Offband commands (MyMesh.cpp:110,117; OffbandConfigProtocol.h). Request and
// response share the code.
const int fwOffbandConfig = 0xC0;
const int fwOffbandGps = 0xC1;
const int fwOffbandBlock = 0xC2;
const int fwOffbandFemLna = 0xC3;
const int fwOffbandCaplog = 0xC4;
const int fwOffbandDeviceUi = 0xC5;
const int fwOffbandPktHash = 0xC6;
/// 0xC2 sub-commands (OffbandConfigProtocol.h:312-315).
const int fwBlockAdd = 0x01;
const int fwBlockRemove = 0x02;
const int fwBlockList = 0x03;
const int fwBlockClear = 0x04;
/// 0xC6 sub-commands and errors (OffbandConfigProtocol.h:158-161).
const int fwPktHashGet = 0x01;
const int fwPktHashErr = 0x7F;
const int fwPktHashErrUnknownKey = 1;
const int fwPktHashErrMalformed = 2;
/// `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,92 @@
import 'dart:convert';
import 'dart:io';
/// A firmware protocol manifest (#769): the codes, capability bits and version
/// a firmware build defines, generated from its source. Today's copies are
/// pinned under `manifests/` by `tool/fake_radio/gen_protocol_manifest.py`;
/// OffbandMesh/meshcore-firmware#1318 will publish them from firmware CI.
class FakeRadioManifest {
FakeRadioManifest._(this.json);
factory FakeRadioManifest.parse(String text) {
final json = jsonDecode(text) as Map<String, dynamic>;
if (json['format'] != 'offband-protocol-manifest') {
throw FormatException('not a protocol manifest: ${json['format']}');
}
if (json['format_version'] != 1) {
throw FormatException(
'unsupported manifest format_version ${json['format_version']}',
);
}
return FakeRadioManifest._(json);
}
factory FakeRadioManifest.load(String path) =>
FakeRadioManifest.parse(File(path).readAsStringSync());
static const String _dir = 'test/support/fake_radio/manifests';
/// The Offband release the fake's Offband profile is pinned to.
static FakeRadioManifest pinnedOffband() =>
FakeRadioManifest.load('$_dir/offband-v1.5.0-beta7.json');
/// The upstream MeshCore release the fake's stock profile is pinned to.
static FakeRadioManifest pinnedStock() =>
FakeRadioManifest.load('$_dir/stock-companion-v1.17.1.json');
final Map<String, dynamic> json;
Map<String, dynamic> get _firmware =>
json['firmware'] as Map<String, dynamic>;
String get flavor => _firmware['flavor'] as String;
bool get isOffband => flavor == 'offband';
String get ref => _firmware['ref'] as String;
String get commit => _firmware['commit'] as String;
/// `FIRMWARE_VERSION`, the MeshCore base, e.g. `v1.17.0`.
String get firmwareVersion => _firmware['firmware_version'] as String;
int get firmwareVerCode => _firmware['firmware_ver_code'] as int;
Map<String, int> section(String name) =>
(json[name] as Map<String, dynamic>).map((k, v) => MapEntry(k, v as int));
Map<String, int> get commands => section('commands');
Map<String, int> get responses => section('responses');
Map<String, int> get pushes => section('pushes');
Map<String, int> get errors => section('errors');
Map<String, int> get offbandCommands => section('offband_commands');
Map<String, int> get offbandResponses => section('offband_responses');
Map<String, int> get offbandCaps => section('offband_caps');
Map<String, int> get offbandCaps2 => section('offband_caps2');
/// OR of the named capability bits; throws if the manifest lacks one, so a
/// renamed or removed bit fails loudly instead of reading as 0.
int capsOf(Iterable<String> names, {bool second = false}) {
final table = second ? offbandCaps2 : offbandCaps;
var bits = 0;
for (final n in names) {
final v = table[n];
if (v == null) throw StateError('$ref defines no $n');
bits |= v;
}
return bits;
}
/// The 20-byte DEVICE_INFO version field this build reports.
///
/// Offband: `offbandClientVersion()` (MyMesh.cpp:1761), the Offband core,
/// a '-', then the MeshCore core (e.g. `1.5.0-1.17.0`); each core is cut at
/// its first '-', with the 'v' stripped from the MeshCore one. Stock:
/// `FIRMWARE_VERSION` as is.
String get deviceInfoVersion {
if (!isOffband) return firmwareVersion;
var mc = firmwareVersion;
if (mc.startsWith('v') || mc.startsWith('V')) mc = mc.substring(1);
mc = mc.split('-').first;
final at = ref.indexOf('offband-v');
if (at < 0) return mc;
final ob = ref.substring(at + 'offband-v'.length).split('-').first;
return ob.isEmpty ? mc : '$ob-$mc';
}
}

@ -0,0 +1,72 @@
import 'fake_radio_manifest.dart';
/// Which firmware the fake radio plays (#769). The difference is what
/// DEVICE_INFO reports and whether Offband commands are answered. Built from a
/// firmware protocol manifest, so codes, bits and versions follow the firmware.
class FakeRadioProfile {
const FakeRadioProfile({
required this.name,
required this.firmwareVerCode,
required this.versionString,
required this.offband,
this.manifest,
this.offbandCaps = 0,
this.femLnaEnabled = false,
this.offbandCaps2 = 0,
this.ledEnabled = 0,
this.displayMode = 0,
this.gpsStatusText = 'detected=0',
});
/// A companion build of [manifest]'s firmware.
///
/// Offband capability bits default to the ones every companion sets
/// unconditionally: OFFBAND_CAP_BLOCK and OFFBAND_CAP_CAPLOG
/// (MyMesh.cpp:2448,2453) and OFFBAND_CAP2_PKT_HASH (MyMesh.cpp:2499).
/// Board-dependent bits (observer, FEM LNA, buzzer, button, indicators) are
/// off unless named.
factory FakeRadioProfile.fromManifest(
FakeRadioManifest manifest, {
Iterable<String> caps = const ['OFFBAND_CAP_BLOCK', 'OFFBAND_CAP_CAPLOG'],
Iterable<String> caps2 = const ['OFFBAND_CAP2_PKT_HASH'],
}) {
final offband = manifest.isOffband;
return FakeRadioProfile(
name: manifest.flavor,
firmwareVerCode: manifest.firmwareVerCode,
versionString: manifest.deviceInfoVersion,
offband: offband,
manifest: manifest,
offbandCaps: offband ? manifest.capsOf(caps) : 0,
offbandCaps2: offband ? manifest.capsOf(caps2, second: true) : 0,
);
}
/// The pinned Offband release (`offband-v1.5.0-beta7`).
factory FakeRadioProfile.offband() =>
FakeRadioProfile.fromManifest(FakeRadioManifest.pinnedOffband());
/// The pinned upstream MeshCore release (`companion-v1.17.1`).
factory FakeRadioProfile.stock() =>
FakeRadioProfile.fromManifest(FakeRadioManifest.pinnedStock());
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 FakeRadioManifest? manifest;
final int offbandCaps;
final bool femLnaEnabled;
final int offbandCaps2;
final int ledEnabled;
final int displayMode;
/// What `sensors.getGpsStatusText` adds after `enabled=N ` in the 0xC1
/// reply. Board-specific in firmware; a seed value here.
final String gpsStatusText;
}

@ -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;
}

@ -0,0 +1,159 @@
{
"commands": {
"CMD_ADD_UPDATE_CONTACT": 9,
"CMD_APP_START": 1,
"CMD_DEVICE_QUERY": 22,
"CMD_EXPORT_CONTACT": 17,
"CMD_EXPORT_PRIVATE_KEY": 23,
"CMD_FACTORY_RESET": 51,
"CMD_GET_ADVERT_PATH": 42,
"CMD_GET_ALLOWED_REPEAT_FREQ": 60,
"CMD_GET_AUTOADD_CONFIG": 59,
"CMD_GET_BATT_AND_STORAGE": 20,
"CMD_GET_CHANNEL": 31,
"CMD_GET_CONTACTS": 4,
"CMD_GET_CONTACT_BY_KEY": 30,
"CMD_GET_CUSTOM_VARS": 40,
"CMD_GET_DEFAULT_FLOOD_SCOPE": 64,
"CMD_GET_DEVICE_TIME": 5,
"CMD_GET_STATS": 56,
"CMD_GET_TUNING_PARAMS": 43,
"CMD_HAS_CONNECTION": 28,
"CMD_IMPORT_CONTACT": 18,
"CMD_IMPORT_PRIVATE_KEY": 24,
"CMD_LOGOUT": 29,
"CMD_REBOOT": 19,
"CMD_REMOVE_CONTACT": 15,
"CMD_RESET_PATH": 13,
"CMD_SEND_ANON_REQ": 57,
"CMD_SEND_BINARY_REQ": 50,
"CMD_SEND_CHANNEL_DATA": 62,
"CMD_SEND_CHANNEL_TXT_MSG": 3,
"CMD_SEND_CONTROL_DATA": 55,
"CMD_SEND_LOGIN": 26,
"CMD_SEND_PATH_DISCOVERY_REQ": 52,
"CMD_SEND_RAW_DATA": 25,
"CMD_SEND_RAW_PACKET": 65,
"CMD_SEND_SELF_ADVERT": 7,
"CMD_SEND_STATUS_REQ": 27,
"CMD_SEND_TELEMETRY_REQ": 39,
"CMD_SEND_TRACE_PATH": 36,
"CMD_SEND_TXT_MSG": 2,
"CMD_SET_ADVERT_LATLON": 14,
"CMD_SET_ADVERT_NAME": 8,
"CMD_SET_AUTOADD_CONFIG": 58,
"CMD_SET_CHANNEL": 32,
"CMD_SET_CUSTOM_VAR": 41,
"CMD_SET_DEFAULT_FLOOD_SCOPE": 63,
"CMD_SET_DEVICE_PIN": 37,
"CMD_SET_DEVICE_TIME": 6,
"CMD_SET_FLOOD_SCOPE_KEY": 54,
"CMD_SET_OTHER_PARAMS": 38,
"CMD_SET_PATH_HASH_MODE": 61,
"CMD_SET_RADIO_PARAMS": 11,
"CMD_SET_RADIO_TX_POWER": 12,
"CMD_SET_TUNING_PARAMS": 21,
"CMD_SHARE_CONTACT": 16,
"CMD_SIGN_DATA": 34,
"CMD_SIGN_FINISH": 35,
"CMD_SIGN_START": 33,
"CMD_SYNC_NEXT_MESSAGE": 10
},
"errors": {
"ERR_CODE_BAD_STATE": 4,
"ERR_CODE_FILE_IO_ERROR": 5,
"ERR_CODE_ILLEGAL_ARG": 6,
"ERR_CODE_NOT_FOUND": 2,
"ERR_CODE_TABLE_FULL": 3,
"ERR_CODE_UNSUPPORTED_CMD": 1
},
"firmware": {
"commit": "53951759bceb4a6b4a90aac55d9ae9829712abf5",
"firmware_ver_code": 22,
"firmware_version": "v1.17.0",
"flavor": "offband",
"ref": "offband-v1.5.0-beta7"
},
"format": "offband-protocol-manifest",
"format_version": 1,
"generated_by": "meshcore-client tool/fake_radio/gen_protocol_manifest.py",
"offband_caps": {
"OFFBAND_CAP_BLOCK": 2,
"OFFBAND_CAP_CAPLOG": 32,
"OFFBAND_CAP_FEM_LNA": 4,
"OFFBAND_CAP_WIFI_OBSERVER": 1
},
"offband_caps2": {
"OFFBAND_CAP2_BUTTON_MATRIX": 2,
"OFFBAND_CAP2_INDICATORS": 4,
"OFFBAND_CAP2_NOTIFY_SCOPE": 1,
"OFFBAND_CAP2_PKT_HASH": 8
},
"offband_commands": {
"CMD_OFFBAND_BLOCK": 194,
"CMD_OFFBAND_CAPLOG": 196,
"CMD_OFFBAND_CONFIG": 192,
"CMD_OFFBAND_DEVICE_UI": 197,
"CMD_OFFBAND_FEM_LNA": 195,
"CMD_OFFBAND_GPS": 193,
"CMD_OFFBAND_PKT_HASH": 198
},
"offband_responses": {
"RESP_CODE_OFFBAND_BLOCK": 194,
"RESP_CODE_OFFBAND_CAPLOG": 196,
"RESP_CODE_OFFBAND_CONFIG": 192,
"RESP_CODE_OFFBAND_DEVICE_UI": 197,
"RESP_CODE_OFFBAND_FEM_LNA": 195,
"RESP_CODE_OFFBAND_GPS": 193,
"RESP_CODE_OFFBAND_PKT_HASH": 198
},
"pushes": {
"PUSH_CODE_ADVERT": 128,
"PUSH_CODE_BINARY_RESPONSE": 140,
"PUSH_CODE_CONTACTS_FULL": 144,
"PUSH_CODE_CONTACT_DELETED": 143,
"PUSH_CODE_CONTROL_DATA": 142,
"PUSH_CODE_LOGIN_FAIL": 134,
"PUSH_CODE_LOGIN_SUCCESS": 133,
"PUSH_CODE_LOG_RX_DATA": 136,
"PUSH_CODE_MSG_WAITING": 131,
"PUSH_CODE_NEW_ADVERT": 138,
"PUSH_CODE_PATH_DISCOVERY_RESPONSE": 141,
"PUSH_CODE_PATH_UPDATED": 129,
"PUSH_CODE_RAW_DATA": 132,
"PUSH_CODE_SEND_CONFIRMED": 130,
"PUSH_CODE_STATUS_RESPONSE": 135,
"PUSH_CODE_TELEMETRY_RESPONSE": 139,
"PUSH_CODE_TRACE_DATA": 137
},
"responses": {
"RESP_CODE_ADVERT_PATH": 22,
"RESP_CODE_AUTOADD_CONFIG": 25,
"RESP_CODE_BATT_AND_STORAGE": 12,
"RESP_CODE_CHANNEL_DATA_RECV": 27,
"RESP_CODE_CHANNEL_INFO": 18,
"RESP_CODE_CHANNEL_MSG_RECV": 8,
"RESP_CODE_CHANNEL_MSG_RECV_V3": 17,
"RESP_CODE_CONTACT": 3,
"RESP_CODE_CONTACTS_START": 2,
"RESP_CODE_CONTACT_MSG_RECV": 7,
"RESP_CODE_CONTACT_MSG_RECV_V3": 16,
"RESP_CODE_CURR_TIME": 9,
"RESP_CODE_CUSTOM_VARS": 21,
"RESP_CODE_DEFAULT_FLOOD_SCOPE": 28,
"RESP_CODE_DEVICE_INFO": 13,
"RESP_CODE_DISABLED": 15,
"RESP_CODE_END_OF_CONTACTS": 4,
"RESP_CODE_ERR": 1,
"RESP_CODE_EXPORT_CONTACT": 11,
"RESP_CODE_NO_MORE_MESSAGES": 10,
"RESP_CODE_OK": 0,
"RESP_CODE_PRIVATE_KEY": 14,
"RESP_CODE_SELF_INFO": 5,
"RESP_CODE_SENT": 6,
"RESP_CODE_SIGNATURE": 20,
"RESP_CODE_SIGN_START": 19,
"RESP_CODE_STATS": 24,
"RESP_CODE_TUNING_PARAMS": 23
}
}

@ -0,0 +1,133 @@
{
"commands": {
"CMD_ADD_UPDATE_CONTACT": 9,
"CMD_APP_START": 1,
"CMD_DEVICE_QUERY": 22,
"CMD_EXPORT_CONTACT": 17,
"CMD_EXPORT_PRIVATE_KEY": 23,
"CMD_FACTORY_RESET": 51,
"CMD_GET_ADVERT_PATH": 42,
"CMD_GET_ALLOWED_REPEAT_FREQ": 60,
"CMD_GET_AUTOADD_CONFIG": 59,
"CMD_GET_BATT_AND_STORAGE": 20,
"CMD_GET_CHANNEL": 31,
"CMD_GET_CONTACTS": 4,
"CMD_GET_CONTACT_BY_KEY": 30,
"CMD_GET_CUSTOM_VARS": 40,
"CMD_GET_DEFAULT_FLOOD_SCOPE": 64,
"CMD_GET_DEVICE_TIME": 5,
"CMD_GET_STATS": 56,
"CMD_GET_TUNING_PARAMS": 43,
"CMD_HAS_CONNECTION": 28,
"CMD_IMPORT_CONTACT": 18,
"CMD_IMPORT_PRIVATE_KEY": 24,
"CMD_LOGOUT": 29,
"CMD_REBOOT": 19,
"CMD_REMOVE_CONTACT": 15,
"CMD_RESET_PATH": 13,
"CMD_SEND_ANON_REQ": 57,
"CMD_SEND_BINARY_REQ": 50,
"CMD_SEND_CHANNEL_DATA": 62,
"CMD_SEND_CHANNEL_TXT_MSG": 3,
"CMD_SEND_CONTROL_DATA": 55,
"CMD_SEND_LOGIN": 26,
"CMD_SEND_PATH_DISCOVERY_REQ": 52,
"CMD_SEND_RAW_DATA": 25,
"CMD_SEND_RAW_PACKET": 65,
"CMD_SEND_SELF_ADVERT": 7,
"CMD_SEND_STATUS_REQ": 27,
"CMD_SEND_TELEMETRY_REQ": 39,
"CMD_SEND_TRACE_PATH": 36,
"CMD_SEND_TXT_MSG": 2,
"CMD_SET_ADVERT_LATLON": 14,
"CMD_SET_ADVERT_NAME": 8,
"CMD_SET_AUTOADD_CONFIG": 58,
"CMD_SET_CHANNEL": 32,
"CMD_SET_CUSTOM_VAR": 41,
"CMD_SET_DEFAULT_FLOOD_SCOPE": 63,
"CMD_SET_DEVICE_PIN": 37,
"CMD_SET_DEVICE_TIME": 6,
"CMD_SET_FLOOD_SCOPE_KEY": 54,
"CMD_SET_OTHER_PARAMS": 38,
"CMD_SET_PATH_HASH_MODE": 61,
"CMD_SET_RADIO_PARAMS": 11,
"CMD_SET_RADIO_TX_POWER": 12,
"CMD_SET_TUNING_PARAMS": 21,
"CMD_SHARE_CONTACT": 16,
"CMD_SIGN_DATA": 34,
"CMD_SIGN_FINISH": 35,
"CMD_SIGN_START": 33,
"CMD_SYNC_NEXT_MESSAGE": 10
},
"errors": {
"ERR_CODE_BAD_STATE": 4,
"ERR_CODE_FILE_IO_ERROR": 5,
"ERR_CODE_ILLEGAL_ARG": 6,
"ERR_CODE_NOT_FOUND": 2,
"ERR_CODE_TABLE_FULL": 3,
"ERR_CODE_UNSUPPORTED_CMD": 1
},
"firmware": {
"commit": "d92964352441e53b93e8667b802e04f6e072b39e",
"firmware_ver_code": 13,
"firmware_version": "v1.17.1",
"flavor": "stock",
"ref": "companion-v1.17.1"
},
"format": "offband-protocol-manifest",
"format_version": 1,
"generated_by": "meshcore-client tool/fake_radio/gen_protocol_manifest.py",
"offband_caps": {},
"offband_caps2": {},
"offband_commands": {},
"offband_responses": {},
"pushes": {
"PUSH_CODE_ADVERT": 128,
"PUSH_CODE_BINARY_RESPONSE": 140,
"PUSH_CODE_CONTACTS_FULL": 144,
"PUSH_CODE_CONTACT_DELETED": 143,
"PUSH_CODE_CONTROL_DATA": 142,
"PUSH_CODE_LOGIN_FAIL": 134,
"PUSH_CODE_LOGIN_SUCCESS": 133,
"PUSH_CODE_LOG_RX_DATA": 136,
"PUSH_CODE_MSG_WAITING": 131,
"PUSH_CODE_NEW_ADVERT": 138,
"PUSH_CODE_PATH_DISCOVERY_RESPONSE": 141,
"PUSH_CODE_PATH_UPDATED": 129,
"PUSH_CODE_RAW_DATA": 132,
"PUSH_CODE_SEND_CONFIRMED": 130,
"PUSH_CODE_STATUS_RESPONSE": 135,
"PUSH_CODE_TELEMETRY_RESPONSE": 139,
"PUSH_CODE_TRACE_DATA": 137
},
"responses": {
"RESP_CODE_ADVERT_PATH": 22,
"RESP_CODE_AUTOADD_CONFIG": 25,
"RESP_CODE_BATT_AND_STORAGE": 12,
"RESP_CODE_CHANNEL_DATA_RECV": 27,
"RESP_CODE_CHANNEL_INFO": 18,
"RESP_CODE_CHANNEL_MSG_RECV": 8,
"RESP_CODE_CHANNEL_MSG_RECV_V3": 17,
"RESP_CODE_CONTACT": 3,
"RESP_CODE_CONTACTS_START": 2,
"RESP_CODE_CONTACT_MSG_RECV": 7,
"RESP_CODE_CONTACT_MSG_RECV_V3": 16,
"RESP_CODE_CURR_TIME": 9,
"RESP_CODE_CUSTOM_VARS": 21,
"RESP_CODE_DEFAULT_FLOOD_SCOPE": 28,
"RESP_CODE_DEVICE_INFO": 13,
"RESP_CODE_DISABLED": 15,
"RESP_CODE_END_OF_CONTACTS": 4,
"RESP_CODE_ERR": 1,
"RESP_CODE_EXPORT_CONTACT": 11,
"RESP_CODE_NO_MORE_MESSAGES": 10,
"RESP_CODE_OK": 0,
"RESP_CODE_PRIVATE_KEY": 14,
"RESP_CODE_SELF_INFO": 5,
"RESP_CODE_SENT": 6,
"RESP_CODE_SIGNATURE": 20,
"RESP_CODE_SIGN_START": 19,
"RESP_CODE_STATS": 24,
"RESP_CODE_TUNING_PARAMS": 23
}
}

@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Generate a protocol manifest from MeshCore companion firmware source.
Bootstrap for the fake radio (#769, Feature #755) until
OffbandMesh/meshcore-firmware#1318 publishes manifests from firmware CI.
Reads the source at a git ref (no checkout) and prints JSON to stdout.
python tool/fake_radio/gen_protocol_manifest.py \
--repo C:/Dev/meshcore-firmware --ref offband-v1.5.0-beta7 \
--flavor offband > test/support/fake_radio/manifests/offband-v1.5.0-beta7.json
Stock: --ref companion-v1.17.1 --flavor stock (upstream meshcore-dev/MeshCore
tag, fetched into the clone).
"""
import argparse
import json
import re
import subprocess
import sys
COMPANION = "examples/companion_radio"
DEFINE = re.compile(r"^#define\s+([A-Z0-9_]+)\s+(0x[0-9A-Fa-f]+|\d+)\b", re.M)
CONSTEXPR = re.compile(
r"^constexpr\s+uint8_t\s+([A-Z0-9_]+)\s*=\s*(0x[0-9A-Fa-f]+|\d+)\s*;", re.M
)
VER_CODE = re.compile(r"^#define\s+FIRMWARE_VER_CODE\s+(\d+)", re.M)
VERSION = re.compile(r'^#define\s+FIRMWARE_VERSION\s+"([^"]+)"', re.M)
def show(repo, ref, path):
out = subprocess.run(
["git", "-C", repo, "show", f"{ref}:{path}"],
capture_output=True,
text=True,
encoding="utf-8",
)
if out.returncode != 0:
return None
return out.stdout
PROTOCOL = re.compile(r"(CMD_|RESP_CODE_|PUSH_CODE_|ERR_CODE_|OFFBAND_)")
def conditional_definitions(text):
"""Protocol definitions inside #if/#ifdef/#ifndef. Reading source with
regexes can't tell which branch a build takes, so the manifest would be
wrong for some build; refuse instead of guessing."""
depth, found = 0, []
for n, line in enumerate(text.splitlines(), 1):
s = line.strip()
if re.match(r"#\s*if", s):
depth += 1
elif re.match(r"#\s*endif", s):
depth -= 1
elif depth > 0:
m = DEFINE.match(s) or CONSTEXPR.match(s)
if m and PROTOCOL.match(m.group(1)):
found.append(f"line {n}: {m.group(1)}")
return found
def pick(pairs, prefix):
out = {}
for name, value in pairs:
if not name.startswith(prefix):
continue
if name in out and out[name] != int(value, 0):
sys.exit(f"{name} is defined twice with different values")
out[name] = int(value, 0)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--repo", required=True)
ap.add_argument("--ref", required=True)
ap.add_argument("--flavor", choices=["offband", "stock"], required=True)
args = ap.parse_args()
header = show(args.repo, args.ref, f"{COMPANION}/MyMesh.h")
source = show(args.repo, args.ref, f"{COMPANION}/MyMesh.cpp")
if header is None or source is None:
sys.exit(f"can't read {COMPANION} at {args.ref}")
commit = subprocess.run(
["git", "-C", args.repo, "rev-parse", f"{args.ref}^{{commit}}"],
capture_output=True,
text=True,
).stdout.strip()
defines = DEFINE.findall(source)
pairs = list(defines)
offband = show(args.repo, args.ref, f"{COMPANION}/OffbandConfigProtocol.h")
if args.flavor == "offband":
if offband is None:
sys.exit("offband flavor but OffbandConfigProtocol.h is missing")
pairs += CONSTEXPR.findall(offband) + DEFINE.findall(offband)
for name, text in [("MyMesh.cpp", source)] + (
[("OffbandConfigProtocol.h", offband)] if args.flavor == "offband" else []
):
found = conditional_definitions(text)
if found:
sys.exit(f"{name} defines protocol codes inside #if: {', '.join(found)}")
commands = pick(pairs, "CMD_")
responses = pick(pairs, "RESP_CODE_")
manifest = {
"format": "offband-protocol-manifest",
"format_version": 1,
"generated_by": "meshcore-client tool/fake_radio/gen_protocol_manifest.py",
"firmware": {
"flavor": args.flavor,
"ref": args.ref,
"commit": commit,
"firmware_version": VERSION.search(header).group(1),
"firmware_ver_code": int(VER_CODE.search(header).group(1)),
},
"commands": {k: v for k, v in commands.items() if "OFFBAND" not in k},
"responses": {k: v for k, v in responses.items() if "OFFBAND" not in k},
"pushes": pick(pairs, "PUSH_CODE_"),
"errors": pick(pairs, "ERR_CODE_"),
"offband_commands": {k: v for k, v in commands.items() if "OFFBAND" in k},
"offband_responses": {k: v for k, v in responses.items() if "OFFBAND" in k},
"offband_caps": {
k: v for k, v in pick(pairs, "OFFBAND_CAP_").items()
},
"offband_caps2": pick(pairs, "OFFBAND_CAP2_"),
}
print(json.dumps(manifest, indent=2, sort_keys=True))
if __name__ == "__main__":
main()
Loading…
Cancel
Save

Powered by TurnKey Linux.