Add review mode with a simulated radio

Store reviewers have no MeshCore radio, so they could not reach any
screen past Connect or test the Android Auto messaging notifications.

- Long-press the "MeshCore Open" title on the Connect screen to enter
  review mode on any platform
- A simulated radio speaks the companion protocol as a fourth transport,
  so sync, messages, ACKs, notifications and notification replies run
  through the normal code paths
- Seeded contacts, channels and history; a new incoming message every
  45 s, auto-replies a few seconds after sending, and a banner with
  "Send test message" and "Exit"
- Review data uses its own fixed key scope and is cleared on entry, exit
  and at startup; the review scope never adopts legacy unscoped keys,
  and channel mutes changed during review are restored
- Code lives in lib/review_mode/ with tests in test/review_mode/
This commit is contained in:
zjs81 committed 2026-10-07 20:38:59 -07:00
1 parent 9334d556fe
commit 11c94040e3
68 files changed
+3314 -197

No files matched your search

+289
View File
@@ -0,0 +1,289 @@
import 'dart:typed_data';
import '../connector/meshcore_protocol.dart';
/// Pure builders for the radio-to-app companion frames the connector parses.
class ReviewFrames {
ReviewFrames._();
/// ERR_CODE_NOT_FOUND in the companion firmware.
static const int errNotFound = 2;
static const int errUnsupported = 1;
static Uint8List ok() => Uint8List.fromList([respCodeOk]);
static Uint8List err([int code = errUnsupported]) =>
Uint8List.fromList([respCodeErr, code]);
static Uint8List selfInfo({
required Uint8List publicKey,
required String name,
required int latitudeE6,
required int longitudeE6,
required int frequencyHz,
required int bandwidthHz,
required int spreadingFactor,
required int codingRate,
required int txPowerDbm,
required int maxTxPowerDbm,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeSelfInfo);
writer.writeByte(advTypeChat);
writer.writeByte(txPowerDbm);
writer.writeByte(maxTxPowerDbm);
writer.writeBytes(publicKey);
writer.writeInt32LE(latitudeE6);
writer.writeInt32LE(longitudeE6);
writer.writeByte(0); // multi_acks
writer.writeByte(0); // advert_loc_policy
writer.writeByte(0); // telemetry modes
writer.writeByte(
1,
); // manual_add_contacts: 1 = auto-add controlled by flags
writer.writeUInt32LE(frequencyHz);
writer.writeUInt32LE(bandwidthHz);
writer.writeByte(spreadingFactor);
writer.writeByte(codingRate);
writer.writeString(name);
writer.writeByte(0);
return writer.toBytes();
}
static Uint8List deviceInfo({
required int firmwareVerCode,
required int maxContacts,
required int maxChannels,
String manufacturer = 'MeshCore Open Review',
String version = 'review',
bool clientRepeat = false,
int pathHashMode = 0,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeDeviceInfo);
writer.writeByte(firmwareVerCode);
writer.writeByte(maxContacts ~/ 2);
writer.writeByte(maxChannels);
writer.writeUInt32LE(0); // ble pin, bytes 4..7
writer.writeCString('', 12); // build date, bytes 8..19
writer.writeCString(manufacturer, 40); // bytes 20..59
writer.writeCString(version, 20); // bytes 60..79
writer.writeByte(clientRepeat ? 1 : 0); // byte 80
writer.writeByte(pathHashMode); // byte 81
return writer.toBytes();
}
static Uint8List contactsStart(int count) {
final writer = BufferWriter();
writer.writeByte(respCodeContactsStart);
writer.writeUInt32LE(count);
return writer.toBytes();
}
static Uint8List contact({
required Uint8List publicKey,
required int type,
required Uint8List path,
required String name,
required int lastAdvertSecs,
required int latitudeE6,
required int longitudeE6,
required int lastModSecs,
int flags = 0,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeContact);
writer.writeBytes(publicKey);
writer.writeByte(type);
writer.writeByte(flags);
writer.writeByte(path.length); // one-byte hashes: hop count == byte count
writer.writeBytesPadded(path, maxPathSize);
writer.writeCString(name, maxNameSize);
writer.writeUInt32LE(lastAdvertSecs);
writer.writeInt32LE(latitudeE6);
writer.writeInt32LE(longitudeE6);
writer.writeUInt32LE(lastModSecs);
return writer.toBytes();
}
static Uint8List endOfContacts(int mostRecentLastModSecs) {
final writer = BufferWriter();
writer.writeByte(respCodeEndOfContacts);
writer.writeUInt32LE(mostRecentLastModSecs);
return writer.toBytes();
}
static Uint8List channelInfo({
required int index,
required String name,
required Uint8List psk,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeChannelInfo);
writer.writeByte(index);
writer.writeCString(name, 32);
writer.writeBytesPadded(psk, 16);
return writer.toBytes();
}
static Uint8List contactMessage({
required Uint8List senderPublicKey,
required String text,
required int timestampSecs,
int pathLen = 0xFF,
int snrQuarterDb = 24,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeContactMsgRecvV3);
writer.writeByte(snrQuarterDb & 0xFF);
writer.writeByte(0);
writer.writeByte(0);
writer.writeBytes(Uint8List.fromList(senderPublicKey.sublist(0, 6)));
writer.writeByte(pathLen);
writer.writeByte(txtTypePlain);
writer.writeUInt32LE(timestampSecs);
writer.writeString(text);
writer.writeByte(0);
return writer.toBytes();
}
/// The on-air text is `sender: message`.
static Uint8List channelMessage({
required int channelIndex,
required String sender,
required String message,
required int timestampSecs,
Uint8List? path,
int snrQuarterDb = 24,
}) {
final hasPath = path != null && path.isNotEmpty;
final writer = BufferWriter();
writer.writeByte(respCodeChannelMsgRecvV3);
writer.writeByte(snrQuarterDb & 0xFF);
writer.writeByte(hasPath ? 1 : 0);
writer.writeByte(0);
writer.writeByte(channelIndex);
writer.writeByte(hasPath ? path.length : 0xFF);
if (hasPath) writer.writeBytes(path);
writer.writeByte(txtTypePlain);
writer.writeUInt32LE(timestampSecs);
writer.writeString('$sender: $message');
writer.writeByte(0);
return writer.toBytes();
}
static Uint8List sent({
required bool flood,
required int ackHash,
required int timeoutMs,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeSent);
writer.writeByte(flood ? 1 : 0);
writer.writeUInt32LE(ackHash);
writer.writeUInt32LE(timeoutMs);
return writer.toBytes();
}
static Uint8List sendConfirmed({
required int ackHash,
required int tripTimeMs,
}) {
final writer = BufferWriter();
writer.writeByte(pushCodeSendConfirmed);
writer.writeUInt32LE(ackHash);
writer.writeUInt32LE(tripTimeMs);
return writer.toBytes();
}
/// [code][permissions][pub_key_prefix x6][server_time x4][acl][fw_level].
static Uint8List loginSuccess({
required Uint8List publicKey,
required int serverTimeSecs,
int permissions = 0,
}) {
final writer = BufferWriter();
writer.writeByte(pushCodeLoginSuccess);
writer.writeByte(permissions);
writer.writeBytes(Uint8List.fromList(publicKey.sublist(0, 6)));
writer.writeUInt32LE(serverTimeSecs);
writer.writeByte(0); // ACL permissions
writer.writeByte(0); // firmware version level
return writer.toBytes();
}
/// [code][reserved][pub_key_prefix x6].
static Uint8List loginFail({required Uint8List publicKey}) {
final writer = BufferWriter();
writer.writeByte(pushCodeLoginFail);
writer.writeByte(0);
writer.writeBytes(Uint8List.fromList(publicKey.sublist(0, 6)));
return writer.toBytes();
}
static Uint8List msgWaiting() => Uint8List.fromList([pushCodeMsgWaiting]);
static Uint8List noMoreMessages() =>
Uint8List.fromList([respCodeNoMoreMessages]);
static Uint8List battAndStorage({
required int millivolts,
required int usedKb,
required int totalKb,
}) {
final writer = BufferWriter();
writer.writeByte(respCodeBattAndStorage);
writer.writeUInt16LE(millivolts);
writer.writeUInt32LE(usedKb);
writer.writeUInt32LE(totalKb);
return writer.toBytes();
}
static Uint8List currTime(int epochSecs) {
final writer = BufferWriter();
writer.writeByte(respCodeCurrTime);
writer.writeUInt32LE(epochSecs);
return writer.toBytes();
}
/// [vars] is the comma separated "key:value" list the connector parses.
static Uint8List customVars(String vars) {
final writer = BufferWriter();
writer.writeByte(respCodeCustomVars);
writer.writeString(vars);
writer.writeByte(0);
return writer.toBytes();
}
static Uint8List autoAddConfig({required int flags, int maxHops = 0}) =>
Uint8List.fromList([respCodeAutoAddConfig, flags, maxHops]);
static Uint8List allowedRepeatFreq(List<RepeatFreqRange> ranges) {
final writer = BufferWriter();
writer.writeByte(respCodeAllowedRepeatFreq);
for (final range in ranges) {
writer.writeUInt32LE(range.lowKHz);
writer.writeUInt32LE(range.highKHz);
}
return writer.toBytes();
}
/// STATS_TYPE_RADIO: [24][1][noise i16][rssi i8][snr*4 i8][tx u32][rx u32].
static Uint8List radioStats({
required int noiseFloorDbm,
required int lastRssiDbm,
required int lastSnrQuarterDb,
required int txAirSecs,
required int rxAirSecs,
}) {
final data = ByteData(14);
data.setUint8(0, respCodeStats);
data.setUint8(1, statsTypeRadio);
data.setInt16(2, noiseFloorDbm, Endian.little);
data.setInt8(4, lastRssiDbm);
data.setInt8(5, lastSnrQuarterDb);
data.setUint32(6, txAirSecs, Endian.little);
data.setUint32(10, rxAirSecs, Endian.little);
return data.buffer.asUint8List();
}
}
+68
View File
@@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../screens/channels_screen.dart';
export 'review_mode_banner.dart';
export 'review_mode_entry.dart';
/// Asks for confirmation, connects to the simulated radio and opens the app.
Future<void> enterReviewMode(BuildContext context) async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
final connector = context.read<MeshCoreConnector>();
final l10n = context.l10n;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(dialogContext.l10n.reviewMode_dialogTitle),
content: Text(dialogContext.l10n.reviewMode_dialogBody),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text(dialogContext.l10n.reviewMode_cancel),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: Text(dialogContext.l10n.reviewMode_confirm),
),
],
),
);
if (confirmed != true || !navigator.mounted) return;
// Progress dialog on the root navigator while connecting.
showDialog<void>(
context: navigator.context,
barrierDismissible: false,
builder: (_) => const PopScope(
canPop: false,
child: Center(child: CircularProgressIndicator()),
),
);
Object? error;
try {
await connector.connectReview();
} catch (e) {
error = e;
}
if (!navigator.mounted) return;
navigator.pop(); // progress dialog
if (error != null) {
messenger.showSnackBar(
SnackBar(content: Text(l10n.reviewMode_connectFailed(error.toString()))),
);
return;
}
// The connect may have been ignored (another connection was in progress)
// or cancelled by a disconnect while it was running.
if (!connector.isReviewMode || !connector.isConnected) return;
navigator.push(MaterialPageRoute(builder: (_) => const ChannelsScreen()));
}
+72
View File
@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
/// Strip shown on top of main screens while the simulated radio is active.
class ReviewModeBanner extends StatelessWidget {
const ReviewModeBanner({super.key});
@override
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
if (!connector.isReviewMode) return const SizedBox.shrink();
final l10n = context.l10n;
const textStyle = TextStyle(
color: MeshPalette.ink,
fontSize: 16,
fontWeight: FontWeight.w700,
);
final buttonStyle = TextButton.styleFrom(
foregroundColor: MeshPalette.warn,
textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
minimumSize: const Size(48, 48),
);
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: const BoxDecoration(
color: MeshPalette.bg3,
border: Border(bottom: BorderSide(color: MeshPalette.warnLine)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.science, color: MeshPalette.warn, size: 24),
const SizedBox(width: 8),
Expanded(child: Text(l10n.reviewMode_banner, style: textStyle)),
],
),
Wrap(
spacing: 8,
children: [
TextButton(
style: buttonStyle,
onPressed: () {
connector.sendReviewTestMessage();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l10n.reviewMode_testSent)),
);
},
child: Text(l10n.reviewMode_sendTest),
),
TextButton(
style: buttonStyle,
// The screens hosting the banner return to the Connect screen
// themselves once disconnected.
onPressed: () => connector.disconnect(manual: true),
child: Text(l10n.reviewMode_exit),
),
],
),
],
),
);
}
}
+19
View File
@@ -0,0 +1,19 @@
import 'package:flutter/material.dart';
import 'review_mode.dart';
/// Hidden entry point: long-pressing [child] offers to enter review mode.
class ReviewModeLongPress extends StatelessWidget {
final Widget child;
const ReviewModeLongPress({super.key, required this.child});
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onLongPress: () => enterReviewMode(context),
child: child,
);
}
}
+55
View File
@@ -0,0 +1,55 @@
import '../services/app_settings_service.dart';
import '../storage/legacy_key_migration.dart';
import '../storage/prefs_manager.dart';
import 'review_radio.dart';
/// Muted channel names as they were when review mode started. Persisted so an
/// interrupted session (crash, app killed) is still undone on the next launch.
const _savedMutedChannelsKey = 'review_mode_saved_muted_channels';
/// Deletes every persisted per-radio preference written while review mode was
/// active. All per-radio stores (contacts, channels, messages, unread counts,
/// channel/contact settings, regions, discovery cache, path history, ...) embed
/// the first 10 hex characters of the radio's public key in their key, so the
/// simulated radio's fixed prefix identifies exactly its data and nothing else.
Future<void> clearReviewModeData() async {
final prefs = PrefsManager.instance;
final prefix = ReviewRadio.storagePrefix;
final keys = prefs.getKeys().where((key) => key.contains(prefix)).toList();
for (final key in keys) {
await prefs.remove(key);
}
}
/// Starts a review session from a clean slate.
///
/// The simulated radio's scope never adopts legacy unscoped keys, so real
/// radio data cannot be pulled into it. Channel mutes are app-wide and keyed
/// by channel name (muting the simulated "Public" would mute the real one),
/// so the current mutes are saved for [endReviewModeSession] to put back.
Future<void> beginReviewModeSession(AppSettingsService? settings) async {
scopesWithoutLegacyMigration.add(ReviewRadio.storagePrefix);
await clearReviewModeData();
final prefs = PrefsManager.instance;
// An earlier interrupted session's record holds the real pre-review state.
if (settings != null && !prefs.containsKey(_savedMutedChannelsKey)) {
await prefs.setStringList(
_savedMutedChannelsKey,
settings.settings.mutedChannels.toList(),
);
}
}
/// Deletes the review session's data and restores the channel mutes saved by
/// [beginReviewModeSession]. Also called at startup to finish a session that
/// was interrupted; it does nothing when no session was left behind.
Future<void> endReviewModeSession(AppSettingsService? settings) async {
await clearReviewModeData();
final prefs = PrefsManager.instance;
final savedMutes = prefs.getStringList(_savedMutedChannelsKey);
if (savedMutes == null || settings == null) return;
await settings.updateSettings(
settings.settings.copyWith(mutedChannels: savedMutes.toSet()),
);
await prefs.remove(_savedMutedChannelsKey);
}
+624
View File
@@ -0,0 +1,624 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../connector/meshcore_protocol.dart';
import '../connector/pending_command_replies.dart';
import '../services/message_retry_service.dart';
import 'review_frames.dart';
import 'review_script.dart';
/// A simulated MeshCore radio that speaks the companion binary protocol.
class ReviewRadio {
ReviewRadio({
this.scheduledMessageInterval = const Duration(seconds: 45),
this.ackDelay = const Duration(milliseconds: 1500),
this.replyDelay = const Duration(seconds: 4),
}) {
_seedState();
}
/// 64 lowercase hex chars, fixed and obviously fake.
static const String selfPublicKeyHex =
'ee5e04b332b386b6cce8355ccf27fffd3a98b7a7a5b9b3a550c039c6ebae38e4';
/// First 10 hex chars of [selfPublicKeyHex], the per-radio storage scope.
static String get storagePrefix => selfPublicKeyHex.substring(0, 10);
final Duration scheduledMessageInterval;
final Duration ackDelay;
final Duration replyDelay;
final StreamController<Uint8List> _controller =
StreamController<Uint8List>.broadcast();
final List<Uint8List> _outbox = [];
final Set<Timer> _timers = {};
final List<Uint8List> _messageQueue = [];
final List<_Contact> _contacts = [];
final Map<int, _Channel> _channels = {};
final Uint8List _selfKey = hexToPubKey(selfPublicKeyHex);
Timer? _flushTimer;
Timer? _scheduledTimer;
bool _disposed = false;
bool _nextScheduledIsDirect = true;
int _directPoolIndex = 0;
int _channelPoolIndex = 0;
int _directReplyIndex = 0;
int _channelReplyIndex = 0;
String _name = ReviewScript.selfName;
int _latitudeE6 = ReviewScript.selfLatitudeE6;
int _longitudeE6 = ReviewScript.selfLongitudeE6;
int _frequencyHz = ReviewScript.frequencyHz;
int _bandwidthHz = ReviewScript.bandwidthHz;
int _spreadingFactor = ReviewScript.spreadingFactor;
int _codingRate = ReviewScript.codingRate;
int _txPowerDbm = ReviewScript.txPowerDbm;
int _autoAddFlags =
autoAddChatFlag | autoAddRepeaterFlag | autoAddRoomServerFlag;
int _timeOffsetSecs = 0;
/// Frames radio to app. Each event is one complete companion frame.
Stream<Uint8List> get frames => _controller.stream;
int get _nowSecs =>
DateTime.now().millisecondsSinceEpoch ~/ 1000 + _timeOffsetSecs;
void _seedState() {
final now = _nowSecs;
for (final c in ReviewScript.contacts) {
_contacts.add(
_Contact(
publicKey: hexToPubKey(c.publicKeyHex),
type: c.type,
path: c.pathHex.isEmpty ? Uint8List(0) : hex2Uint8List(c.pathHex),
name: c.name,
lastAdvertSecs: now - c.lastAdvertAgoSecs,
latitudeE6: (c.latitude * 1e6).round(),
longitudeE6: (c.longitude * 1e6).round(),
lastModSecs: now,
),
);
}
for (final c in ReviewScript.channels) {
_channels[c.index] = _Channel(c.name, hex2Uint8List(c.pskHex));
}
final history = <_SeedEntry>[
for (final m in ReviewScript.seedDirectMessages)
_SeedEntry(
m.agoSecs,
ReviewFrames.contactMessage(
senderPublicKey: _contacts[m.contactIndex].publicKey,
text: m.text,
timestampSecs: now - m.agoSecs,
pathLen: ReviewScript.contacts[m.contactIndex].hopCount,
),
),
for (final m in ReviewScript.seedChannelMessages)
_SeedEntry(
m.agoSecs,
ReviewFrames.channelMessage(
channelIndex: m.channelIndex,
sender: m.sender,
message: m.text,
timestampSecs: now - m.agoSecs,
path: _pathForSender(m.sender),
),
),
]..sort((a, b) => b.agoSecs.compareTo(a.agoSecs));
for (final entry in history) {
_messageQueue.add(entry.frame);
}
}
Uint8List? _pathForSender(String sender) {
for (final c in _contacts) {
if (c.name == sender && c.path.isNotEmpty) return c.path;
}
return null;
}
/// Starts the scheduled incoming-message timer.
void start() {
if (_disposed || _scheduledTimer != null) return;
_scheduledTimer = Timer.periodic(scheduledMessageInterval, (_) {
_enqueueScheduledMessage();
});
}
/// Immediately queues one incoming message and pushes MSG_WAITING.
void sendTestMessage() {
if (_disposed) return;
_enqueueScheduledMessage();
}
void _enqueueScheduledMessage() {
if (_disposed) return;
final now = _nowSecs;
if (_nextScheduledIsDirect) {
final pool = ReviewScript.incomingDirectPool;
final line = pool[_directPoolIndex++ % pool.length];
_messageQueue.add(
ReviewFrames.contactMessage(
senderPublicKey: _contacts[line.contactIndex].publicKey,
text: line.text,
timestampSecs: now,
pathLen: ReviewScript.contacts[line.contactIndex].hopCount,
),
);
} else {
final pool = ReviewScript.incomingChannelPool;
final line = pool[_channelPoolIndex++ % pool.length];
_messageQueue.add(
ReviewFrames.channelMessage(
channelIndex: line.channelIndex,
sender: line.sender,
message: line.text,
timestampSecs: now,
path: _pathForSender(line.sender),
),
);
}
_nextScheduledIsDirect = !_nextScheduledIsDirect;
_emit([ReviewFrames.msgWaiting()]);
}
/// Frame app to radio. Responses are emitted asynchronously.
void handle(Uint8List frame) {
if (_disposed || frame.isEmpty) return;
final code = frame[0];
switch (code) {
case cmdDeviceQuery:
_emit([
ReviewFrames.deviceInfo(
firmwareVerCode: ReviewScript.firmwareVerCode,
maxContacts: ReviewScript.maxContacts,
maxChannels: ReviewScript.maxChannels,
),
]);
break;
case cmdAppStart:
_emit([_selfInfoFrame()]);
break;
case cmdGetContacts:
_handleGetContacts(frame);
break;
case cmdGetContactByKey:
_handleGetContactByKey(frame);
break;
case cmdGetChannel:
_handleGetChannel(frame);
break;
case cmdSetChannel:
_handleSetChannel(frame);
break;
case cmdSyncNextMessage:
_emit([
_messageQueue.isEmpty
? ReviewFrames.noMoreMessages()
: _messageQueue.removeAt(0),
]);
break;
case cmdSendTxtMsg:
_handleSendText(frame);
break;
case cmdSendChannelTxtMsg:
_handleSendChannelText(frame);
break;
case cmdGetBattAndStorage:
_emit([
ReviewFrames.battAndStorage(
millivolts: 3980,
usedKb: 412,
totalKb: 1792,
),
]);
break;
case cmdGetDeviceTime:
_emit([ReviewFrames.currTime(_nowSecs)]);
break;
case cmdSetDeviceTime:
if (frame.length >= 5) {
_timeOffsetSecs =
readUint32LE(frame, 1) -
DateTime.now().millisecondsSinceEpoch ~/ 1000;
}
_emit([ReviewFrames.ok()]);
break;
case cmdGetCustomVar:
_emit([ReviewFrames.customVars('gps:0')]);
break;
case cmdGetAutoAddConfig:
_emit([ReviewFrames.autoAddConfig(flags: _autoAddFlags)]);
break;
case cmdSetAutoAddConfig:
if (frame.length >= 2) _autoAddFlags = frame[1];
_emit([ReviewFrames.ok()]);
break;
case cmdGetAllowedRepeatFreq:
_emit([
ReviewFrames.allowedRepeatFreq(const [
(lowKHz: 433000, highKHz: 433000),
(lowKHz: 869000, highKHz: 869000),
(lowKHz: 918000, highKHz: 918000),
]),
]);
break;
case cmdGetStats:
_emit([
frame.length >= 2 && frame[1] == statsTypeRadio
? ReviewFrames.radioStats(
noiseFloorDbm: -112,
lastRssiDbm: -78,
lastSnrQuarterDb: 28,
txAirSecs: 12,
rxAirSecs: 48,
)
: ReviewFrames.err(),
]);
break;
case cmdSetAdvertName:
_name = _readCString(frame, 1, maxNameSize - 1);
_emit([ReviewFrames.ok()]);
break;
case cmdSetAdvertLatLon:
if (frame.length >= 9) {
_latitudeE6 = readInt32LE(frame, 1);
_longitudeE6 = readInt32LE(frame, 5);
}
_emit([ReviewFrames.ok()]);
break;
case cmdSetRadioParams:
if (frame.length >= 11) {
_frequencyHz = readUint32LE(frame, 1);
_bandwidthHz = readUint32LE(frame, 5);
_spreadingFactor = frame[9];
_codingRate = frame[10];
}
_emit([ReviewFrames.ok()]);
break;
case cmdSetRadioTxPower:
if (frame.length >= 2) _txPowerDbm = frame[1];
_emit([ReviewFrames.ok()]);
break;
case cmdRemoveContact:
if (frame.length >= 1 + pubKeySize) {
final key = frame.sublist(1, 1 + pubKeySize);
_contacts.removeWhere((c) => listEquals(c.publicKey, key));
}
_emit([ReviewFrames.ok()]);
break;
case cmdSendLogin:
_handleLogin(frame);
break;
case cmdSendStatusReq:
case cmdSendTracePath:
case cmdSendBinaryReq:
case cmdSendAnonReq:
_emit([ReviewFrames.err()]);
break;
case cmdSendTelemetryReq:
// The 4-byte "self" form is answered with a push the app does not
// track; remote requests are answered with ERR.
if (frame.length > 4) _emit([ReviewFrames.err()]);
break;
default:
// Setters, advert, reset path, flood scope, import/export and any
// other command the app tracks get OK; untracked ones get nothing.
final reply = replyCodeForCommand(frame);
if (reply == respCodeOk) {
_emit([ReviewFrames.ok()]);
} else if (reply != null) {
_emit([ReviewFrames.err()]);
}
}
}
Uint8List _selfInfoFrame() => ReviewFrames.selfInfo(
publicKey: _selfKey,
name: _name,
latitudeE6: _latitudeE6,
longitudeE6: _longitudeE6,
frequencyHz: _frequencyHz,
bandwidthHz: _bandwidthHz,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: _txPowerDbm,
maxTxPowerDbm: ReviewScript.maxTxPowerDbm,
);
Uint8List _contactFrame(_Contact c) => ReviewFrames.contact(
publicKey: c.publicKey,
type: c.type,
path: c.path,
name: c.name,
lastAdvertSecs: c.lastAdvertSecs,
latitudeE6: c.latitudeE6,
longitudeE6: c.longitudeE6,
lastModSecs: c.lastModSecs,
);
void _handleGetContacts(Uint8List frame) {
final since = frame.length >= 5 ? readUint32LE(frame, 1) : 0;
final matching = _contacts.where((c) => c.lastModSecs > since).toList();
var mostRecent = since;
for (final c in matching) {
if (c.lastModSecs > mostRecent) mostRecent = c.lastModSecs;
}
_emit([
ReviewFrames.contactsStart(_contacts.length),
for (final c in matching) _contactFrame(c),
ReviewFrames.endOfContacts(mostRecent),
]);
}
void _handleGetContactByKey(Uint8List frame) {
if (frame.length >= 1 + pubKeySize) {
final key = frame.sublist(1, 1 + pubKeySize);
for (final c in _contacts) {
if (listEquals(c.publicKey, key)) {
_emit([_contactFrame(c)]);
return;
}
}
}
_emit([ReviewFrames.err(ReviewFrames.errNotFound)]);
}
void _handleGetChannel(Uint8List frame) {
final index = frame.length >= 2 ? frame[1] : 0;
if (index >= ReviewScript.maxChannels) {
_emit([ReviewFrames.err(ReviewFrames.errNotFound)]);
return;
}
final channel = _channels[index];
_emit([
ReviewFrames.channelInfo(
index: index,
name: channel?.name ?? '',
psk: channel?.psk ?? Uint8List(16),
),
]);
}
void _handleSetChannel(Uint8List frame) {
// [cmd][idx][name x32][psk x16]
if (frame.length >= 50) {
final index = frame[1];
final name = _readCString(frame, 2, 32);
final psk = Uint8List.fromList(frame.sublist(34, 50));
if (name.isEmpty && psk.every((b) => b == 0)) {
_channels.remove(index);
} else {
_channels[index] = _Channel(name, psk);
}
}
_emit([ReviewFrames.ok()]);
}
void _handleSendText(Uint8List frame) {
// [cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]\0
if (frame.length < 13) {
_emit([ReviewFrames.err()]);
return;
}
final attempt = frame[2];
final timestamp = readUint32LE(frame, 3);
final prefix = frame.sublist(7, 13);
final text = _readCString(frame, 13, frame.length - 13);
final contact = _contactByPrefix(prefix);
if (contact == null) {
_emit([ReviewFrames.err(ReviewFrames.errNotFound)]);
return;
}
final ackHash = MessageRetryService.computeExpectedAckHash(
timestamp,
attempt,
text,
_selfKey,
);
final tripMs = ackDelay.inMilliseconds;
_emit([
ReviewFrames.sent(
// Every simulated contact has a known path; an empty one is a
// direct neighbour, so sends are never flooded.
flood: false,
ackHash: ackHash,
timeoutMs: 8000,
),
]);
_later(ackDelay, () {
_emit([ReviewFrames.sendConfirmed(ackHash: ackHash, tripTimeMs: tripMs)]);
});
if (contact.type == advTypeChat || contact.type == advTypeRoom) {
_later(ackDelay + replyDelay, () {
final replies = ReviewScript.directReplies;
_messageQueue.add(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: replies[_directReplyIndex++ % replies.length],
timestampSecs: _nowSecs,
pathLen: contact.path.length,
),
);
_emit([ReviewFrames.msgWaiting()]);
});
}
}
void _handleLogin(Uint8List frame) {
// [cmd][pub_key x32][password...]
_Contact? contact;
if (frame.length >= 1 + pubKeySize) {
final key = frame.sublist(1, 1 + pubKeySize);
for (final c in _contacts) {
if (listEquals(c.publicKey, key)) contact = c;
}
}
if (contact == null) {
_emit([ReviewFrames.err(ReviewFrames.errNotFound)]);
return;
}
final target = contact;
// The firmware tags a login with the first 4 bytes of the target key.
_emit([
ReviewFrames.sent(
flood: false,
ackHash: readUint32LE(target.publicKey, 0),
timeoutMs: 8000,
),
]);
// Room servers accept any password so reviewers can open the room chat.
// Repeater administration needs real hardware, so it fails right away
// instead of leaving the login dialog waiting for a timeout.
_later(ackDelay, () {
_emit([
target.type == advTypeRoom
? ReviewFrames.loginSuccess(
publicKey: target.publicKey,
serverTimeSecs: _nowSecs,
)
: ReviewFrames.loginFail(publicKey: target.publicKey),
]);
});
}
void _handleSendChannelText(Uint8List frame) {
// [cmd][txt_type][channel_idx][timestamp x4][text...]\0
if (frame.length < 8) {
_emit([ReviewFrames.err()]);
return;
}
final channelIndex = frame[2];
_emit([ReviewFrames.ok()]);
final members = ReviewScript.channelMembers[channelIndex];
if (members == null ||
members.isEmpty ||
!_channels.containsKey(channelIndex)) {
return;
}
_later(replyDelay, () {
final replies = ReviewScript.channelReplies;
final index = _channelReplyIndex++;
final sender = members[index % members.length];
_messageQueue.add(
ReviewFrames.channelMessage(
channelIndex: channelIndex,
sender: sender,
message: replies[index % replies.length],
timestampSecs: _nowSecs,
path: _pathForSender(sender),
),
);
_emit([ReviewFrames.msgWaiting()]);
});
}
_Contact? _contactByPrefix(List<int> prefix) {
for (final c in _contacts) {
if (c.publicKey.length >= prefix.length &&
listEquals(c.publicKey.sublist(0, prefix.length), prefix)) {
return c;
}
}
return null;
}
String _readCString(Uint8List frame, int start, int maxLength) {
final end = (start + maxLength).clamp(start, frame.length);
final bytes = <int>[];
for (var i = start; i < end; i++) {
if (frame[i] == 0) break;
bytes.add(frame[i]);
}
return utf8.decode(bytes, allowMalformed: true);
}
void _later(Duration delay, void Function() action) {
if (_disposed) return;
late final Timer timer;
timer = Timer(delay, () {
_timers.remove(timer);
if (!_disposed) action();
});
_timers.add(timer);
}
/// Queues frames and flushes them from a timer, so a response is never
/// delivered synchronously inside [handle] and ordering is preserved.
void _emit(List<Uint8List> frames) {
if (_disposed) return;
_outbox.addAll(frames);
_flushTimer ??= Timer(Duration.zero, _flush);
}
void _flush() {
_flushTimer = null;
if (_disposed) return;
final pending = List<Uint8List>.of(_outbox);
_outbox.clear();
for (final frame in pending) {
if (_disposed || _controller.isClosed) return;
_controller.add(frame);
}
}
/// Cancels all timers and closes the stream. Safe to call twice.
void dispose() {
if (_disposed) return;
_disposed = true;
_scheduledTimer?.cancel();
_scheduledTimer = null;
_flushTimer?.cancel();
_flushTimer = null;
for (final t in _timers) {
t.cancel();
}
_timers.clear();
_outbox.clear();
unawaited(_controller.close());
}
}
class _Contact {
final Uint8List publicKey;
final int type;
final Uint8List path;
final String name;
final int lastAdvertSecs;
final int latitudeE6;
final int longitudeE6;
final int lastModSecs;
_Contact({
required this.publicKey,
required this.type,
required this.path,
required this.name,
required this.lastAdvertSecs,
required this.latitudeE6,
required this.longitudeE6,
required this.lastModSecs,
});
}
class _Channel {
final String name;
final Uint8List psk;
_Channel(this.name, this.psk);
}
class _SeedEntry {
final int agoSecs;
final Uint8List frame;
_SeedEntry(this.agoSecs, this.frame);
}
+297
View File
@@ -0,0 +1,297 @@
import '../connector/meshcore_protocol.dart';
/// A contact in the simulated radio's contact table.
class ReviewContact {
final String name;
final String publicKeyHex;
final int type;
/// One-byte path hashes, as hex. Empty means a direct (zero hop) path.
final String pathHex;
final double latitude;
final double longitude;
final int lastAdvertAgoSecs;
const ReviewContact({
required this.name,
required this.publicKeyHex,
required this.type,
required this.pathHex,
required this.latitude,
required this.longitude,
required this.lastAdvertAgoSecs,
});
int get hopCount => pathHex.length ~/ 2;
}
/// A channel slot configured on the simulated radio.
class ReviewChannel {
final int index;
final String name;
final String pskHex;
const ReviewChannel({
required this.index,
required this.name,
required this.pskHex,
});
}
/// A direct message from a script contact.
class ReviewDirectLine {
final int contactIndex;
final String text;
final int agoSecs;
const ReviewDirectLine({
required this.contactIndex,
required this.text,
this.agoSecs = 0,
});
}
/// A channel message from a script member.
class ReviewChannelLine {
final int channelIndex;
final String sender;
final String text;
final int agoSecs;
const ReviewChannelLine({
required this.channelIndex,
required this.sender,
required this.text,
this.agoSecs = 0,
});
}
/// The fake world the simulated radio lives in.
class ReviewScript {
ReviewScript._();
static const String selfName = 'Review Radio';
static const int selfLatitudeE6 = 45515232;
static const int selfLongitudeE6 = -122678385;
static const int frequencyHz = 910525000;
static const int bandwidthHz = 62500;
static const int spreadingFactor = 7;
static const int codingRate = 5;
static const int txPowerDbm = 20;
static const int maxTxPowerDbm = 22;
static const int firmwareVerCode = 14;
static const int maxContacts = 100;
static const int maxChannels = 8;
static const List<ReviewContact> contacts = [
ReviewContact(
name: 'Maya',
publicKeyHex:
'a95db5b0ac159e4384ff55ef91c94a98dc563d66a88e7b027fcd5190c0f5bed5',
type: advTypeChat,
pathHex: 'a1',
latitude: 45.5231,
longitude: -122.6765,
lastAdvertAgoSecs: 600,
),
ReviewContact(
name: 'Jordan',
publicKeyHex:
'136c67657614311f32238751044a0a3c0294f2a521e573afa8e496992d3786ba',
type: advTypeChat,
pathHex: 'a1c4',
latitude: 45.5089,
longitude: -122.6912,
lastAdvertAgoSecs: 1800,
),
ReviewContact(
name: 'Sam',
publicKeyHex:
'e96e02d8e47f2a7c03be5117b3ed175c52aa30fb22028cf9c96f261563577605',
type: advTypeChat,
pathHex: '',
latitude: 45.5176,
longitude: -122.6701,
lastAdvertAgoSecs: 240,
),
ReviewContact(
name: 'Ranger Pat',
publicKeyHex:
'dbc4a04327176e6577b4da46df04564150053960eba5d89587dad1f76a818d80',
type: advTypeChat,
pathHex: 'a1c47f',
latitude: 45.5402,
longitude: -122.7120,
lastAdvertAgoSecs: 3600,
),
ReviewContact(
name: 'Hilltop Repeater',
publicKeyHex:
'409e364456fa93642cd24878f532fffe31e3aae5944d04239a7d023e66ebdbe3',
type: advTypeRepeater,
pathHex: '',
latitude: 45.5298,
longitude: -122.7064,
lastAdvertAgoSecs: 120,
),
ReviewContact(
name: 'Trailhead Room',
publicKeyHex:
'08d33503ee27d4c13055d0cefec5e730be4ef2e41cd6cfce434936ec1e7c9d4b',
type: advTypeRoom,
pathHex: 'a1',
latitude: 45.5350,
longitude: -122.6650,
lastAdvertAgoSecs: 900,
),
];
static const List<ReviewChannel> channels = [
ReviewChannel(
index: 0,
name: 'Public',
pskHex: '8b3387e9c5cdea6ac9e5edbaa115cd72',
),
ReviewChannel(
index: 1,
name: 'Hiking Group',
pskHex: 'dd488fa58a29956b6271b573e1a33ac5',
),
ReviewChannel(
index: 2,
name: 'Local Net',
pskHex: '8bca9c2e3ef52ebcd61d30ec6c724a25',
),
];
/// Senders that may speak in each channel, by channel index.
static const Map<int, List<String>> channelMembers = {
0: ['Maya', 'Sam'],
1: ['Jordan', 'Sam'],
2: ['Ranger Pat', 'Maya'],
};
static const List<ReviewDirectLine> seedDirectMessages = [
ReviewDirectLine(
contactIndex: 0,
text: 'Hey! Are you heading up to the ridge this weekend?',
agoSecs: 7200,
),
ReviewDirectLine(
contactIndex: 0,
text: 'The repeater on the hill is showing a great signal today.',
agoSecs: 6900,
),
ReviewDirectLine(
contactIndex: 1,
text: 'Signal check from the trailhead. Reading you loud and clear.',
agoSecs: 3300,
),
];
static const List<ReviewChannelLine> seedChannelMessages = [
ReviewChannelLine(
channelIndex: 0,
sender: 'Maya',
text: 'Good morning mesh! Anyone on the air?',
agoSecs: 5400,
),
ReviewChannelLine(
channelIndex: 1,
sender: 'Jordan',
text: 'Planning to leave the trailhead at 8 on Saturday.',
agoSecs: 4800,
),
ReviewChannelLine(
channelIndex: 1,
sender: 'Sam',
text: 'I will bring the spare battery pack.',
agoSecs: 4500,
),
ReviewChannelLine(
channelIndex: 2,
sender: 'Ranger Pat',
text: 'Weekly net check-in starts at 7 pm. Please report your signal.',
agoSecs: 2400,
),
];
/// Scheduled incoming direct messages, cycled in order.
static const List<ReviewDirectLine> incomingDirectPool = [
ReviewDirectLine(
contactIndex: 0,
text: 'Just got a message through the hilltop repeater. Nice!',
),
ReviewDirectLine(
contactIndex: 1,
text: 'Battery is at 80 percent. Plenty for the whole hike.',
),
ReviewDirectLine(
contactIndex: 2,
text: 'Can you hear me from the creek crossing?',
),
ReviewDirectLine(
contactIndex: 3,
text: 'Trail conditions are good. A little muddy near the bridge.',
),
ReviewDirectLine(
contactIndex: 0,
text: 'Testing a new antenna today. How is my signal?',
),
ReviewDirectLine(
contactIndex: 2,
text: 'Heading back down now. See you at the trailhead.',
),
];
/// Scheduled incoming channel messages, cycled in order.
static const List<ReviewChannelLine> incomingChannelPool = [
ReviewChannelLine(
channelIndex: 0,
sender: 'Sam',
text: 'Radio check, one two three. Anyone copy?',
),
ReviewChannelLine(
channelIndex: 1,
sender: 'Jordan',
text: 'We reached the lookout. The view is great!',
),
ReviewChannelLine(
channelIndex: 2,
sender: 'Ranger Pat',
text: 'Reminder: the net is open to everyone. Say hello.',
),
ReviewChannelLine(
channelIndex: 0,
sender: 'Maya',
text: 'Clear skies and a strong signal across town today.',
),
ReviewChannelLine(
channelIndex: 1,
sender: 'Sam',
text: 'Anyone need water? I am refilling at the next stop.',
),
ReviewChannelLine(
channelIndex: 2,
sender: 'Maya',
text: 'Checking in from the east side. Copy you five by five.',
),
];
/// Auto-replies to a direct message the app sends.
static const List<String> directReplies = [
'Got it, thanks!',
'Sounds good to me.',
'Message received loud and clear.',
'Thanks for the update. Talk soon!',
];
/// Auto-replies to a channel message the app sends.
static const List<String> channelReplies = [
'Copy that!',
'Welcome to the mesh!',
'Heard you loud and clear.',
'Thanks for checking in.',
];
}