feat(#768): fake radio in-process and TCP adapters

FakeRadioTcpServer serves the fake on a loopback port with the
companion serial framing (0x3c app->radio, 0x3e radio->app), written
independently of the client codec. FakeRadioInProcess plugs the fake
into sendFrameOverrideForTest/handleFrameForTest with no socket.

lib change, test seam only: connectTcp's post-transport handshake moves
into _runConnectedHandshake (same statements, same order, same
try/catch), and connectInProcessForTest runs it for the in-process
path. A1 (#767) now passes on both adapters and asserts the handshake
commands reached the fake. analyze clean; connector + TCP tests green
(271).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feat/756-fake-radio-core
diffwireauto 2 months ago
parent d770cef887
commit a0df51274e

@ -2366,28 +2366,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 =
@ -2409,6 +2388,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,

@ -1,5 +1,3 @@
import 'dart:io';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
@ -8,13 +6,35 @@ import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
// #767 (A1 of #755): the real connector, over its real TCP path, against a
// radio. Today the only radio a test can stand up never answers, so the
// handshake times out and nothing past "connected" can be exercised.
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_seed.dart';
// #767 (A1 of #755): the real connector against a radio, over both the real
// TCP path and the in-process seam (#768).
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;
late ServerSocket radio;
setUp(() async {
SharedPreferences.setMockInitialValues({});
@ -23,29 +43,62 @@ void main() {
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
connector = MeshCoreConnector();
radio = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
radio.listen((socket) => socket.listen((_) {}));
});
tearDown(() async {
await connector.disconnect();
await radio.close();
BlobStore.clearTestOverride();
await db.close();
});
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.
final codes = radio.received.map((f) => f[0]).toSet();
expect(
codes,
containsAll([
fwCmdDeviceQuery,
fwCmdAppStart,
fwCmdSetDeviceTime,
fwCmdGetChannel,
fwCmdSyncNextMessage,
fwCmdGetContacts,
]),
);
}
test(
'over TCP: connects, loads self info, channels and contacts',
() async {
final radio = FakeRadio(seed: _seed());
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(
'connects, loads self info, channels and contacts',
'in-process: connects, loads self info, channels and contacts',
() async {
await connector.connectTcp(
host: InternetAddress.loopbackIPv4.address,
port: radio.port,
);
expect(connector.isConnected, isTrue);
expect(connector.selfName, 'Fake Radio');
expect(connector.channels.map((c) => c.name), contains('Public'));
expect(connector.contacts.map((c) => c.name), contains('Alpha'));
final radio = FakeRadio(seed: _seed());
final link = await FakeRadioInProcess.connect(connector, radio);
addTearDown(link.close);
await expectSynced(radio);
},
timeout: const Timeout(Duration(seconds: 30)),
);

@ -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;
}
}
Loading…
Cancel
Save

Powered by TurnKey Linux.