fix(#1060): erased slots never overwrite the channel list, and radio notify follows the channel

Two findings from the owner's field report: a Channels screen full of
replacement characters, and a channel he had silenced chirping again.

An erased record is not an empty one. Erased flash reads back 0xFF and
Channel.isEmpty tests for 0x00, so a slot the radio had LOST was adopted
as a channel, rendered with U+FFFD, and then persisted over the client's
own good cached list. One missing validation gate, two symptoms.

- Channel.isErased / isUnusable: an all-0xFF record, or a name that did
  not decode, is never adopted.
- A sync that sees an erased slot KEEPS the cached list, reusing the
  fail-closed branch #1062 already had for unconfirmed holes.
- restoreChannelsToRadio() writes the cache back to the original slots
  with their PSKs, behind a confirmed banner action.

Radio notify was keyed by slot, not identity. #544 landed after #1061 and
keyed its in-memory map by slot index; the slot-identity handler cleared
the slot's messages but not its notify mode, so a channel that moved
slots handed its mode to the new occupant and lost its own.

- _channelNotifyModes is keyed by PSK hex, matching channelNotifyModesByRadio
  (#848) and the PSK-keyed history (#194).
- A reply whose slot does not resolve to a confirmed channel is dropped.
- setChannelNotify takes a Channel and resolves its CURRENT slot at send
  time, so a stale handle cannot address the wrong one; unresolvable is a
  visible refusal, not a silent write.

Both guards proved against planted defects: forcing isErased false turns
5 tests red including the cache overwrite, and restoring the slot-keyed
map yields Expected: null, Actual: RadioChannelNotify.off.

flutter analyze clean, 1885 tests pass. New strings English-only with
untranslated.json regenerated.

Task: meshcore-open-75d
Agent: CalmBay

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/1068-radio-channel-notify
diffwireauto 3 weeks ago
parent 061451c48e
commit 383ed5f9ee

@ -0,0 +1,95 @@
# Channel identity alignment: erased slots and slot-keyed notify (#1060)
Agent: CalmBay. Branch `feat/1068-radio-channel-notify`. No push, no PR.
## 1. Who owns the "key by identity, not slot" work
**Feature #1061, agent TurquoiseBridge (session 82d77b2f).** The identity key is
the channel's **PSK hex**, not a pubkey; channels have no pubkey, and the PSK is
what both history and settings already hang off.
| Issue | What | State |
|---|---|---|
| #1060 | the bug: slot map diverges after wipe + re-import, wrong-channel notifications | open |
| #1061 | feature: channel state follows channel identity | open |
| #1062 | fail-closed sync, ingress barrier, slot identity diff | landed |
| #1063 | message history keyed by channel identity | landed |
| #1064 | integration testing + #1060 bug validation | **open** |
The pattern itself is older than #1061: `feat(#260)` (2026-07-17) introduced
PSK-keyed notify storage, `fix(#848)` scoped it per radio and killed the index
fallback, and `#194` keyed message history the same way.
`test/connector/channel_slot_resync_integration_test.dart` already encodes the
exact field case, down to `#wardriving` set to OFF.
## 2. What was still slot-keyed
#544 (epics #1068-#1071, this branch) added the RADIO-side per-channel notify
after #1061 landed, and keyed it by **slot index**:
```dart
final Map<int, RadioChannelNotify> _channelNotifyModes = {};
```
That re-opened the exact class of defect #1061 was built to close, on the one
surface where the user notices it fastest: the buzzer. The slot-identity-change
handler cleared `_channelMessages[slot]` but not `_channelNotifyModes[slot]`,
so after a slot shift the new occupant inherited the old one's mode.
Reproduced by planting the slot-keyed map back and running the new A5 test:
```
Expected: null
Actual: RadioChannelNotify:<RadioChannelNotify.off>
```
A channel silenced on the radio handing its Off to whatever took its slot, and
losing its own. That is the chirping.
### Fixed
- `_channelNotifyModes` is keyed by **PSK hex**. The wire stays slot-addressed;
the slot is resolved to an identity at the wire edge and nowhere else.
- A reply whose slot does not resolve to a confirmed channel is **dropped**,
not stored against a slot number.
- `setChannelNotify` takes a `Channel` and resolves its **current** slot at
send time, so a `Channel` a widget captured before a re-sync cannot address a
stale slot. Unresolvable means a visible refusal, no frame.
## 3. The erased-slot defect
Erased flash reads back as `0xFF`. `Channel.isEmpty` tests for `0x00`, so an
erased record is not empty: it was adopted as a channel, rendered with U+FFFD
replacement characters, and then **saved over the client's own good list**.
That is one missing validation gate, not two defects. The rendering and the
overwrite are the same hole seen twice.
### Fixed
- `Channel.isErased` / `isUnusable`: an all-`0xFF` record, or a name that did
not decode, is never adopted.
- A sync that sees an erased slot **keeps the cached list** instead of
overwriting it, reusing the fail-closed branch #1062 already had for holes.
- `restoreChannelsToRadio()` writes the cached channels back to their own
slots, with their PSKs, so history and settings line up again. Surfaced as an
undismissable banner with a confirmed **Restore to radio** action.
Probe: forcing `isErased => false` turns 5 of the new tests red, including the
cache overwrite.
## 4. Recovery for the list already lost
Not built, flagged for a decision. Message history keys are
`channel_messages_<devicePrefix>psk_<pskHex>`, so **the PSKs of the lost
channels still exist in the message store** even though the channel list was
overwritten. A recovery pass could enumerate those keys and rebuild the list.
Names would need retyping; the PSK is the part that matters.
## 5. State
`flutter analyze` clean. **1885 tests pass, 1 skipped.** New strings are
English-only with `untranslated.json` regenerated.
Not pushed, no PR: the owner's gate is a hardware test first.

@ -452,7 +452,14 @@ class MeshCoreConnector extends ChangeNotifier {
/// Written only from a device reply, and cleared per radio like every other
/// device-UI surface. Slot-derived state: #1061's identity diff must reset
/// it when a slot's PSK changes, or it describes the wrong channel.
final Map<int, RadioChannelNotify> _channelNotifyModes = {};
// #1060/#544: keyed by channel PSK hex, NOT by slot index. The wire is
// slot-addressed, but a slot is not an identity: when a channel moves slots
// (wipe + re-import, manual reorder) a slot-keyed mode follows the SLOT and
// lands on whatever channel now sits there. That is how a channel set to
// None started chirping again. The slot is resolved at the wire edge only,
// and everything the client holds or shows is keyed by PSK, matching the
// app's own `channelNotifyModesByRadio` (#848) and PSK-keyed history (#194).
final Map<String, RadioChannelNotify> _channelNotifyModes = {};
final Map<ToneEvent, EventToneState> _eventTones = {};
final Map<int, TuneSlotInfo> _tuneSlots = {};
ScreenSettingsState? _screenSettings;
@ -616,6 +623,25 @@ class MeshCoreConnector extends ChangeNotifier {
Set<int> get unconfirmedChannelSlots =>
Set.unmodifiable(_unconfirmedChannelSlots);
// #1060: slots the device answered for with an ERASED record (all-0xFF).
// The device answering is not the same as the device having a channel: a
// reflash or a wipe leaves readable garbage, not silence. These are refused
// rather than adopted, and their presence blocks the cached-list overwrite
// below, because a cached list the user can still see is better data than
// erased flash.
final Set<int> _erasedChannelSlots = {};
/// Device slots that answered with an erased record on the latest sync.
/// Non-empty means the radio lost channel storage and the client is holding
/// its own cached list instead (#1060).
Set<int> get erasedChannelSlots => Set.unmodifiable(_erasedChannelSlots);
/// True when the radio reported erased slots and the client therefore kept a
/// cached channel list the radio no longer has. The UI offers a restore.
bool get canRestoreChannelsToRadio =>
_erasedChannelSlots.isNotEmpty &&
_cachedChannels.any((c) => !c.isUnusable);
// #1062: ingress barrier. Live channel traffic is held while this
// connection's channel list is not yet synced, then flushed, so a message
// is never filed against a guessed slot map. Held MESSAGE frames are keyed
@ -1082,8 +1108,11 @@ class MeshCoreConnector extends ChangeNotifier {
/// The radio's notify mode for [channel], or null until the radio has
/// reported it. Null is "not yet known", distinct from
/// [RadioChannelNotify.unset], which is the radio saying no choice is set.
RadioChannelNotify? channelNotifyFor(int channel) =>
_channelNotifyModes[channel];
///
/// Looked up by the channel's PSK identity, so a mode read for one channel
/// can never be shown against another that later occupies its slot (#1060).
RadioChannelNotify? channelNotifyFor(Channel channel) =>
_channelNotifyModes[channel.pskHex];
/// The tune the radio reported for [event], or null if not read yet.
EventToneState? eventTone(ToneEvent event) => _eventTones[event];
@ -1399,19 +1428,53 @@ class MeshCoreConnector extends ChangeNotifier {
/// Set the radio's notify mode for [channel]. Local state follows the
/// device's re-read reply, never the request, so a refused choice is never
/// shown as saved.
Future<void> setChannelNotify(int channel, RadioChannelNotify mode) async {
/// The slot [channel] currently occupies on the radio, by PSK identity, or
/// null when the synced list does not hold it. The caller's own
/// [Channel.index] is deliberately not trusted: it may have been captured
/// before a re-sync moved the channel, and writing to a stale slot is how a
/// setting lands on the wrong channel (#1060).
int? _liveSlotFor(Channel channel) {
if (!_channelListSynced) return null;
for (final c in _channels) {
if (c.pskHex == channel.pskHex && !c.isUnusable) return c.index;
}
return null;
}
Future<void> setChannelNotify(
Channel channel,
RadioChannelNotify mode,
) async {
if (!_deviceUiGateOpen('chnotify SET', advertised: supportsChannelNotify)) {
return;
}
final slot = _liveSlotFor(channel);
if (slot == null) {
// Fail closed and visibly, per #1021's rule: refuse the write and say
// why, rather than addressing a slot whose occupant is unconfirmed.
_deviceUiError =
'This channel is not confirmed on the radio right now, so its '
'sound setting was not written. Refresh the channel list and try '
'again.';
_deviceUiErrorSurface = DeviceUiSurface.channelNotify;
_pendingDeviceUiWrite = null;
_appDebugLogService?.error(
'chnotify SET refused: "${channel.name}" (psk ${channel.pskHex}) '
'does not resolve to a confirmed slot; no frame sent',
tag: 'DeviceUI',
);
notifyListeners();
return;
}
_deviceUiError = null;
_deviceUiErrorSurface = null;
_pendingDeviceUiWrite = DeviceUiSurface.channelNotify;
_appDebugLogService?.info(
'chnotify SET -> ch=$channel mode=${mode.name} '
'chnotify SET -> ch=$slot "${channel.name}" mode=${mode.name} '
'stored=${mode.stored} [0xC5][0x19]',
tag: 'DeviceUI',
);
await sendFrame(buildChannelNotifySetFrame(channel, mode));
await sendFrame(buildChannelNotifySetFrame(slot, mode));
}
/// Ask the radio how GPS is running (#969).
@ -1939,10 +2002,27 @@ class MeshCoreConnector extends ChangeNotifier {
if (isWrite && _pendingDeviceUiWrite == DeviceUiSurface.channelNotify) {
_pendingDeviceUiWrite = null;
}
_channelNotifyModes[reply.channel] = reply.mode;
// #1060: the wire gives a slot; the client stores an identity. Resolve the
// slot against the synced list and drop the reply if it cannot be
// resolved, rather than filing a mode under a slot number that may mean a
// different channel by the time anything reads it.
final channel = _findChannelByIndex(reply.channel);
if (channel == null || channel.isUnusable) {
_appDebugLogService?.warn(
'chnotify reply for slot ${reply.channel} '
'(mode=${reply.mode.name}) does not resolve to a known channel; '
'dropped rather than stored against a slot number',
tag: 'DeviceUI',
);
// A pending write was still cleared above, so the UI must be released
// from "saving" even though nothing was stored.
notifyListeners();
return;
}
_channelNotifyModes[channel.pskHex] = reply.mode;
_appDebugLogService?.info(
'chnotify reply: ch=${reply.channel} mode=${reply.mode.name} '
'(${isWrite ? 'write confirmed' : 'read'})',
'chnotify reply: ch=${reply.channel} "${channel.name}" '
'mode=${reply.mode.name} (${isWrite ? 'write confirmed' : 'read'})',
tag: 'DeviceUI',
);
notifyListeners();
@ -4413,6 +4493,11 @@ class MeshCoreConnector extends ChangeNotifier {
_cachedChannels = List<Channel>.from(channels);
}
/// The last fully-confirmed channel list this client persisted. Survives a
/// sync that found erased slots, which is what makes a restore possible
/// (#1060).
List<Channel> get cachedChannels => List.unmodifiable(_cachedChannels);
@visibleForTesting
Channel? findChannelByIndexForTest(int index) => _findChannelByIndex(index);
@ -4510,6 +4595,7 @@ class MeshCoreConnector extends ChangeNotifier {
// Raw sniff frames are lossy observations; a dead connection's are stale.
_channelListSynced = false;
_unconfirmedChannelSlots.clear();
_erasedChannelSlots.clear();
_slotIdentityChanges.clear();
_heldRawChannelFrames.clear();
}
@ -6649,6 +6735,7 @@ class MeshCoreConnector extends ChangeNotifier {
// against a stale one (#1062).
_channelListSynced = false;
_unconfirmedChannelSlots.clear();
_erasedChannelSlots.clear();
_previousChannelsCache = List<Channel>.from(_channels);
_channels.clear();
_nextChannelIndexToRequest = 0;
@ -6781,7 +6868,19 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
if (_unconfirmedChannelSlots.isEmpty) {
if (_erasedChannelSlots.isNotEmpty) {
// #1060: the radio answered, but for erased slots. "Device is truth"
// assumes the device HAS the truth; erased flash is the device having
// lost it. Writing this over the cache would turn one-sided loss on the
// radio into total loss, so the cached list stands and the UI offers to
// push it back.
_appDebugLogService?.error(
'Channel sync found ERASED slots $_erasedChannelSlots. The radio has '
'lost those channels. Cached list NOT overwritten (${_cachedChannels.where((c) => !c.isUnusable).length} '
'channel(s) retained); use Restore to write them back to the radio.',
tag: 'ChannelSync',
);
} else if (_unconfirmedChannelSlots.isEmpty) {
// Full confirmation: the fresh list is the truth, replace the cache.
_cachedChannels = List<Channel>.from(_channels);
unawaited(
@ -6990,6 +7089,44 @@ class MeshCoreConnector extends ChangeNotifier {
await getChannels(force: true);
}
/// Writes the client's cached channel list back onto the radio (#1060).
///
/// For a radio that lost channel storage (reflash, wipe) the client's cache
/// is the only surviving copy. Each cached channel goes back to the slot it
/// came from, so PSK-keyed history and per-channel settings line up again.
///
/// Frames are sent directly rather than through [setChannel] because that
/// re-syncs after every write; this re-syncs once at the end. Nothing here
/// clears history: the identities being restored are the ones that own it.
///
/// Returns the number of channels written, or -1 when there was nothing to
/// restore or the link is down.
Future<int> restoreChannelsToRadio() async {
if (!isConnected) return -1;
final toRestore = _cachedChannels.where((c) => !c.isUnusable).toList();
if (toRestore.isEmpty) return -1;
_appDebugLogService?.info(
'Restoring ${toRestore.length} cached channel(s) to the radio: '
'${toRestore.map((c) => 'slot ${c.index} "${c.name}"').join(', ')}',
tag: 'ChannelSync',
);
var written = 0;
for (final channel in toRestore) {
if (!isConnected) break;
await sendFrame(
buildSetChannelFrame(channel.index, channel.name, channel.psk),
);
written++;
}
// The radio now holds these again, so a fresh sync should confirm them and
// the erased-slot block clears itself on the next pass.
await getChannels(force: true);
return written;
}
Future<void> deleteChannel(int index) async {
if (!isConnected) return;
@ -10250,6 +10387,22 @@ class MeshCoreConnector extends ChangeNotifier {
'[ChannelSync] Received channel ${channel.index}: ${channel.isEmpty ? "empty" : channel.name}',
);
// #1060: an erased record is the radio having LOST this slot, not the
// radio reporting a channel. Adopting it would render replacement
// characters as a channel name, and persisting it would destroy the
// client's own good copy. Refuse it here, loudly, and let the sync
// completion keep the cached list.
if (channel.isErased) {
if (_erasedChannelSlots.add(channel.index)) {
_appDebugLogService?.error(
'Channel slot ${channel.index} came back ERASED (all-0xFF name/PSK). '
'The radio has lost this channel. Refusing to adopt it, and the '
'cached channel list will NOT be overwritten.',
tag: 'ChannelSync',
);
}
}
// Preserve unread count from the cached channel, but only when the slot
// still holds the SAME channel. An unread count following the slot across
// an identity change is another channel's count (#1062).
@ -10269,8 +10422,9 @@ class MeshCoreConnector extends ChangeNotifier {
_channelSyncInFlight = false;
_channelSyncRetries = 0; // Reset retry counter on success
// Only add non-empty channels
if (!channel.isEmpty) {
// Only add slots that carry a usable channel. An erased slot is
// skipped exactly like an empty one (#1060).
if (!channel.isUnusable) {
_channels.add(channel);
}
@ -10286,7 +10440,7 @@ class MeshCoreConnector extends ChangeNotifier {
'[ChannelSync] Received unexpected channel ${channel.index}, expected $_nextChannelIndexToRequest',
);
// Add it anyway but don't advance sync
if (!channel.isEmpty &&
if (!channel.isUnusable &&
!_channels.any((c) => c.index == channel.index)) {
_channels.add(channel);
}
@ -10295,7 +10449,7 @@ class MeshCoreConnector extends ChangeNotifier {
}
// Not syncing, or received unsolicited update - handle normally
if (!channel.isEmpty) {
if (!channel.isUnusable) {
// Update or add channel
final existingIndex = _channels.indexWhere(
(c) => c.index == channel.index,

@ -845,6 +845,35 @@
}
},
"channels_retrySync": "Retry sync",
"channels_erasedSlots": "The radio has lost the channels in slot(s) {slots}; it reported them as erased. Your channel list here has been kept and was not overwritten.",
"@channels_erasedSlots": {
"placeholders": {
"slots": {
"type": "String"
}
}
},
"channels_restoreToRadio": "Restore to radio",
"channels_restoreToRadioConfirm": "Write {count} channel(s) back to the radio: {names}. This replaces whatever those slots hold now.",
"@channels_restoreToRadioConfirm": {
"placeholders": {
"count": {
"type": "int"
},
"names": {
"type": "String"
}
}
},
"channels_restoreToRadioDone": "Restored {count} channel(s) to the radio.",
"@channels_restoreToRadioDone": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"channels_restoreToRadioFailed": "Could not restore the channel list: nothing cached to restore, or the radio is not connected.",
"channels_slotIdentityChanged": "Channel layout changed on the radio: {changes}",
"@channels_slotIdentityChanged": {
"placeholders": {

@ -2830,6 +2830,36 @@ abstract class AppLocalizations {
/// **'Retry sync'**
String get channels_retrySync;
/// No description provided for @channels_erasedSlots.
///
/// In en, this message translates to:
/// **'The radio has lost the channels in slot(s) {slots}; it reported them as erased. Your channel list here has been kept and was not overwritten.'**
String channels_erasedSlots(String slots);
/// No description provided for @channels_restoreToRadio.
///
/// In en, this message translates to:
/// **'Restore to radio'**
String get channels_restoreToRadio;
/// No description provided for @channels_restoreToRadioConfirm.
///
/// In en, this message translates to:
/// **'Write {count} channel(s) back to the radio: {names}. This replaces whatever those slots hold now.'**
String channels_restoreToRadioConfirm(int count, String names);
/// No description provided for @channels_restoreToRadioDone.
///
/// In en, this message translates to:
/// **'Restored {count} channel(s) to the radio.'**
String channels_restoreToRadioDone(int count);
/// No description provided for @channels_restoreToRadioFailed.
///
/// In en, this message translates to:
/// **'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'**
String get channels_restoreToRadioFailed;
/// No description provided for @channels_slotIdentityChanged.
///
/// In en, this message translates to:

@ -1587,6 +1587,28 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1581,6 +1581,28 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1563,6 +1563,28 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1582,6 +1582,28 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1587,6 +1587,28 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1588,6 +1588,28 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1583,6 +1583,28 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1531,6 +1531,28 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1526,6 +1526,28 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1574,6 +1574,28 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1593,6 +1593,28 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1583,6 +1583,28 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1584,6 +1584,28 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1574,6 +1574,28 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1571,6 +1571,28 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1565,6 +1565,28 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1579,6 +1579,28 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -1512,6 +1512,28 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get channels_retrySync => 'Retry sync';
@override
String channels_erasedSlots(String slots) {
return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.';
}
@override
String get channels_restoreToRadio => 'Restore to radio';
@override
String channels_restoreToRadioConfirm(int count, String names) {
return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.';
}
@override
String channels_restoreToRadioDone(int count) {
return 'Restored $count channel(s) to the radio.';
}
@override
String get channels_restoreToRadioFailed =>
'Could not restore the channel list: nothing cached to restore, or the radio is not connected.';
@override
String channels_slotIdentityChanged(String changes) {
return 'Channel layout changed on the radio: $changes';

@ -25,6 +25,23 @@ class Channel {
bool get isEmpty => name.isEmpty && psk.every((b) => b == 0);
/// A slot the radio answered for that holds no usable channel.
///
/// Erased flash reads back as 0xFF, not 0x00, so such a record is NOT
/// [isEmpty]: the name decodes through `allowMalformed` into U+FFFD
/// replacement characters and the PSK is all-ones. Both halves are checked
/// because either one being unreadable makes the record unusable as a
/// channel identity, and the PSK is what every per-channel setting is keyed
/// by (#1060).
///
/// The client must never adopt one of these as a channel, and must never
/// persist a list containing one over a known-good cached list.
bool get isErased =>
name.contains('<EFBFBD>') || (psk.isNotEmpty && psk.every((b) => b == 0xFF));
/// A slot that carries no channel the client should hold, for either reason.
bool get isUnusable => isEmpty || isErased;
bool get isPublicChannel => pskHex == publicChannelPsk;
static Channel? fromFrame(Uint8List frame) {

@ -209,6 +209,30 @@ class _ChannelsScreenState extends State<ChannelsScreen>
),
],
),
// #1060: the radio answered for these slots with erased
// records. Undismissable: the radio has lost channels the
// client still holds, and the only way out is to write them
// back or accept the loss deliberately.
if (connector.erasedChannelSlots.isNotEmpty)
MaterialBanner(
backgroundColor: Theme.of(
context,
).colorScheme.errorContainer,
content: Text(
context.l10n.channels_erasedSlots(
connector.erasedChannelSlots.toList().join(', '),
),
),
actions: [
if (connector.canRestoreChannelsToRadio)
TextButton(
onPressed: () => unawaited(
_confirmRestoreChannels(context, connector),
),
child: Text(context.l10n.channels_restoreToRadio),
),
],
),
if (connector.slotIdentityChanges.isNotEmpty)
MaterialBanner(
content: Text(
@ -581,7 +605,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
final live = tileContext.watch<MeshCoreConnector>();
final effective = radioChannelNotifyEffective(
tileContext,
live.channelNotifyFor(channel.index),
live.channelNotifyFor(channel),
live.deviceNotifyScope,
);
return ListTile(
@ -1616,6 +1640,52 @@ class _ChannelsScreenState extends State<ChannelsScreen>
);
}
/// Writes the client's cached channels back onto a radio that lost them
/// (#1060). Confirmed first: it overwrites whatever those slots hold now.
Future<void> _confirmRestoreChannels(
BuildContext context,
MeshCoreConnector connector,
) async {
final toRestore = connector.cachedChannels
.where((c) => !c.isUnusable)
.toList();
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(dialogContext.l10n.channels_restoreToRadio),
content: Text(
dialogContext.l10n.channels_restoreToRadioConfirm(
toRestore.length,
toRestore.map((c) => c.name).join(', '),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(dialogContext.l10n.common_cancel),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(dialogContext.l10n.channels_restoreToRadio),
),
],
),
);
if (confirmed != true) return;
final written = await connector.restoreChannelsToRadio();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
written < 0
? context.l10n.channels_restoreToRadioFailed
: context.l10n.channels_restoreToRadioDone(written),
),
persist: written < 0,
);
}
void _confirmDeleteChannel(
BuildContext context,
MeshCoreConnector connector,

@ -84,7 +84,7 @@ void showRadioChannelNotifyDialog(BuildContext context, Channel channel) {
// State follows the radio's reply, never the tap: until the radio has
// answered for this slot there is no current value to tick, and a
// write that it refuses never appears as saved.
final current = live.channelNotifyFor(channel.index);
final current = live.channelNotifyFor(channel);
final error = live.deviceUiErrorSurface == DeviceUiSurface.channelNotify
? live.deviceUiError
: null;
@ -132,7 +132,7 @@ void showRadioChannelNotifyDialog(BuildContext context, Channel channel) {
trailing: mode == current ? const Icon(Icons.check) : null,
onTap: () async {
Navigator.pop(dialogContext);
await connector.setChannelNotify(channel.index, mode);
await connector.setChannelNotify(channel, mode);
},
),
],

@ -0,0 +1,248 @@
// #1060: a radio that has LOST its channel storage still answers for every
// slot. Erased flash reads back as 0xFF, so the reply is a well-formed
// CHANNEL_INFO frame carrying garbage, not silence and not an error.
//
// The field case: a reflash between two sessions left slot 0 ("Public")
// intact and slots 1+ entirely 0xFF. The client adopted those records as
// channels, rendered their names as replacement characters, and then
// persisted them over the user's own good cached list, turning one-sided loss
// on the radio into loss on both sides.
import 'dart:typed_data';
import 'package:drift/native.dart';
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/models/channel.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';
Uint8List _channelInfoFrame({
required int index,
required String name,
required int pskSeed,
}) {
final frame = Uint8List(50);
frame[0] = respCodeChannelInfo;
frame[1] = index;
final nameBytes = name.codeUnits;
for (var i = 0; i < nameBytes.length && i < 31; i++) {
frame[2 + i] = nameBytes[i];
}
for (var i = 0; i < 16; i++) {
frame[34 + i] = (pskSeed + i) & 0xFF;
}
return frame;
}
/// Everything after the slot index reads back as erased flash.
Uint8List _erasedFrame(int index) {
final frame = Uint8List(50);
frame[0] = respCodeChannelInfo;
frame[1] = index;
for (var i = 2; i < 50; i++) {
frame[i] = 0xFF;
}
return frame;
}
Channel _channel(int index, String name, int pskSeed) => Channel(
index: index,
name: name,
psk: Uint8List.fromList(List<int>.generate(16, (i) => (pskSeed + i) & 0xFF)),
);
Future<void> _settle([int turns = 25]) async {
for (var i = 0; i < turns; i++) {
await Future<void>.delayed(Duration.zero);
}
}
void main() {
late OffbandDatabase db;
late MeshCoreConnector c;
late List<List<int>> sent;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
sent = [];
c = MeshCoreConnector();
c.sendFrameOverrideForTest = (data) => sent.add(data.toList());
c.setConnectedForTest();
});
tearDown(() async {
BlobStore.clearTestOverride();
await db.close();
});
group('the erased record itself', () {
test('an all-0xFF record is erased, and is NOT caught by isEmpty', () {
final erased = Channel.fromFrame(_erasedFrame(1))!;
expect(erased.isErased, isTrue);
expect(erased.isUnusable, isTrue);
// This is the exact gap that let the garbage through: isEmpty tests for
// 0x00, and erased flash is 0xFF.
expect(
erased.isEmpty,
isFalse,
reason: 'if this ever passes, isEmpty alone would have been enough',
);
});
test('the erased name is replacement characters, which is what showed', () {
final erased = Channel.fromFrame(_erasedFrame(1))!;
expect(erased.name, contains('<EFBFBD>'));
});
test('a real channel is neither empty nor erased', () {
final real = Channel.fromFrame(
_channelInfoFrame(index: 0, name: 'Public', pskSeed: 10),
)!;
expect(real.isErased, isFalse);
expect(real.isEmpty, isFalse);
expect(real.isUnusable, isFalse);
expect(real.name, 'Public');
});
test('a genuinely empty slot is still empty, not erased', () {
final empty = Channel.fromFrame(
Uint8List(50)..[0] = respCodeChannelInfo,
)!;
expect(empty.isEmpty, isTrue);
expect(empty.isErased, isFalse);
expect(empty.isUnusable, isTrue);
});
});
group('sync against a radio that lost its channels', () {
/// The field case: slot 0 survived, slots 1 and 2 came back erased.
Future<void> syncWithErasedTail() async {
await c.getChannels(force: true, maxChannels: 3);
c.handleFrameForTest(
_channelInfoFrame(index: 0, name: 'Public', pskSeed: 10),
);
await _settle(2);
c.handleFrameForTest(_erasedFrame(1));
await _settle(2);
c.handleFrameForTest(_erasedFrame(2));
await _settle();
}
test('erased slots are not adopted as channels', () async {
await syncWithErasedTail();
expect(c.channels.map((ch) => ch.index), [0]);
expect(c.channels.single.name, 'Public');
expect(
c.channels.any((ch) => ch.name.contains('<EFBFBD>')),
isFalse,
reason: 'no channel may be named with replacement characters',
);
});
test(
'erased slots are reported, so the UI can say what happened',
() async {
await syncWithErasedTail();
expect(c.erasedChannelSlots, {1, 2});
},
);
test('the good cached list is NOT overwritten', () async {
c.seedCachedChannelsForTest([
_channel(0, 'Public', 10),
_channel(1, 'wardriving', 40),
_channel(2, 'test', 50),
]);
await syncWithErasedTail();
// The data-loss fix: the client keeps its own copy of the channels the
// radio has lost, rather than saving erased records over them.
expect(c.cachedChannels.map((ch) => ch.name), [
'Public',
'wardriving',
'test',
]);
expect(c.canRestoreChannelsToRadio, isTrue);
});
test('a clean sync still replaces the cache', () async {
c.seedCachedChannelsForTest([_channel(0, 'stale', 99)]);
await c.getChannels(force: true, maxChannels: 2);
c.handleFrameForTest(
_channelInfoFrame(index: 0, name: 'Public', pskSeed: 10),
);
await _settle(2);
c.handleFrameForTest(
_channelInfoFrame(index: 1, name: 'wardriving', pskSeed: 40),
);
await _settle();
expect(
c.cachedChannels.map((ch) => ch.name),
['Public', 'wardriving'],
reason: 'the guard must not block a healthy sync',
);
expect(c.erasedChannelSlots, isEmpty);
expect(c.canRestoreChannelsToRadio, isFalse);
});
});
group('restoring the list to the radio', () {
test('every cached channel is written back to its own slot', () async {
c.seedCachedChannelsForTest([
_channel(0, 'Public', 10),
_channel(1, 'wardriving', 40),
]);
sent.clear();
final written = await c.restoreChannelsToRadio();
expect(written, 2);
final setFrames = sent.where((f) => f[0] == cmdSetChannel).toList();
expect(setFrames.length, 2);
expect(setFrames[0][1], 0);
expect(setFrames[1][1], 1);
// The PSK travels with it, so the restored channel keeps the identity
// its history and settings are keyed by.
expect(setFrames[1].sublist(34, 50), _channel(1, 'wardriving', 40).psk);
});
test('an erased cached entry is never written back', () async {
c.seedCachedChannelsForTest([
_channel(0, 'Public', 10),
Channel.fromFrame(_erasedFrame(1))!,
]);
sent.clear();
final written = await c.restoreChannelsToRadio();
expect(written, 1);
expect(sent.where((f) => f[0] == cmdSetChannel).length, 1);
});
test(
'restoring with nothing cached is refused, not a silent no-op',
() async {
c.seedCachedChannelsForTest([]);
expect(await c.restoreChannelsToRadio(), -1);
expect(sent.where((f) => f[0] == cmdSetChannel), isEmpty);
},
);
});
}

@ -18,6 +18,7 @@ import 'package:meshcore_open/connector/offband_capability_advert.dart';
import 'package:meshcore_open/connector/offband_channel_notify.dart';
import 'package:meshcore_open/connector/offband_device_ui.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
@ -46,6 +47,55 @@ Uint8List deviceInfo({
return f;
}
/// A RESP_CODE_CHANNEL_INFO frame. [pskSeed] makes each channel's PSK, and so
/// its identity, distinct.
Uint8List channelInfoFrame({
required int index,
required String name,
required int pskSeed,
}) {
final frame = Uint8List(50);
frame[0] = respCodeChannelInfo;
frame[1] = index;
final nameBytes = name.codeUnits;
for (var i = 0; i < nameBytes.length && i < 31; i++) {
frame[2 + i] = nameBytes[i];
}
for (var i = 0; i < 16; i++) {
frame[34 + i] = (pskSeed + i) & 0xFF;
}
return frame;
}
/// A slot whose stored record was erased: flash reads back as 0xFF, so the
/// name decodes to replacement characters and the PSK is all-ones (#1060).
Uint8List erasedChannelInfoFrame(int index) {
final frame = Uint8List(50);
frame[0] = respCodeChannelInfo;
frame[1] = index;
for (var i = 2; i < 50; i++) {
frame[i] = 0xFF;
}
return frame;
}
/// A standalone Channel for tests that never sync a list, e.g. the capability
/// gate, which must refuse before it ever looks a slot up.
Channel testChannel(int index, {String name = 'ch', int pskSeed = 10}) =>
Channel(
index: index,
name: name,
psk: Uint8List.fromList(
List<int>.generate(16, (i) => (pskSeed + i) & 0xFF),
),
);
Future<void> settle([int turns = 25]) async {
for (var i = 0; i < turns; i++) {
await Future<void>.delayed(Duration.zero);
}
}
void main() {
late OffbandDatabase db;
late MeshCoreConnector connector;
@ -68,6 +118,26 @@ void main() {
await db.close();
});
/// Drives a full channel sync so slot indices are confirmed. The radio's
/// notify modes are only meaningful past that barrier (#1062), and since
/// #1060 the client resolves every slot to a channel identity, so a test
/// that never syncs has no identities to resolve against.
Future<void> syncChannels(
List<({int index, String name, int seed})> arrangement,
) async {
await connector.getChannels(force: true, maxChannels: arrangement.length);
for (final ch in arrangement) {
connector.handleFrameForTest(
channelInfoFrame(index: ch.index, name: ch.name, pskSeed: ch.seed),
);
await settle(2);
}
await settle();
}
Channel slot(int index) =>
connector.channels.firstWhere((c) => c.index == index);
bool sentChannelNotify() => sent.any(
(f) =>
f.length >= 2 &&
@ -81,10 +151,15 @@ void main() {
group('A1 radio channel notify', () {
test('the wire bytes are the documented ones', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
(index: 2, name: 'wardriving', seed: 40),
]);
sent.clear();
await connector.requestChannelNotify(2);
await connector.setChannelNotify(2, RadioChannelNotify.mentions);
await connector.setChannelNotify(slot(2), RadioChannelNotify.mentions);
expect(
sent,
@ -95,49 +170,179 @@ void main() {
);
});
test('a reply sets that slot, and only that slot', () {
test('a reply sets that channel, and only that channel', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
(index: 2, name: 'wardriving', seed: 40),
]);
connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x02]);
expect(connector.channelNotifyFor(1), RadioChannelNotify.mentions);
expect(connector.channelNotifyFor(0), isNull);
expect(connector.channelNotifyFor(2), isNull);
expect(connector.channelNotifyFor(slot(1)), RadioChannelNotify.mentions);
expect(connector.channelNotifyFor(slot(0)), isNull);
expect(connector.channelNotifyFor(slot(2)), isNull);
});
test('mode 0 is unset, and is distinct from Off', () {
test('mode 0 is unset, and is distinct from Off', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
]);
connector.handleFrameForTest([0xC5, 0x18, 0x00, 0x00]);
connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]);
expect(connector.channelNotifyFor(0), RadioChannelNotify.unset);
expect(connector.channelNotifyFor(1), RadioChannelNotify.off);
expect(connector.channelNotifyFor(slot(0)), RadioChannelNotify.unset);
expect(connector.channelNotifyFor(slot(1)), RadioChannelNotify.off);
});
test('a write is not shown until the radio confirms it', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await connector.setChannelNotify(3, RadioChannelNotify.off);
await syncChannels([(index: 3, name: 'wardriving', seed: 40)]);
await connector.setChannelNotify(slot(3), RadioChannelNotify.off);
expect(connector.channelNotifyFor(3), isNull);
expect(connector.channelNotifyFor(slot(3)), isNull);
connector.handleFrameForTest([0xC5, 0x19, 0x03, 0x03]);
expect(connector.channelNotifyFor(3), RadioChannelNotify.off);
expect(connector.channelNotifyFor(slot(3)), RadioChannelNotify.off);
});
test('an unknown mode byte is dropped, never guessed at', () {
test('an unknown mode byte is dropped, never guessed at', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([(index: 4, name: 'wardriving', seed: 40)]);
connector.handleFrameForTest([0xC5, 0x18, 0x04, 0x09]);
expect(connector.channelNotifyFor(4), isNull);
expect(connector.channelNotifyFor(slot(4)), isNull);
expect(parseChannelNotifyReply([0xC5, 0x18, 0x04, 0x09]), isNull);
});
test('state does not survive a change of radio', () {
test('state does not survive a change of radio', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([(index: 1, name: 'wardriving', seed: 40)]);
final wardriving = slot(1);
connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x01]);
expect(connector.channelNotifyFor(1), RadioChannelNotify.all);
expect(connector.channelNotifyFor(wardriving), RadioChannelNotify.all);
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
expect(connector.channelNotifyFor(wardriving), isNull);
});
test(
'a reply for a slot with no confirmed channel is dropped, not stored',
() async {
connector.handleFrameForTest(
deviceInfo(caps2: offbandCap2ChannelNotify),
);
await syncChannels([(index: 0, name: 'Public', seed: 10)]);
// Slot 7 was never confirmed. Storing this against slot 7 is what let
// a later occupant of that slot inherit the mode (#1060).
connector.handleFrameForTest([0xC5, 0x18, 0x07, 0x03]);
expect(connector.channels.any((c) => c.index == 7), isFalse);
expect(connector.channelNotifyFor(slot(0)), isNull);
},
);
});
// ---- A5: the mode follows the channel, not the slot (#1060) --------------
group('A5 radio notify is keyed by channel identity', () {
test('a mode read for one channel does not appear on the channel that '
'later takes its slot', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
// #wardriving sits in slot 1 and the radio reports it as Off.
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'wardriving', seed: 40),
]);
final wardriving = slot(1);
connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]);
expect(connector.channelNotifyFor(wardriving), RadioChannelNotify.off);
// A wipe and re-import puts a DIFFERENT channel in slot 1.
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
]);
final testCh = slot(1);
// The new occupant must not inherit #wardriving's Off. Before this
// fix the slot-keyed map handed it straight over, which is how a
// channel the owner had silenced started chirping again.
expect(testCh.pskHex, isNot(wardriving.pskHex));
expect(connector.channelNotifyFor(testCh), isNull);
});
test('a mode survives the channel moving to a different slot', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
expect(connector.channelNotifyFor(1), isNull);
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'wardriving', seed: 40),
]);
connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]);
// Same channel, new slot.
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
(index: 2, name: 'wardriving', seed: 40),
]);
expect(connector.channelNotifyFor(slot(2)), RadioChannelNotify.off);
expect(connector.channelNotifyFor(slot(1)), isNull);
});
test(
'a write addresses the channel current slot, not a stale one',
() async {
connector.handleFrameForTest(
deviceInfo(caps2: offbandCap2ChannelNotify),
);
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'wardriving', seed: 40),
]);
// A Channel captured while it was in slot 1, as a UI widget holds one.
final staleHandle = slot(1);
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'test', seed: 50),
(index: 2, name: 'wardriving', seed: 40),
]);
sent.clear();
await connector.setChannelNotify(staleHandle, RadioChannelNotify.off);
// Addressed to slot 2, where #wardriving actually is now.
expect(
sent,
equals([
[0xC5, 0x19, 0x02, 0x03],
]),
);
},
);
test('a write for a channel the radio does not hold is refused', () async {
connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify));
await syncChannels([
(index: 0, name: 'Public', seed: 10),
(index: 1, name: 'wardriving', seed: 40),
]);
final gone = slot(1);
// The channel is deleted on the radio.
await syncChannels([(index: 0, name: 'Public', seed: 10)]);
sent.clear();
await connector.setChannelNotify(gone, RadioChannelNotify.off);
expect(sent, isEmpty);
expect(connector.deviceUiError, isNotNull);
expect(connector.deviceUiErrorSurface, DeviceUiSurface.channelNotify);
});
});
@ -211,7 +416,7 @@ void main() {
test('without 0x80 no channel-notify frame is ever emitted', () async {
connector.handleFrameForTest(deviceInfo(caps2: 0x40));
await connector.requestChannelNotify(0);
await connector.setChannelNotify(0, RadioChannelNotify.off);
await connector.setChannelNotify(testChannel(0), RadioChannelNotify.off);
expect(connector.supportsChannelNotify, isFalse);
expect(sentChannelNotify(), isFalse);
@ -450,7 +655,12 @@ void main() {
// hide a genuinely refused write and wrongly mark the radio as predating
// the advert.
connector.handleFrameForTest(deviceInfo(caps2: 0x80));
await connector.setChannelNotify(0, RadioChannelNotify.off);
// The channel must really exist, so the write really goes out: a write
// refused for an unresolvable slot would also set deviceUiError and
// pass this test for the wrong reason.
await syncChannels([(index: 0, name: 'Public', seed: 10)]);
await connector.setChannelNotify(slot(0), RadioChannelNotify.off);
expect(sentChannelNotify(), isTrue);
connector.handleFrameForTest(advertUnsupported());
expect(

@ -128,6 +128,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -477,6 +482,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -826,6 +836,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -1175,6 +1190,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -1524,6 +1544,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -1873,6 +1898,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -2222,6 +2252,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -2571,6 +2606,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -2920,6 +2960,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -3269,6 +3314,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -3618,6 +3668,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -3967,6 +4022,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -4316,6 +4376,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -4665,6 +4730,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -5014,6 +5084,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -5363,6 +5438,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",
@ -5712,6 +5792,11 @@
"contact_cliConsole",
"channels_unconfirmedSlots",
"channels_retrySync",
"channels_erasedSlots",
"channels_restoreToRadio",
"channels_restoreToRadioConfirm",
"channels_restoreToRadioDone",
"channels_restoreToRadioFailed",
"channels_slotIdentityChanged",
"common_dismiss",
"channels_notifications",

Loading…
Cancel
Save

Powered by TurnKey Linux.