feat(#822): connector wiring for regions discovery + flood-scope (Epic #813 T3)

discoverRegions() correlates the 0x8C reply by the echoed tag (mirrors the 0xC6 pkt-hash pattern); setChannelSendScope/clearSendScope/setSendUnscoped and setDefaultFloodScope/clearDefaultFloodScope/getDefaultFloodScope wrap CMD 54/63/64 with RESP 28 handling. All gated fail-closed on supportsRegionScope. Two new dispatch cases (0x8C, RESP 28). Tested via the connector test seams.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
pull/841/head
diffwireauto 2 months ago committed by Strycher
parent 4b295f74fc
commit f3d8949624

@ -5721,6 +5721,148 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
// --- Region flood-scoping + regions discovery (Feature #812, Epic #813).
// Frames and parsers live in meshcore_protocol.dart; this is the connector
// wiring, modeled on the 0xC6 pkt-hash request/reply correlation above.
/// Pending regions-discovery requests, keyed by the tag the firmware echoes
/// (the anon request's timestamp, returned as RESP_CODE_SENT.tag and again in
/// the 0x8C reply). Mirrors [_pendingPktHashCompleters].
final Map<int, Completer<RegionsReply?>> _pendingRegionsCompleters = {};
Completer<DefaultFloodScope?>? _defaultFloodScopeCompleter;
int _regionsTagSeq = 0;
/// Unique 32-bit tag for a regions request. The firmware treats the anon
/// request's timestamp purely as an echo tag, so a monotonic value avoids
/// collisions between back-to-back discoveries.
int _nextRegionsTag() {
final base = DateTime.now().millisecondsSinceEpoch & 0xFFFFFF;
return (base << 8) | (_regionsTagSeq++ & 0xFF);
}
/// True iff the connected firmware supports region flood-scoping + discovery.
bool get supportsRegionScope => firmwareSupportsRegionScope(_firmwareVerCode);
@visibleForTesting
void setFirmwareVerCodeForTest(int? value) => _firmwareVerCode = value;
void _guardRegionScope() {
if (!supportsRegionScope) {
throw StateError('firmware does not support region scoping');
}
}
/// Discover the flood regions a reachable repeater advertises. Sends an anon
/// regions request to [repeaterPubKey] (32 bytes) and awaits the 0x8C reply,
/// correlated by the echoed tag. Returns null on timeout. Throws [StateError]
/// when the firmware does not support region scoping (fail-closed; callers
/// gate the UI on [supportsRegionScope]).
Future<RegionsReply?> discoverRegions({
required Uint8List repeaterPubKey,
Duration timeout = const Duration(seconds: 10),
}) async {
_guardRegionScope();
final tag = _nextRegionsTag();
final completer = Completer<RegionsReply?>();
_pendingRegionsCompleters[tag] = completer;
final timer = Timer(timeout, () {
if (!completer.isCompleted) completer.complete(null);
});
try {
await sendFrame(
buildAnonRegionsRequestFrame(repeaterPubKey, timestamp: tag),
);
return await completer.future;
} catch (e) {
appLogger.warn(
'regions discovery failed for tag $tag: $e',
tag: 'Region',
);
return null;
} finally {
timer.cancel();
_pendingRegionsCompleters.remove(tag);
}
}
/// Routes a 0x8C binary response to a waiting regions request, matched by tag.
/// 0x8C is a generic envelope, so a frame whose tag matches no pending regions
/// request is left alone (a timeout, or another handler, owns it).
void _handleRegionsReply(Uint8List frame) {
final parsed = parseRegionsReply(frame);
if (parsed == null) return;
final completer = _pendingRegionsCompleters[parsed.tag];
if (completer != null && !completer.isCompleted) {
completer.complete(parsed);
}
}
/// Override the companion's flood send-scope with [key] (16 bytes) for
/// subsequent sends. (CMD 54 sub-0)
Future<void> setChannelSendScope(Uint8List key) async {
_guardRegionScope();
await sendFrame(buildSetFloodScopeKeyFrame(key));
}
/// Clear the send-scope override, reverting to the node default. (CMD 54 sub-0)
Future<void> clearSendScope() async {
_guardRegionScope();
await sendFrame(buildClearFloodScopeFrame());
}
/// Force subsequent sends unscoped. (CMD 54 sub-1)
Future<void> setSendUnscoped() async {
_guardRegionScope();
await sendFrame(buildFloodScopeUnscopedFrame());
}
/// Set the node default flood scope to ([name],[key]). (CMD 63)
Future<void> setDefaultFloodScope(String name, Uint8List key) async {
_guardRegionScope();
await sendFrame(buildSetDefaultFloodScopeFrame(name, key));
}
/// Clear the node default flood scope. (CMD 63, bare)
Future<void> clearDefaultFloodScope() async {
_guardRegionScope();
await sendFrame(buildClearDefaultFloodScopeFrame());
}
/// Query the node default flood scope. Returns null on timeout, or a
/// [DefaultFloodScope] whose name is empty when the node has none. (CMD 64)
Future<DefaultFloodScope?> getDefaultFloodScope({
Duration timeout = const Duration(seconds: 5),
}) async {
_guardRegionScope();
final completer = Completer<DefaultFloodScope?>();
_defaultFloodScopeCompleter = completer;
final timer = Timer(timeout, () {
if (!completer.isCompleted) completer.complete(null);
});
try {
await sendFrame(buildGetDefaultFloodScopeFrame());
return await completer.future;
} catch (e) {
appLogger.warn('get default flood scope failed: $e', tag: 'Region');
return null;
} finally {
timer.cancel();
if (identical(_defaultFloodScopeCompleter, completer)) {
_defaultFloodScopeCompleter = null;
}
}
}
/// Routes a RESP_CODE_DEFAULT_FLOOD_SCOPE (28) reply to a waiting query.
void _handleDefaultFloodScopeReply(Uint8List frame) {
final parsed = parseDefaultFloodScopeReply(frame);
if (parsed == null) return;
final completer = _defaultFloodScopeCompleter;
if (completer != null && !completer.isCompleted) {
completer.complete(parsed);
}
}
/// Ask firmware for the on-air packet hash of a channel message we sent,
/// keyed by (ts, chan) (0xC6, #524). Returns null on timeout / error frame.
Future<OffbandPktHash?> _queryPacketHash(
@ -6084,6 +6226,12 @@ class MeshCoreConnector extends ChangeNotifier {
case cmdOffbandPktHash:
_handleOffbandPktHashFrame(frame);
break;
case pushCodeBinaryResponse:
_handleRegionsReply(frame);
break;
case respCodeDefaultFloodScope:
_handleDefaultFloodScopeReply(frame);
break;
case respCodeOffbandDeviceUi:
_handleDeviceUiReply(frame);
break;

@ -0,0 +1,171 @@
// Epic #813 T3: connector wiring for region discovery + flood-scope.
// Exercises the real dispatch/correlation via the test seams
// (setConnectedForTest / sendFrameOverrideForTest / handleFrameForTest).
// No key material here is real.
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
Uint8List _u32le(int v) {
final b = Uint8List(4);
ByteData.sublistView(b).setUint32(0, v, Endian.little);
return b;
}
Uint8List _padName(String name, int len) {
final b = Uint8List(len);
for (var i = 0; i < name.length && i < len - 1; i++) {
b[i] = name.codeUnitAt(i);
}
return b;
}
// Build the 0x8C reply a repeater would elicit for a given outgoing request,
// echoing the request's tag (bytes 33..37 of the CMD_SEND_ANON_REQ frame).
Uint8List _regionsReplyFor(
Uint8List req, {
required int clock,
required String csv,
}) {
final tag = ByteData.sublistView(req, 33, 37).getUint32(0, Endian.little);
final b = BytesBuilder()
..addByte(pushCodeBinaryResponse)
..addByte(0)
..add(_u32le(tag))
..add(_u32le(clock))
..add(Uint8List.fromList([...csv.codeUnits, 0]));
return b.toBytes();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late MeshCoreConnector connector;
final pub = Uint8List.fromList(List<int>.generate(32, (i) => i + 1));
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
connector = MeshCoreConnector();
connector.setConnectedForTest();
connector.setFirmwareVerCodeForTest(22);
});
group('discoverRegions', () {
test(
'sends the anon regions request and returns the parsed reply',
() async {
Uint8List? sent;
connector.sendFrameOverrideForTest = (data) {
sent = data;
connector.handleFrameForTest(
_regionsReplyFor(data, clock: 0x01020304, csv: 'oki,test,*'),
);
};
final reply = await connector.discoverRegions(repeaterPubKey: pub);
expect(sent, isNotNull);
expect(sent![0], cmdSendAnonReq);
expect(sent![37], anonReqTypeRegions);
expect(reply, isNotNull);
expect(reply!.regionNames, ['oki', 'test', '*']);
expect(reply.clock, 0x01020304);
},
);
test('returns null on timeout when no reply arrives', () async {
connector.sendFrameOverrideForTest = (_) {};
final reply = await connector.discoverRegions(
repeaterPubKey: pub,
timeout: const Duration(milliseconds: 50),
);
expect(reply, isNull);
});
test(
'a 0x8C with a non-matching tag never satisfies the request',
() async {
connector.sendFrameOverrideForTest = (_) {
final b = BytesBuilder()
..addByte(pushCodeBinaryResponse)
..addByte(0)
..add(_u32le(0xFFFFFFFF))
..add(_u32le(1))
..add(Uint8List.fromList([...'zzz'.codeUnits, 0]));
connector.handleFrameForTest(b.toBytes());
};
final reply = await connector.discoverRegions(
repeaterPubKey: pub,
timeout: const Duration(milliseconds: 80),
);
expect(reply, isNull);
},
);
test('refuses when firmware does not support region scope', () async {
connector.setFirmwareVerCodeForTest(7);
expect(connector.supportsRegionScope, isFalse);
await expectLater(
connector.discoverRegions(repeaterPubKey: pub),
throwsStateError,
);
});
});
group('send-scope setters', () {
test('setChannelSendScope emits [54][0][key16]', () async {
Uint8List? sent;
connector.sendFrameOverrideForTest = (d) => sent = d;
final key = Uint8List.fromList(List<int>.generate(16, (i) => 0xA0 + i));
await connector.setChannelSendScope(key);
expect(sent, isNotNull);
expect(sent![0], cmdSetFloodScopeKey);
expect(sent![1], floodScopeSubSetKey);
expect(sent!.sublist(2), key);
});
test('clearSendScope emits [54][0]', () async {
Uint8List? sent;
connector.sendFrameOverrideForTest = (d) => sent = d;
await connector.clearSendScope();
expect(sent, [cmdSetFloodScopeKey, floodScopeSubSetKey]);
});
test('setChannelSendScope refuses when unsupported', () async {
connector.setFirmwareVerCodeForTest(7);
await expectLater(
connector.setChannelSendScope(Uint8List(16)),
throwsStateError,
);
});
});
group('default flood scope', () {
test('getDefaultFloodScope returns the parsed RESP 28', () async {
connector.sendFrameOverrideForTest = (_) {
final b = BytesBuilder()
..addByte(respCodeDefaultFloodScope)
..add(_padName('oki', 31))
..add(Uint8List.fromList(List<int>.generate(16, (i) => i)));
connector.handleFrameForTest(b.toBytes());
};
final scope = await connector.getDefaultFloodScope();
expect(scope, isNotNull);
expect(scope!.name, 'oki');
expect(scope.isSet, isTrue);
});
test('setDefaultFloodScope emits [63][name31][key16]', () async {
Uint8List? sent;
connector.sendFrameOverrideForTest = (d) => sent = d;
await connector.setDefaultFloodScope('oki', Uint8List(16));
expect(sent, isNotNull);
expect(sent![0], cmdSetDefaultFloodScope);
expect(sent!.length, 1 + 31 + 16);
});
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.