commit
7734d681e8
@ -0,0 +1,267 @@
|
||||
package com.meshcore.meshcore_open
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.ApplicationExitInfo
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
|
||||
/**
|
||||
* Reads the system's record of why this app's processes died, so an ANR that
|
||||
* killed the process can be reported on the next launch (#906).
|
||||
*
|
||||
* `ActivityManager.getHistoricalProcessExitReasons` is API 30; `minSdk` here is
|
||||
* 24, so everything below reports itself unsupported rather than failing. The
|
||||
* query and the trace reads run on a background executor: #334 is the leading
|
||||
* hypothesis for these ANRs, so a collector that blocked the main thread would
|
||||
* be adding to the problem it exists to measure.
|
||||
*/
|
||||
class AppExitInfoFunctions(
|
||||
private val activity: FlutterActivity,
|
||||
) {
|
||||
private companion object {
|
||||
/** Bound on the query. The system keeps a ring buffer of unspecified size. */
|
||||
const val maxRecords = 15
|
||||
|
||||
/** Per-trace read cap, so one pathological trace can't be unbounded. */
|
||||
const val maxTraceBytes = 256 * 1024
|
||||
}
|
||||
|
||||
private val channelName = "meshcore_open/app_exit_info"
|
||||
|
||||
private val activityManager by lazy {
|
||||
activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
}
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val ioExecutor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
|
||||
@Volatile private var disposed = false
|
||||
|
||||
fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
|
||||
.setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"getExitRecords" -> handleGetExitRecords(result)
|
||||
"forceMainThreadBlock" -> handleForceMainThreadBlock(call, result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
disposed = true
|
||||
// shutdown(), NOT shutdownNow(): an in-flight read is holding a
|
||||
// MethodChannel.Result, and interrupting it would leave that Result
|
||||
// neither succeeded nor errored, so the Dart future would never
|
||||
// complete. Letting the task finish is cheap; a hung future is not.
|
||||
ioExecutor.shutdown()
|
||||
}
|
||||
|
||||
private fun handleGetExitRecords(result: MethodChannel.Result) {
|
||||
if (disposed) {
|
||||
result.error("exit_info_disposed", "activity is being destroyed", null)
|
||||
return
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
result.success(
|
||||
mapOf(
|
||||
"supported" to false,
|
||||
"unsupportedReason" to "api_below_30",
|
||||
"sdkInt" to Build.VERSION.SDK_INT,
|
||||
"records" to emptyList<Map<String, Any?>>(),
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
val records = collectExitRecords()
|
||||
mainHandler.post {
|
||||
result.success(
|
||||
mapOf(
|
||||
"supported" to true,
|
||||
"sdkInt" to Build.VERSION.SDK_INT,
|
||||
"records" to records,
|
||||
),
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
// Surfaced, never swallowed: Dart logs this and leaves the
|
||||
// watermark untouched so the next launch retries.
|
||||
mainHandler.post {
|
||||
result.error(
|
||||
"exit_info_query_failed",
|
||||
error.message ?: error.javaClass.simpleName,
|
||||
error.stackTraceToString().take(2000),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: RejectedExecutionException) {
|
||||
// The executor shut down between the disposed check and here. Reply
|
||||
// rather than returning silently, so the Dart future completes.
|
||||
result.error("exit_info_rejected", error.message ?: "executor shut down", null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* API 30+ only, isolated in its own method so the verifier never has to
|
||||
* resolve [ApplicationExitInfo] on a device that cannot run this path.
|
||||
*/
|
||||
private fun collectExitRecords(): List<Map<String, Any?>> {
|
||||
// null package name means this app's own records, which needs no permission.
|
||||
val infos = activityManager.getHistoricalProcessExitReasons(null, 0, maxRecords)
|
||||
return infos.map { info -> describe(info) }
|
||||
}
|
||||
|
||||
private fun describe(info: ApplicationExitInfo): Map<String, Any?> {
|
||||
val record = mutableMapOf<String, Any?>(
|
||||
"reason" to info.reason,
|
||||
"reasonName" to reasonName(info.reason),
|
||||
"description" to info.description,
|
||||
"timestampMs" to info.timestamp,
|
||||
"pid" to info.pid,
|
||||
"processName" to info.processName,
|
||||
"importance" to info.importance,
|
||||
// Documented as kB, and 0 when the system never sampled the process.
|
||||
"pssKb" to info.pss,
|
||||
"rssKb" to info.rss,
|
||||
"status" to info.status,
|
||||
)
|
||||
|
||||
readTrace(info, record)
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* A text ANR trace is printable ASCII; a native tombstone protobuf is not.
|
||||
*
|
||||
* Content, not reason code, decides whether the bytes are usable. Gating on
|
||||
* [ApplicationExitInfo.REASON_CRASH_NATIVE] instead would lose a real text
|
||||
* trace, because AOSP says a trace from an earlier ANR stays attached to the
|
||||
* record even when the process later died for a different reason.
|
||||
*/
|
||||
private fun looksLikeText(bytes: ByteArray): Boolean {
|
||||
val sample = minOf(bytes.size, 256)
|
||||
if (sample == 0) return false
|
||||
var printable = 0
|
||||
for (i in 0 until sample) {
|
||||
val b = bytes[i].toInt() and 0xFF
|
||||
if (b == 0x09 || b == 0x0A || b == 0x0D || (b in 0x20..0x7E)) printable++
|
||||
}
|
||||
return printable * 10 >= sample * 9
|
||||
}
|
||||
|
||||
/**
|
||||
* A trace is NOT guaranteed, even for [ApplicationExitInfo.REASON_ANR]: the
|
||||
* system keeps traces in a circular buffer shared across all applications,
|
||||
* so another app's crash can evict ours. A trace can also ride on a record
|
||||
* whose reason is something else, when the process survived an ANR and died
|
||||
* later for another reason. So this attempts the read on every record and
|
||||
* treats absence as an ordinary outcome, not an error.
|
||||
*
|
||||
* `getTraceInputStream()` is declared `throws IOException`, so the call
|
||||
* itself is inside the try, not only the reads on the stream it returns.
|
||||
*/
|
||||
private fun readTrace(info: ApplicationExitInfo, record: MutableMap<String, Any?>) {
|
||||
try {
|
||||
val stream = info.traceInputStream
|
||||
if (stream == null) {
|
||||
record["traceUnavailable"] = "evicted_or_absent"
|
||||
return
|
||||
}
|
||||
stream.use { open ->
|
||||
// Read loop rather than readNBytes: that one is API 33, and this
|
||||
// path has to work from API 30 up.
|
||||
val sink = ByteArrayOutputStream()
|
||||
val chunk = ByteArray(8192)
|
||||
while (sink.size() < maxTraceBytes) {
|
||||
val read = open.read(chunk, 0, minOf(chunk.size, maxTraceBytes - sink.size()))
|
||||
if (read <= 0) break
|
||||
sink.write(chunk, 0, read)
|
||||
}
|
||||
if (sink.size() == 0) {
|
||||
record["traceUnavailable"] = "empty_stream"
|
||||
return
|
||||
}
|
||||
val bytes = sink.toByteArray()
|
||||
if (!looksLikeText(bytes)) {
|
||||
// Almost certainly a native tombstone protobuf (API 31+).
|
||||
// Recorded rather than written, because concatenating binary
|
||||
// into a text log would corrupt it (#906).
|
||||
record["traceUnavailable"] = "binary_tombstone_not_text"
|
||||
return
|
||||
}
|
||||
record["traceBytes"] = bytes
|
||||
if (bytes.size >= maxTraceBytes) {
|
||||
record["traceTruncated"] = true
|
||||
}
|
||||
}
|
||||
} catch (error: IOException) {
|
||||
record["traceUnavailable"] = "io_error: ${error.message ?: "IOException"}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun reasonName(reason: Int): String = when (reason) {
|
||||
ApplicationExitInfo.REASON_ANR -> "ANR"
|
||||
ApplicationExitInfo.REASON_CRASH -> "CRASH"
|
||||
ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
|
||||
ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
|
||||
ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
|
||||
ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
|
||||
ApplicationExitInfo.REASON_FREEZER -> "FREEZER"
|
||||
ApplicationExitInfo.REASON_INITIALIZATION_FAILURE -> "INITIALIZATION_FAILURE"
|
||||
ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY"
|
||||
ApplicationExitInfo.REASON_OTHER -> "OTHER"
|
||||
ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE -> "PACKAGE_STATE_CHANGE"
|
||||
ApplicationExitInfo.REASON_PACKAGE_UPDATED -> "PACKAGE_UPDATED"
|
||||
ApplicationExitInfo.REASON_PERMISSION_CHANGE -> "PERMISSION_CHANGE"
|
||||
ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
|
||||
ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
|
||||
ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
|
||||
else -> "UNKNOWN"
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only: hangs the main thread so the system raises a real ANR, which is
|
||||
* the only way to produce an [ApplicationExitInfo.REASON_ANR] record. No adb
|
||||
* command induces one. Unreachable in a shipped build, because the only
|
||||
* caller is compiled out unless `OFFBAND_ANR_TEST` is defined (#911).
|
||||
*
|
||||
* Replies before blocking so the Dart call completes; the block then runs on
|
||||
* the next turn of the main looper.
|
||||
*/
|
||||
private fun handleForceMainThreadBlock(call: MethodCall, result: MethodChannel.Result) {
|
||||
val millis = (call.argument<Int>("millis") ?: 20000).coerceIn(1000, 120000)
|
||||
result.success(millis)
|
||||
mainHandler.post {
|
||||
// Sleeps to a deadline and swallows interrupts rather than a single
|
||||
// Thread.sleep. An interrupt cutting the block short would mean no
|
||||
// ANR, no record, and a wasted trip to the hardware. Looping on
|
||||
// short sleeps keeps the duration guaranteed without the CPU burn
|
||||
// (and thermal throttling) of a busy-wait.
|
||||
val deadline = System.nanoTime() + millis * 1_000_000L
|
||||
while (true) {
|
||||
val remainingMs = (deadline - System.nanoTime()) / 1_000_000L
|
||||
if (remainingMs <= 0) break
|
||||
try {
|
||||
Thread.sleep(minOf(remainingMs, 250L))
|
||||
} catch (_: InterruptedException) {
|
||||
// Deliberately ignored; the deadline is what ends this.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
🚀 **Offband Meshcore 1.7.0 is out.** A foundations release: faster storage, every radio keeps its own data, and a contact list that matches your radio. Over 100 changes since 1.6.0.
|
||||
|
||||
⚠️ **Read this before updating: it's a one-way upgrade.** On first launch, 1.7.0 converts your message history to a new database format. After that, **older versions of the app can't open it**, so there's no going back to 1.6.0. Your messages carry over. The old copy is kept 30 days and then cleared automatically, so the database is bigger for a while. Want the space back now? **App Settings > Storage > Clear Stale History Now** (it asks first and never touches your messages).
|
||||
|
||||
💾 **Storage that keeps up.** One row per message instead of one giant blob per conversation, so a new message costs the same at 50,000 messages of history as at 50, and the heavy lifting is off the UI thread.
|
||||
|
||||
📻 **Every radio keeps its own data.** Discovered nodes, blocked contacts, channel notification modes, path history, and delivery records all belong to the radio they came from. A brand-new radio no longer shows up pre-blocked, and switching radios no longer flashes the last radio's history.
|
||||
|
||||
👥 **Contacts that match your radio.** No more phantom contacts piling up from adverts your radio rejected; a contact your radio actually stores still shows up on its own. And **custom names**: rename any contact, keep seeing what the node calls itself underneath, and your label never goes over the air or into exports.
|
||||
|
||||
🗺️ **Region scoping.** Discover a repeater's regions and scope a channel to one, so its messages flood only there. Needs MeshCore companion 1.16+ or current Offband firmware.
|
||||
|
||||
⚙️ **Settings, reorganized.** Location gets its own category (and is the one home for GPS), Buzzer and tones moves to Message Settings, and import/export plus GPX live under Actions. Badge tones, custom tunes, screen settings, and GPS power save are built in and will appear once the matching Offband firmware ships.
|
||||
|
||||
🖥️ **CLI for stock 1.18 companions.** A Device CLI console for your radio, remote CLI to another companion from the chat menu, and a per-contact Remote CLI permission toggle. CLI stays out of your chat.
|
||||
|
||||
📶 **Steadier Bluetooth.** Auto-reconnect now gives up after 5 tries or 3 minutes, **Stop** ends it right away, and a connect you start always wins. Plus a fix for a race that could leave the composer unusable, and a Windows crash on close.
|
||||
|
||||
🔧 **Fixes.** Messages with 2- or 3-byte path hashes show the right hop count (no more 13 hops reading as 39).
|
||||
|
||||
**📥 Get it on Google Play:** search **Offband MeshCore**, or https://play.google.com/store/apps/details?id=app.offband.meshcore (rolling out in stages, so it may take a few days to reach you)
|
||||
💻 **Desktop (Windows / Linux) and Android APK:** https://github.com/OffbandMesh/meshcore-client/releases/tag/v1.7.0
|
||||
🌐 **Or run it in your browser:** https://offband.app
|
||||
|
||||
💚 Thanks as always to the **OKIMesh community** (https://okimesh.org/). Offband is open source and always will be; if you'd like to help keep it going: https://offband.org/donate
|
||||
@ -0,0 +1,52 @@
|
||||
# Feature #812 region scoping: OUTCOMES
|
||||
|
||||
Status: shipped and verified on hardware (D1 PASSED, 2026-10-15). Client-only, no firmware change.
|
||||
|
||||
## What shipped
|
||||
A client capability at parity with stock MeshCore, built on current stock-parity firmware:
|
||||
|
||||
- **Discover Regions** (Epic #814): from a reachable repeater, ask which flood regions it carries and present the list.
|
||||
- **Channel Set Region Scope** (Epic #815): a per-channel region selection that makes a channel's outgoing messages ride that region's flood scope, orchestrated per send (set the flood-scope key before each channel send, clear after).
|
||||
- **Protocol + transport** (Epic #813): the v8 companion frames and the region transport-key derivation that both of the above rely on.
|
||||
|
||||
### Epics / PRs
|
||||
| Epic | Scope | PR |
|
||||
|---|---|---|
|
||||
| #813 | protocol + transport (anon-request discovery, flood-scope CMD 54/63/64, name-derived keys, version gate) | #824 |
|
||||
| #814 | Discover Regions service + UI | #828 |
|
||||
| #815 | channel Set Region Scope (store + picker + per-send scoping) | #833 |
|
||||
| #816 | integration testing + this OUTCOMES.md | (this PR) |
|
||||
|
||||
## Wire contract (verified in firmware source)
|
||||
- Region transport key = first 16 bytes of `SHA256("#"+name)` (`RegionMap.getTransportKeysFor` / `TransportKeyStore`). On-air code = `HMAC(key, type+payload)[:2]` little-endian, reserving `0x0000`/`0xFFFF`.
|
||||
- Flood-scope: `CMD_SET_FLOOD_SCOPE_KEY` 54 (sub-0 set 16B key / sub-0 no-key clear / sub-1 unscoped), `CMD_SET_DEFAULT_FLOOD_SCOPE` 63, `CMD_GET_DEFAULT_FLOOD_SCOPE` 64, `RESP_CODE_DEFAULT_FLOOD_SCOPE` 28.
|
||||
- Discovery is an ANON request: `CMD_SEND_ANON_REQ` 57 with payload `[ANON_REQ_TYPE_REGIONS 0x01][reply_path_len][reply_path]`. The firmware's `sendAnonReq` prepends its own 4-byte tag and returns it in `RESP_CODE_SENT`; the repeater echoes it in the `PUSH_CODE_BINARY_RESPONSE` 0x8C reply `[0x8C][0][tag:4][clock:4][CSV names]`. The reply routes back along the client-supplied `reply_path`, used as-is (`Mesh.cpp:176-177`).
|
||||
- Version gate: `firmwareSupportsRegionScope` is `FIRMWARE_VER_CODE >= 13`.
|
||||
|
||||
## D1 hardware session (PASSED)
|
||||
On a real radio (region-capable firmware, direct repeater), end to end:
|
||||
1. Discover Regions returned the repeater's flood-allowed region list.
|
||||
2. Set Region Scope persisted the chosen region on a channel.
|
||||
3. A send on that channel rode the chosen region's flood scope.
|
||||
4. The feature is hidden below the firmware gate.
|
||||
|
||||
## Issues found in D1 and fixed (all on epic/815-channel-scope)
|
||||
D1 did its job; several defects only surfaced on real hardware.
|
||||
|
||||
- **Repeater picker unusable** (#830): the picker was an unsorted, unsearchable dropdown. Now alpha-sorted and searchable.
|
||||
- **Path-aware picker** (#830, owner Option 1): the picker lists only repeaters with a usable route, with a note explaining that; a search surfaces path-less matches greyed out and non-selectable, labeled "No stored path".
|
||||
- **Direct repeaters wrongly excluded** (#830): `hasPath` required a non-empty path, but a direct (0-hop) repeater has `pathLength 0` and an empty path. Direct is reachable (best case); fixed to `pathLength >= 0`.
|
||||
- **Discovery returned no reply** (#836): two wire-format bugs. The client double-counted the anon-request tag (the firmware prepends its own), so the repeater read the request as a login and never answered; and the reply was correlated on a client-invented tag instead of the firmware tag the 0x8C echoes. Fixed to match the real contract.
|
||||
- **Zero-hop reply cap** (#836): the reply was pinned to zero-hop, so only an adjacent repeater could answer. Now the request carries the repeater contact's stored path as the reply path (multi-hop), and the discovery timeout uses the firmware's own `est_timeout` estimate rather than a fixed value.
|
||||
- **First-attempt LoRa drop** (#836, owner Option A): a single anon-request round-trip can drop over LoRa. Discovery now makes one automatic retry before reporting no response.
|
||||
|
||||
## Region model finding (firmware/repeater, not client)
|
||||
A community discussion raised that `region def` on a repeater stores and displays regions as a hierarchy, and a region can only have one parent, which breaks tri-state-border configs (e.g. putting `oki` under both `us-midwest` and `us-southeast`). Verified in firmware: `RegionMap::findMatch` iterates regions as a **flat whitelist** at forward time (flood allow/deny flag plus a transport-code match) and never consults `parent_id`. So the hierarchy is cosmetic; the re-parenting on `region def` is a repeater-side config/doc UX flaw, not a routing behavior. Our client scopes a channel by the flat tag name and discovers the flat list of flood-allowed names, so it is already aligned with how the firmware routes and is unaffected by the hierarchy issue.
|
||||
|
||||
## Known limits / follow-ups
|
||||
- The multi-hop reply uses the repeater contact's **stored** path. Stored paths go stale when the companion moves, so a repeater can occasionally not answer until the path refreshes; this surfaces as a plain timeout (plus the one auto-retry), never a silent drop. The repeater list is deliberately not filtered by hop count for the same reason.
|
||||
- `$`-prefixed private regions are not name-derivable (keystore-only) and are out of scope.
|
||||
- A true per-channel firmware scope (firmware TODO) would remove the client-orchestrated per-send dance; sequenced separately by the owner.
|
||||
- Android was not built for D1 (release signing needs the keystore in the worktree); the owner tested on Windows, and the same client code runs on both.
|
||||
|
||||
Agent: EmeraldFalcon (session 6966cd3a)
|
||||
@ -0,0 +1,132 @@
|
||||
# Feature PLAN: region scoping (client): Discover Regions + channel Set Region Scope
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#812](https://github.com/OffbandMesh/meshcore-client/issues/812) · Citadel `meshcore-open-e0l` |
|
||||
| **Serves** | No parent Initiative; a standalone Feature. Pulls "Set Region Scope" out of the #651 channel-menu parity bundle. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-07 |
|
||||
|
||||
## At a glance
|
||||
- **What:** a **Discover Regions** action that asks a reachable repeater which regions it floods, and a per-channel **Set Region Scope** action (stock channel-menu parity) that makes that channel's outgoing messages ride the chosen region's flood scope.
|
||||
- **Why:** stock MeshCore has both; Offband has neither. Owner-directed 2026-10-06.
|
||||
- **How:** entirely client-side against current stock-parity firmware. No firmware change. Four Epics in order: A protocol/transport, B Discover Regions, C channel Set Region Scope, D hardware integration test.
|
||||
- **Done when:** the owner can discover regions from his repeater, set a channel's region, send on that channel scoped to the region, and confirm on hardware; the feature is hidden on firmware that doesn't support it.
|
||||
|
||||
## 1. Diagnosis
|
||||
Verified against firmware `C:\Dev\meshcore-firmware` and client `dev`, 2026-10-06/07. Full cited contract on #817.
|
||||
|
||||
| # | Finding | Evidence |
|
||||
|---|---|---|
|
||||
| 1 | Client has no region capability; only raw repeater-CLI passthrough | `repeater_cli_screen.dart` region commands; no region model/UI in `lib/` |
|
||||
| 2 | **Discover Regions = an ANON request**, not control-data | `ANON_REQ_TYPE_REGIONS 0x01` via `CMD_SEND_ANON_REQ 57`; repeater `handleAnonRegionsReq` replies region names; reply to app as `PUSH_CODE_BINARY_RESPONSE 0x8C` `[0x8C,0,tag4,clock4,CSV names]` `[simple_repeater MyMesh.cpp:58,150-166,599; companion MyMesh.cpp:3114-3141,1201-1211; RegionMap.cpp:318-346]` |
|
||||
| 3 | Region names are public; key is derivable | transport key = first 16B of `SHA256("#"+name)`; `$`-prefixed private regions are not name-derivable `[RegionMap.cpp:173-188; TransportKeyStore.cpp:44-47; TransportKeyStore.h:8]` |
|
||||
| 4 | Scope-set is exposed over the companion | `CMD_SET_FLOOD_SCOPE_KEY 54` (sub-0 set 16B key / sub-1 unscoped), `CMD_SET_DEFAULT_FLOOD_SCOPE 63`, `CMD_GET_DEFAULT_FLOOD_SCOPE 64`, `RESP 28` `[companion MyMesh.cpp:3512-3547]` |
|
||||
| 5 | No per-channel scope in firmware | `companion MyMesh.cpp:896 "// TODO: have per-channel send_scope"`; send applies one `send_scope` override or the node default |
|
||||
| 6 | Client implements none of it; v8+ | highest client command 61; `appProtocolVersion 4`; client already gates by `firmwareVerCode` (`firmwareSupportsPktHash` >= 22) `[meshcore_protocol.dart]` |
|
||||
|
||||
## 2. Scope
|
||||
**In:**
|
||||
- Protocol: anon regions request + 0x8C reply parse; flood-scope cmd 54/63/64 + RESP 28; name->key (SHA256) + on-air code (HMAC); firmware-version gate.
|
||||
- Discover Regions: query a chosen repeater, parse the CSV region names, present a list.
|
||||
- Channel scope: per-channel region stored client-side; channel-menu "Set Region Scope"; and the **client-orchestrated per-send** apply (set `send_scope` via cmd 54 sub-0 with the channel's SHA256 key immediately before each channel send, reset after).
|
||||
- Optional node default scope via cmd 63/64.
|
||||
|
||||
**Out:**
|
||||
- Firmware changes of any kind (per-channel firmware scope, finding 5, is a firmware TODO the owner sequences separately).
|
||||
- `$`-prefixed private regions (keys not name-derivable).
|
||||
- RF/IATA region settings (#503) and geofencing: different concern.
|
||||
- Administering a repeater's region map (that is the existing repeater CLI).
|
||||
|
||||
## 3. Epics
|
||||
Each Epic ends with a verification task and gets one PR. The first task reproduces the diagnosis as a failing test.
|
||||
|
||||
### Epic A: protocol + transport layer (#813)
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **A1 · Region model + key derivation:** NEW `lib/models/region.dart`, NEW `lib/helpers/region_key.dart` (transportKeyForName = first 16B of SHA256("#"+name); on-air code HMAC). Unit tests incl. a known vector and wildcard. | 2 |
|
||||
| **A2 · Frames + version gate:** `lib/connector/meshcore_protocol.dart` constants (cmd 54/63/64, resp 28, push 0x8C), builders (anon regions req type 0x01, set-scope-key, default-scope set/get), parsers (resp 28, 0x8C CSV), `firmwareSupportsRegionScope(verCode)`. Unit tests. | 3 |
|
||||
| **A3 · Connector wiring:** `lib/connector/meshcore_connector.dart`: `discoverRegions()`, set/clear channel send scope, set/get default scope, 0x8C + resp 28 handling (tag-matched), exposed via stream/callback. | 3 |
|
||||
| **A4 · Epic verification:** protocol unit tests pass; frames round-trip against a real radio on benign paths. | 1 |
|
||||
|
||||
### Epic B: Discover Regions (#814)
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **B1 · Discovery service:** NEW `lib/services/region_discovery_service.dart`: target a repeater, send, collect/parse/dedupe 0x8C replies; timeout, empty, parse-error all surfaced. Unit tests with a fake connector. | 3 |
|
||||
| **B2 · Discover Regions UI:** list screen/dialog (source node, SNR), entry point, l10n. | 3 |
|
||||
| **B3 · Epic verification:** discover against rpt-01 returns its regions; empty/timeout surfaces. | 1 |
|
||||
|
||||
### Epic C: channel Set Region Scope (#815)
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **C1 · Per-channel scope store:** NEW `lib/storage/channel_region_scope_store.dart` (device-key scoped, channel->region) + model + tests. | 3 |
|
||||
| **C2 · Channel-menu action + picker:** `lib/screens/channel_chat_screen.dart` overflow item "Set Region Scope" + picker (sourced from B), writes the store, l10n. | 3 |
|
||||
| **C3 · Send-path scoping:** `lib/connector/meshcore_connector.dart` channel send: apply send_scope (cmd 54 sub-0, SHA256) before send, reset after; optional node default (cmd 63). | 3 |
|
||||
| **C4 · Epic verification:** a scoped channel send applies the right key on the wire. | 1 |
|
||||
|
||||
### Epic D: integration testing (#816)
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **D1 · Owner hardware session:** discover from rpt-01 -> set a channel's region -> send -> confirm flood-scoped; verify the feature is hidden on non-supporting firmware. | 2 |
|
||||
| **D2 · OUTCOMES.md** | 1 |
|
||||
|
||||
## 4. Order and dependencies
|
||||
- A, B, C, D in order; each Epic's verification blocks the next (wired in Citadel).
|
||||
- **File overlap:** only `lib/connector/meshcore_connector.dart` is shared (A3 and C3) -> Epic C depends on Epic A. No other cross-task file collisions.
|
||||
- Merges held to the end of the Feature, stacked, so each Epic branch is on the one before.
|
||||
- Fail-closed branches (standards#677): firmware ver < gate -> feature hidden, never send region frames; discovery empty/malformed -> surface, never show empty as success; discovery timeout -> surface + retry, never hang; channel scoped but firmware unsupported -> block the send with a clear error, never send unscoped; cmd 54 ERR before a send -> abort + surface. No fail-open branches.
|
||||
|
||||
## 5. Grants and authorization
|
||||
| Term | Proposed | Why |
|
||||
|---|---|---|
|
||||
| **What merging this plan authorizes** | Running Epics A to D in order without stopping between them: code, tests, builds, one PR per Epic, stacked. | Canon: once the plan grant is minted, run the whole chain. |
|
||||
| **Merges** | Held to the end of the Feature, in order A, B, C, D, after the owner's D1 hardware session. | Canon. |
|
||||
| **Epic verification** | Command mode: the merge hook runs `flutter test` on each PR's exact commit; the owner's D1 hardware session is the Feature-level gate before the end merges. | Minimizes owner per-PR steps; the real on-air proof is D1. |
|
||||
| **Owner steps during the run** | None until D1 (the hardware session, one sitting). | Canon: owner steps are one message, at the end. |
|
||||
| **Stops** | A new decision; a firmware reply I can't cite; a fault I can't fix. | |
|
||||
| **Flash** | None (client-only; owner tests via a build, the session flashes nothing). | |
|
||||
|
||||
```grant-terms
|
||||
{
|
||||
"epic_chain": [813, 814, 815, 816],
|
||||
"chain": true,
|
||||
"verification": { "mode": "command", "command": "flutter test" },
|
||||
"merge": { "budget": 4, "basis": "One PR per Epic: #813 protocol, #814 Discover Regions, #815 channel Set Region Scope, #816 integration test + OUTCOMES.md." },
|
||||
"flash": null,
|
||||
"reset": null,
|
||||
"expires_after_hours": 168
|
||||
}
|
||||
```
|
||||
`expires_after_hours` basis: ~32 points across four Epics at interactive pace around the owner's day job; 168h is the maximum.
|
||||
|
||||
## 6. Verification
|
||||
- **Named commands** on every Epic PR: `flutter analyze --fatal-infos --fatal-warnings`, `dart format --set-exit-if-changed`, the em-dash guard, `flutter test`.
|
||||
- **Acceptance:** key derivation matches a firmware vector; discovery parses a real repeater's region CSV; a scoped channel send puts the right transport key on the wire; the feature is hidden on firmware below the gate; every surfaced error is tested present-on-failure and absent-when-ideal (#748).
|
||||
- **D1 hardware session** proves discover -> scope -> send end to end; the owner signs off.
|
||||
|
||||
## 7. Done when
|
||||
- Discover Regions lists the owner's repeater's regions over BLE/USB.
|
||||
- A channel can be scoped to a discovered region; its sends ride that region's flood scope, confirmed on hardware.
|
||||
- The feature is hidden/disabled on firmware that doesn't support it.
|
||||
- `OUTCOMES.md` is approved.
|
||||
|
||||
## 8. Your choices
|
||||
| # | Question | Option A | Option B | Rec. | Your choice |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Epic verification mode | Command (`flutter test` per PR; D1 is the on-air gate) | Owner `dw-approve verify` per Epic PR | A (fewer steps for you; D1 is the real proof) | |
|
||||
| 2 | Node default scope (cmd 63) | Include as an option in C | Channels only, skip default | A (cheap, matches firmware) | |
|
||||
|
||||
## Decisions
|
||||
| Date | Decision |
|
||||
|---|---|
|
||||
| 2026-10-06 | Build region scoping client-side; stock parity: Discover Regions + channel Set Region Scope. |
|
||||
| 2026-10-07 | Diagnosis (#817) accepted: discovery = anon request; scope via flood-scope commands; key = SHA256("#"+name). |
|
||||
| 2026-10-07 | Channel scope is client-orchestrated per-send (cmd 54 before each channel send): the only path at parity with stock firmware until stock exposes per-channel scope. |
|
||||
|
||||
## Alternatives considered but not chosen
|
||||
- **Control-data (PAYLOAD_TYPE_CONTROL) for discovery:** that is node discovery (`CTL_TYPE_NODE_DISCOVER 0x80/0x90`), not regions; regions use the anon-request path.
|
||||
- **Per-channel firmware scope:** firmware TODO (finding 5); would be firmware work the owner sequences, not this client Feature.
|
||||
- **Reading the stock client (Liam's) source for the discovery format:** unavailable; the firmware is the authoritative contract and fully specifies it.
|
||||
|
||||
When this plan merges, each Task gets a GitHub issue and a Citadel task, per canon.
|
||||
@ -0,0 +1,193 @@
|
||||
# Feature PLAN: radio-profile isolation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#853](https://github.com/OffbandMesh/meshcore-client/issues/853) · Citadel task minted on merge |
|
||||
| **Serves** | No parent Initiative; a standalone Feature. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-20 |
|
||||
|
||||
## At a glance
|
||||
|
||||
- **What:** every piece of client state that belongs to a specific radio is scoped to that radio, and every surface that stays global is global **on the record** rather than by accident.
|
||||
- **Why now:** the owner runs twelve radios through one client. Eleven stores already scope correctly, so what is left are leftovers, and leftovers rot: #754 and #471 sat written-but-unmerged for four days because this Feature had no plan, so no chain could run them.
|
||||
- **How:** a harness that makes the verdict mechanical, then one consolidated migration for the three remaining global surfaces, then the two smaller jobs, then integration testing.
|
||||
- **Done when:** a test fails if any persistence surface lacks a declared scoping verdict, and on hardware radio A's data never appears while radio B is connected, across a switch and a restart.
|
||||
|
||||
## 1. Diagnosis
|
||||
|
||||
Verified against `dev` at `b59bc728`, which is after tonight's #917 storage rewrite and after #754 and #471 landed. The audit in #853's body was taken at `a69cb998` and parts of it have moved since; the rows below supersede it.
|
||||
|
||||
| # | Finding | Evidence | Effect |
|
||||
|---|---|---|---|
|
||||
| 1 | Twelve stores already scope by the connected radio's key prefix and are correct | `channel_message_store`, `message_store`, `channel_store`, `channel_order_store`, `channel_region_scope_store`, `channel_settings_store`, `contact_store`, `contact_settings_store`, `contact_group_store`, `community_store`, `unread_store`, `block_store` all read `publicKeyHex` | The mechanism works. This Feature closes leftovers, it does not redesign |
|
||||
| 2 | `contact_discovery_store` was the last store-level hole and is now fixed | #754, merged `a331075a` | One hole closed, and the pattern it used (orphan the untagged legacy blob, let it self-heal) is the precedent for choice 1 below |
|
||||
| 3 | `path_history_<contactPubKey>` is keyed by contact only, so a learned mesh route bleeds between any two radios that share a contact | `storage_service.dart:51`, `path_history_service.dart:360,411,472` | #854. A route learned by a 1 W handheld gets applied to a repeater, and the reverse |
|
||||
| 4 | `path_history_` is also unbounded in SharedPreferences: **2,041 keys, 3,652,667 bytes, 86% of a 4.23 MB prefs file**, while `PathHistoryService` caches only 50 | measured on the owner's live prefs, 2026-10-19 | #924. And since every prefs write re-encodes the whole file (#923, 49.4 ms on Windows), this one store makes every unrelated settings write about seven times slower |
|
||||
| 5 | `delivery_observations` is one global list feeding the ACK-timeout ML model, so one radio's RF timing trains another radio's predictions | `storage_service.dart:166`, `timeout_prediction_service.dart:46,92`; 3,091 bytes, 14 entries on the owner's install | #856. Silent accuracy loss rather than a visible failure, which is why nobody reported it |
|
||||
| 6 | `pending_messages` is **dead code**: `loadPendingMessages`, `savePendingMessages` and `clearPendingMessages` have no callers anywhere in `lib/` or `test/`, and the key is absent from the owner's live prefs | `grep -rn "PendingMessages\|pending_messages" lib/ test/` returns only the three definitions; the `_pendingMessages` field at `message_retry_service.dart:547` is an unrelated in-memory list | #855 does not need scoping. It needs deleting |
|
||||
| 7 | The scope key is set from the SELF_INFO handshake, so a read issued before it lands uses the **previous** radio's prefix | #158, confirmed in source at `meshcore_connector.dart` and `channels_screen.dart`; desktop-only, does not reproduce on Android | A different defect class from rows 3 to 6: these stores are scoped correctly and still bleed, through timing |
|
||||
| 8 | #190's named root cause is already addressed, yet #190 is still open as an in-progress epic | #190 blames slot-index keying with no PSK binding; `channel_message_store._storageKey()` now resolves PSK first and logs loudly on the index fallback (#194), and #472 closed the cross-radio case | Needs a **verdict**, not an assumption. Either it no longer reproduces, or what remains is narrower than its body says |
|
||||
| 9 | Three surfaces are global **on purpose** and must not be "fixed" | `client_id_store` (`client_install_id`, the app install identity); `repeater_passwords` and `repeater_auto_clock_sync_after_login` (keyed per repeater **node**, not per connecting radio); theme, language, units, map prefs | Without a recorded verdict a future audit re-opens these as holes, which is exactly how time gets wasted |
|
||||
| 10 | Nothing makes any of this checkable | #853's acceptance says the Feature closes when "every store has a verified scoping verdict", and the only way to check that today is to re-read the audit by hand | A new global key can land tomorrow and nothing notices. Same lesson as #927: a prose guard does not gate |
|
||||
|
||||
**Root cause of the *pattern*, as distinct from the individual bugs:** there is no mechanical statement of what each surface's scoping is meant to be, so correctness lives in an issue body and decays.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
**In:**
|
||||
- A machine-checkable scoping verdict for every persistence surface, which is #853's acceptance bar made executable.
|
||||
- #854 path history per radio, and out of SharedPreferences, which also resolves #924.
|
||||
- #855 dead `pending_messages` API removed.
|
||||
- #856 delivery observations per radio.
|
||||
- #507 Settings to Blocked per-radio view, plus its T1000e hardware validation.
|
||||
- #158 the stale-scope read window, and a verdict on #190.
|
||||
- Recorded global-on-purpose verdicts for the surfaces in diagnosis row 9.
|
||||
|
||||
**Out:**
|
||||
- **#923**, the 49 ms cost of a single SharedPreferences write on Windows. Epic B shrinks its blast radius considerably by removing 86% of the prefs file, but the mechanism is untouched and #923 stays open. Fixing it properly means moving the remaining keys or batching writes, which is its own work.
|
||||
- Refactoring the twelve already-correct stores onto a shared scoping helper. The pattern is duplicated and the rule of three would justify a helper, but rewriting working per-radio storage carries real data risk for no user-visible benefit.
|
||||
- #660 and #280. #853's own body excludes them as "related but not isolation, not parented here", and that is still right: #660 is radio-side contact loss, #280 is message ordering.
|
||||
- Any firmware or wire-format change. This Feature is entirely client-side.
|
||||
|
||||
## 3. Epics
|
||||
|
||||
Tasks are 3 to 4 points. Each Epic ends with a verification task and gets one PR. Epic A reproduces the diagnosis as failing tests before anything is built.
|
||||
|
||||
### Epic A: [#936](https://github.com/OffbandMesh/meshcore-client/issues/936) scoping-verdict harness and failing repros
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **A1 · Surface inventory with declared verdicts:** a test that enumerates every persistence surface (drift key prefixes and prefs keys) against a declared table of `perRadio` or `globalOnPurpose(reason)`. It fails on an unclassified surface and on a new global key. Proven by adding a fake global key in the test and watching it go red | 4 |
|
||||
| **A2 · Reproduce rows 3 and 5 as failing tests:** radio A's path history visible to radio B, and radio A's delivery observations feeding radio B's model. Both red before Epic B touches anything | 3 |
|
||||
| **A3 · Epic verification:** the harness fails for the right reasons and passes for the current declared set, with A2's two repros red | 1 |
|
||||
|
||||
### Epic B: [#937](https://github.com/OffbandMesh/meshcore-client/issues/937) the three global `storage_service` surfaces, as one migration
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **B1 · Delete the dead `pending_messages` API** (#855): three methods and the key, with the harness updated so the surface leaves the inventory rather than being reclassified | 3 |
|
||||
| **B2 · Path history per radio, in drift** (#854 and #924): scope by radio prefix, move the store from SharedPreferences to `BlobStore`, bound what persists to what `PathHistoryService` actually caches, and **delete the 2,041 legacy untagged keys once the readback gate passes** (decision 1) | 4 |
|
||||
| **B3 · Delivery observations per radio** (#856): scope by radio prefix so the model trains per radio, and **delete the legacy global list** (decision 1) | 3 |
|
||||
| **B4 · Epic verification:** A2's repros now pass, the inventory shows no unclassified surface, and the owner's real prefs file is measurably smaller with route history intact | 1 |
|
||||
|
||||
### Epic C: [#938](https://github.com/OffbandMesh/meshcore-client/issues/938) Blocked per-radio view
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **C1 · The view** (#507): Settings to Blocked lists the connected radio's blocks, with an explicit disconnected state and an explicit empty state that read differently from each other | 3 |
|
||||
| **C2 · Isolation and clear tests:** a block on radio A is absent on radio B, and a clear sticks across a restart | 3 |
|
||||
| **C3 · Epic verification:** hardware on the T1000e, confirming the re-clear behind #471 does not recur | 1 |
|
||||
|
||||
### Epic D: [#939](https://github.com/OffbandMesh/meshcore-client/issues/939) scope-key lifecycle, the stale-read window
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **D1 · Verdict on #190** (diagnosis, no code): does its reproduction still reproduce after #194 and #472? Close it, or re-scope it to what actually remains, with evidence either way | 3 |
|
||||
| **D2 · Close the stale-read window** (#158): no per-radio read resolves against a stale or unset prefix. Fail closed, returning nothing rather than the previous radio's data | 4 |
|
||||
| **D3 · Epic verification:** a switch between two radios with no window in which a read can see the wrong prefix, proven by test and on desktop where #158 was seen | 1 |
|
||||
|
||||
### Epic E: [#940](https://github.com/OffbandMesh/meshcore-client/issues/940) Integration Testing
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **E1 · The full matrix:** for every surface in the inventory, radio A's datum isolated and not inherited by radio B, across a radio switch **and** an app restart, which is #853's stated acceptance bar | 4 |
|
||||
| **E2 · Hardware validation:** two real radios on the owner's own install, including the twelve-radio database already on his machine | 3 |
|
||||
| **E3 · Epic verification and Feature closure:** the inventory is complete, every verdict recorded, no hole left | 1 |
|
||||
|
||||
## 4. Order and dependencies
|
||||
|
||||
**A, then B, then C and D in either order, then E.**
|
||||
|
||||
- **A is first** because it is the base diagnostic: without it, B's fixes cannot be shown to have fixed anything, and it is the only task that prevents recurrence.
|
||||
- **B is second** because it is the largest hole and the only one with a cost a user feels today, both the route bleed and the prefs-file tax on every other settings write.
|
||||
- **C and D are independent** of each other and of B. C touches `lib/screens/`, D touches the connector and the scope-key plumbing, neither touches `storage_service.dart`.
|
||||
- **E is last** by canon: a Feature's final Epic is Integration Testing of the whole integrated environment.
|
||||
|
||||
**File overlap:** only B touches `lib/services/storage_service.dart`, and it touches it three times inside one Epic instead of across three PRs, which is the whole reason these were consolidated. D touches `lib/connector/meshcore_connector.dart`, the most contended file in the repo, so D should not run alongside other connector work.
|
||||
|
||||
## 5. Grants and authorization
|
||||
|
||||
What merging this plan authorizes, in words:
|
||||
|
||||
| Term | Proposed | Why |
|
||||
|---|---|---|
|
||||
| **What merging this plan authorizes** | Building all five Epics end to end with no further approval, opening one PR per Epic | The chain model that worked for #917: one approval, unattended run, merges held |
|
||||
| **Merges** | 5, one per Epic | Tasks are commits on the Epic branch, so there is no per-task PR. Five Epics, five PRs |
|
||||
| **Epic verification** | `owner` | Three of the five end in a judgement only the owner can make: hardware on the T1000e (C), a real two-radio switch (D and E), and whether route history survived the move (B). A command here would be a check that cannot fail |
|
||||
| **Owner steps during the run** | Two, both late: the T1000e check for C and the two-radio switch for E, one message each | Everything else, including the migration rehearsal against a copy of his real database, runs without him |
|
||||
| **Stops** | A refused migration readback, a harness failure this plan did not predict, or any sign of lost route history | Each is a data-integrity signal, and each stops rather than proceeding |
|
||||
| **Flash** | `null` | Nothing here touches firmware. The T1000e check uses whatever is already on it |
|
||||
|
||||
```grant-terms
|
||||
{
|
||||
"epic_chain": [936, 937, 938, 939, 940],
|
||||
"chain": true,
|
||||
"verification": { "mode": "owner" },
|
||||
"merge": { "budget": 5, "basis": "one merge per Epic in the chain (936, 937, 938, 939, 940); Tasks are commits on the Epic branch, so there is no per-task PR" },
|
||||
"flash": null,
|
||||
"reset": null,
|
||||
"expires_after_hours": 168
|
||||
}
|
||||
```
|
||||
|
||||
**Basis for the expiry.** 168 hours, the maximum, because Epics C, D and E each end in an owner hardware step and the owner has a day job. #917's 72 hours was enough only because its single owner step came at the very end; a grant that expired between Epic C's hardware check and Epic D's would break the chain and need a re-mint for no reason.
|
||||
|
||||
## 6. Can't-tell branches
|
||||
|
||||
| Where | Can't tell what | Does |
|
||||
|---|---|---|
|
||||
| Legacy untagged `path_history_<contact>` key | which radio learned this route | **stop** — never assign it to a radio. Per decision 1 it is deleted, not guessed at, and only after the per-radio readback gate passes |
|
||||
| Legacy untagged `delivery_observations` | which radio produced these observations | **stop** — same. Deleted per decision 1; mixed-radio data is worse than no data for the model |
|
||||
| Per-radio read with an empty or unset scope prefix (#158) | which radio is connected | **stop** — return nothing, never fall back to the last known prefix. This is the #754 precedent: an unset key loads nothing and never writes |
|
||||
| A surface in the inventory with no declared verdict | whether it should be per-radio | **stop** — the harness fails the build. That is the point of A1 |
|
||||
| Path-history migration readback mismatch | whether every route survived the move into drift | **stop** — keep the prefs copy, delete nothing, surface loudly. Same gate as #920, which caught a lossy converter precisely because the count was measured independently of the converter |
|
||||
| `repeater_passwords`, keyed by repeater node | nothing: this one is **decidable**, and the verdict is global-on-purpose | proceeds, by recorded verdict rather than by silence. Not a fail-open branch |
|
||||
|
||||
No fail-open branches. Nothing in this plan needs a fail-open grant.
|
||||
|
||||
## 7. Verification
|
||||
|
||||
- **Named command:** `flutter test test/storage/ test/services/ test/connector/` plus `flutter analyze`, with the scoping-inventory test named explicitly in each Epic's PR body.
|
||||
- **Acceptance bar:** the inventory test fails when a surface is unclassified or a new global key appears, proven by making it fail on purpose; Epic A's two repros go red to green across Epic B; and on hardware, radio A's data never appears while radio B is connected, across a switch and a restart.
|
||||
|
||||
## 8. Done when
|
||||
|
||||
- Every persistence surface has a declared verdict, `perRadio` or `globalOnPurpose` with a reason, and a test fails if one does not.
|
||||
- #854, #855, #856, #507 and #158 are closed, and #190 has a recorded verdict.
|
||||
- #924 is closed as a side effect of B2.
|
||||
- On the owner's own twelve-radio install, a radio switch and a restart show no data belonging to any other radio.
|
||||
|
||||
## 9. Decisions
|
||||
|
||||
Settled by the owner, 2026-10-20. No open choices remain in this plan.
|
||||
|
||||
| # | Decision | What it means for the build |
|
||||
|---|---|---|
|
||||
| 1 | **Delete the legacy untagged data.** The 2,041 `path_history_<contact>` keys and the global `delivery_observations` are removed, not orphaned | B2 and B3 each delete their legacy key **only after** the per-radio readback gate passes. Both surfaces are regenerable: routes relearn in normal use and the ML model retrains. This is also what reclaims 86% of the prefs file |
|
||||
| 2 | **Path history moves into drift**, not just a radio prefix in place | B2 is a store move plus a scoping change in one migration, following #335's precedent for messages and contacts. Resolves #924, and cuts most of #923's per-write cost as a side effect by shrinking the file every other write re-encodes |
|
||||
| 3 | **#158 and #190 stay in this Feature**, as Epic D | The Feature cannot claim isolation while a read can still resolve against a stale prefix. A user cannot tell "wrong store" from "right store, wrong moment" |
|
||||
|
||||
Decision 1 differs from #754's choice to orphan, deliberately: that blob was small, whereas here the orphaned data *is* the performance problem.
|
||||
|
||||
## 10. Carried-in work
|
||||
|
||||
| Item | Goes to |
|
||||
|---|---|
|
||||
| #854 path history per radio | Epic B, task B2 |
|
||||
| #855 pending messages | Epic B, task B1, **as a deletion** rather than a scoping fix |
|
||||
| #856 delivery observations | Epic B, task B3 |
|
||||
| #924 `path_history_` unbounded (filed 2026-10-19) | Epic B, task B2, the same change as #854 |
|
||||
| #507 Blocked per-radio view | Epic C |
|
||||
| #158 history bleed after a radio switch | Epic D, task D2 |
|
||||
| #190 history bleed into a new channel | Epic D, task D1, as a verdict |
|
||||
| #923 prefs write cost | **Out of scope.** B2 shrinks its blast radius; the mechanism is untouched and the issue stays open |
|
||||
|
||||
## Alternatives considered but not chosen
|
||||
|
||||
- **One shared scoping helper across all twelve stores.** The rule of three would justify it, but rewriting working per-radio storage risks data for no user-visible gain.
|
||||
- **Three separate PRs for #854, #855 and #856.** How they were filed, and the reason this plan exists. They share a file, a defect and a migration decision, and splitting them triples the review and test rounds while hiding that one of the three is dead code.
|
||||
- **A commit hook blocking any new global prefs key.** Mechanical, but it would fire on every legitimate global setting. A1's inventory test achieves the same thing where the knowledge belongs, in a declared table beside the code.
|
||||
|
||||
When this plan merges, each Epic's Tasks get a GitHub issue and a Citadel task, per canon.
|
||||
@ -0,0 +1,175 @@
|
||||
# Feature PLAN: storage save path: remove O(history) work per message
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#917](https://github.com/OffbandMesh/meshcore-client/issues/917) · Citadel `meshcore-open-1hf` |
|
||||
| **Serves** | No parent Initiative; a standalone Feature. Resolves the cause behind [#334](https://github.com/OffbandMesh/meshcore-client/issues/334), the originating Epic, which stays open until this Feature's integration test proves the ANRs are gone. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-19 |
|
||||
|
||||
## At a glance
|
||||
- **What:** stop re-encoding a channel's entire message history every time one message arrives. First move the work off the UI isolate (Epic A), then delete the work by storing one row per message (Epic B).
|
||||
- **Why:** 25 ANR clusters on Play since September, all `Input dispatching timed out`. The cost grows linearly with history, so it worsens for exactly the users who use the app most. ANR rate is also the Android vitals signal Google uses to suppress an app in Play search, and Offband is currently absent from search for "meshcore" while ranking first for "offband".
|
||||
- **How:** entirely client-side. No firmware change. Three Epics in order: A isolate offload, B normalise to rows with a migration, C hardware integration test.
|
||||
- **Done when:** receiving a message costs the same at 50,000 messages of history as at 50, no message is lost in the migration, and the owner confirms on hardware on Android and Windows.
|
||||
|
||||
## 1. Diagnosis
|
||||
|
||||
All figures measured 2026-10-19 against the owner's live database and the real Dart VM. Full evidence: [#334 comment](https://github.com/OffbandMesh/meshcore-client/issues/334#issuecomment-6262727767).
|
||||
|
||||
| # | Finding | Evidence |
|
||||
|---|---|---|
|
||||
| 1 | `StoredBlobs` is `key TEXT PRIMARY KEY, value TEXT`: one JSON blob per store key | `lib/storage/drift/offband_database.dart:347` |
|
||||
| 2 | Live DB is 41.03 MB: 151 rows, 39.21 MB of JSON. Largest row is 5.38 MB holding **9,230 messages** in one channel | `select key, length(value) from stored_blobs` on a copy of the live DB |
|
||||
| 3 | Saving one message decodes the whole blob, rebuilds every record, re-encodes the whole blob | `channel_message_store.dart:80-104`, `message_store.dart:33-57` |
|
||||
| 4 | That costs **134 ms** on a desktop CPU: decode 50, rebuild 38, encode 51 | Dart benchmark, real 5.39 MB payload, median of 5 |
|
||||
| 5 | Cost scales linearly: ~14 ms per 1,000 records of history, per message | 500 recs 4 ms, 1k 12 ms, 2.5k 26 ms, 5k 83 ms, 9,230 130 ms |
|
||||
| 6 | Appending one record instead costs **0.002 ms**, so the current path does **67,000x** more work per message | Same benchmark, single-record encode, median of 200 |
|
||||
| 7 | Bursts serialize: `BlobStore.synchronized` chains futures per key, so N messages each pay full cost | `blob_store.dart:58-62` |
|
||||
| 8 | 5 messages on a 10x slower device is **6.7 s**, past the 5 s ANR watchdog | Arithmetic on finding 4. **Not reproduced on a device**; see Risks |
|
||||
| 9 | Each cycle allocates ~11 MB of strings plus 9,230 maps, which is why traces are dominated by GC frames | `ScavengerVisitor`, `MarkingVisitor`, `FreeList::TryAllocate`, `String::ConcatAllRange` in 25 clusters |
|
||||
| 10 | **#335 did not fix this.** It moved the bytes into SQLite; the JSON stayed. ANRs span version codes 65, 66 and 67, all post-drift | Play Reporting API clusters by `lastAppVersion` |
|
||||
| 11 | **SQLite was never on the UI isolate.** `drift_flutter` 0.3.1 hosts connections in a background isolate; web uses `drift_worker.js` | `drift_flutter-0.3.1/lib/src/connect.dart` |
|
||||
| 12 | Only 9 distinct users affected, 1 per cluster, consistent with cost scaling by history | `distinctUsers` on every cluster |
|
||||
|
||||
**Root cause:** O(entire history) work per message, serialized across a burst, with GC pressure compounding it.
|
||||
|
||||
## 2. Decisions
|
||||
|
||||
| Decision | Choice | Why |
|
||||
|---|---|---|
|
||||
| Fix the isolate first or normalise first | Isolate first | Stops the ANRs and the Play penalty with zero data risk, and buys time to do the migration carefully |
|
||||
| Is the isolate offload sufficient | No | It relocates ~11 MB of allocation per message rather than removing it. Total work unchanged |
|
||||
| Isolate granularity | One `Isolate.run` around the **whole** read-modify-write | Only two strings cross the boundary. Wrapping encode and decode separately would ship the object graph across twice |
|
||||
| Where the helper lives | `BlobStore` | One place, so stores change call shape instead of each growing its own isolate wrapper |
|
||||
| Migration safety | Additive. Blob retained until per-key readback matches | #355 cost 574 messages after the last storage migration shipped in a day |
|
||||
| Retype #334 | No | #917 is the Feature and carries this plan. #334 stays as the originating Epic and closes on the integration test. Less board churn |
|
||||
|
||||
## 3. Epic chain
|
||||
|
||||
### Epic A: blob read-modify-write off the UI isolate
|
||||
|
||||
One helper in `lib/storage/drift/blob_store.dart` that runs the entire read, decode, merge, encode, write inside a single `Isolate.run`, taking the raw JSON string in and returning the merged string out. Then call-shape changes in `channel_message_store.dart`, `message_store.dart` and `lib/services/storage_service.dart` (11 JSON call sites). Smaller stores follow only if measurement says they matter.
|
||||
|
||||
**Epic verification:** the benchmark harness shows main-isolate block time at or near zero against the real 5.39 MB payload, and the owner confirms a burst no longer freezes the UI.
|
||||
|
||||
#### Epic A outcome, 2026-10-19
|
||||
|
||||
Built as A1 (`BlobStore.mergeOffThread`), A2 (DM save), A3 (both explicit delete paths), A5 (verification). Measured against the owner's real largest channel, 5,650,194 chars / 9,230 messages, on a desktop:
|
||||
|
||||
| | UI blocked | wall | heartbeats |
|
||||
|---|---|---|---|
|
||||
| 1 save, inline (pre-#919) | 381 ms | 381 ms | 1 |
|
||||
| 1 save, off-thread | 44 ms | 297 ms | 174 |
|
||||
| 5 saves, inline | 1,385 ms | 1,385 ms | 1 |
|
||||
| 5 saves, off-thread | 66 ms | 1,496 ms | 964 |
|
||||
|
||||
Wall time barely moves, as predicted. Inline, the blocked time equals the whole operation. The burst case is now measured rather than arithmetic, though still on desktop hardware; the device check remains the owner's.
|
||||
|
||||
**A4 (`storage_service.dart`) was measured and declined**, which is this section's "smaller stores follow only if measurement says they matter" resolving to no. The largest value that file touches is 20,907 bytes (`path_history`, from the owner's live prefs); it costs 0.22 ms inline and 0.48 ms through `Isolate.run`, so converting those 11 call sites would add 2.2x the work. Full numbers: [#919 comment](https://github.com/OffbandMesh/meshcore-client/issues/919#issuecomment-6269611306).
|
||||
|
||||
That measurement turned up two things outside this Feature's shape, filed rather than absorbed:
|
||||
|
||||
- [#923](https://github.com/OffbandMesh/meshcore-client/issues/923): on Windows, one `SharedPreferences` write costs **49.4 ms on the UI isolate**, because `shared_preferences_windows` is pure Dart and re-encodes plus rewrites the whole file per key. Measured against the owner's live 4.23 MB prefs.
|
||||
- [#924](https://github.com/OffbandMesh/meshcore-client/issues/924): `path_history_` is unbounded on disk, 2,041 keys and 86% of that prefs file, which makes every write in #923 worse over time.
|
||||
|
||||
Both are children of #334 and neither is fixed by this Feature.
|
||||
|
||||
### Epic B: normalise messages into rows
|
||||
|
||||
A real drift table beside `StoredBlobs`, one row per message. A save becomes an INSERT; reads page. Both message stores' read and write paths rewritten. An additive migration that never deletes a blob until readback proves the per-key count matches.
|
||||
|
||||
**Epic verification:** per-key message counts identical before and after on a copy of the real 41 MB database, and the benchmark shows per-message cost flat across history length.
|
||||
|
||||
#### Epic B outcome, 2026-10-19
|
||||
|
||||
Built as B1 (`message_records` at schema 2 plus a row API), B2 (both stores on rows), B3 (the per-key migration and its gate), B4 (verification). Run against a copy of the live 41.17 MiB database:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| keys migrated | **138 of 138** |
|
||||
| records in blobs | 64,883 |
|
||||
| rows stored | **64,883** |
|
||||
| elapsed | 4,382 ms |
|
||||
|
||||
Exact parity, no refusals, and every blob byte-identical afterwards (length and content hash per key).
|
||||
|
||||
Per-message save cost against history length, median of 20:
|
||||
|
||||
| history | one more save |
|
||||
|---|---|
|
||||
| 500 | 0.124 ms |
|
||||
| 5,000 | 0.126 ms |
|
||||
| 50,000 | 0.133 ms |
|
||||
|
||||
A hundred times the history for 1.07x the cost, against 381 ms of UI block at 9,230 messages on the blob path. The Feature's "done when" is met.
|
||||
|
||||
One-time migration of the worst key (5.38 MiB, 9,230 messages), measured with a production-shaped background-isolate connection: **UI blocked 64 ms, wall 447 ms**. So the first open of the biggest channel after this ships costs one 64 ms hitch on a desktop.
|
||||
|
||||
**Two deliberate departures from this plan, both stricter or narrower, never looser:**
|
||||
|
||||
1. **The blob is never deleted**, not even on a verified match. This plan said "retained until per-key readback matches"; the implementation keeps it after the match too. Rows become the read and write path and the blob is left untouched, so the database temporarily holds both copies. Reclaiming that space is a separate owner-gated step, because the moment that delete runs is the moment a mistake stops being recoverable.
|
||||
|
||||
> **Correction, 2026-10-21 (#943), revised 2026-10-22.** This section originally added that a downgrade to an older build "still finds its history where it looks for it". That is true of the **data** and false in **practice**, and the owner hit it: a pre-#917 build cannot open a migrated database at all, so it never gets as far as the blobs it would have read.
|
||||
>
|
||||
> The first version of this correction gave the wrong reason, namely that drift refuses a newer `user_version`. It does not; there is no such check. drift compares the stored version against `schemaVersion` for *inequality* and routes a downgrade into `onUpgrade` just like an upgrade. The pre-#917 build declared schema 1 and **no `migration` getter**, so it got drift's default `onUpgrade`, which throws. The conclusion stands and is in fact firmer: every already-shipped build lacks that strategy, so no change made now can let one open a schema-2 file.
|
||||
>
|
||||
> The consequence is a release one, not a desktop one: **once a user launches a schema-2 build they cannot go back to an earlier release.** A Play rollback or a halted staged rollout does not help anyone who already launched it, and the real fallback is an older build *plus* a pre-migration database copy, which loses everything received since. #943 carries the decisions (release-note wording, whether to tolerate a newer schema, whether the app should take its own pre-migration copy), with measurements and a recommendation per decision in its comments. Behaviour is pinned by `test/storage/schema_downgrade_test.dart`.
|
||||
2. **One row per message with the per-message JSON in a `payload` column**, rather than a column per field. The migration is then a pure re-key with no field mapping that can silently drop or coerce a value, and the stores reuse their existing encoders verbatim. The trade, stated on the issue before building: message fields are not SQL-queryable. Columns can be added beside the payload later without another data migration.
|
||||
|
||||
### Epic C: Integration Testing
|
||||
|
||||
A and B together on real hardware, Android and Windows. Carries the test that validates #334 is dead, which gates closing it.
|
||||
|
||||
## 4. Interfaces
|
||||
|
||||
No protocol, wire-format or firmware change. No new dependency: `Isolate.run` is `dart:isolate`, and drift is already present. Storage schema change is internal and additive.
|
||||
|
||||
## 5. Secrets
|
||||
|
||||
None. This Feature touches no credential, key or external service.
|
||||
|
||||
## 6. Cannot-tell branches (standards#677)
|
||||
|
||||
| Branch | Behaviour |
|
||||
|---|---|
|
||||
| `Isolate.run` throws | **Stop.** Surface the error, leave the blob untouched. Never fall back to a silent main-thread encode |
|
||||
| Blob is corrupt or not a JSON list | **Stop.** Do not overwrite. Log the key and byte length, keep the original |
|
||||
| Migration readback count mismatch for a key | **Stop.** Keep the blob, delete nothing, surface loudly |
|
||||
| Row insert fails mid-migration | **Stop** inside a transaction, roll back, keep the blob |
|
||||
| Payload too large to send across the isolate | **Ask the owner.** Needs a measured threshold first; no guessed limit |
|
||||
|
||||
No fail-open paths. No branch proceeds on a condition it cannot confirm.
|
||||
|
||||
## 7. Risks
|
||||
|
||||
| Risk | Mitigation |
|
||||
|---|---|
|
||||
| Migration loses messages | Additive, blob retained, per-key readback gate, test against a copy of the real 41 MB DB |
|
||||
| The burst multiplier is arithmetic, not observed | Epic A's verification includes an owner device check. If a burst does not reproduce, the ANR cause is re-opened rather than assumed fixed |
|
||||
| Isolate transfer cost exceeds the saving on small blobs | Measure before converting the smaller stores. Epic A converts the three big ones first |
|
||||
| Play traces stay unresolvable | Out of scope here. Release builds strip Dart symbols, so no frame from this codebase appears in any trace. Retaining native debug symbols is a separate pipeline issue |
|
||||
|
||||
## 8. Owner steps
|
||||
|
||||
One, at the end of Epic A, and one at the end of Epic C: run the build on hardware and confirm the UI no longer freezes under a burst. Everything else, including the migration test, runs without him.
|
||||
|
||||
## grant-terms
|
||||
|
||||
The Epic chain is [#919](https://github.com/OffbandMesh/meshcore-client/issues/919) (A, isolate offload), [#920](https://github.com/OffbandMesh/meshcore-client/issues/920) (B, normalise to rows), [#921](https://github.com/OffbandMesh/meshcore-client/issues/921) (C, integration testing), merged in that order.
|
||||
|
||||
```grant-terms
|
||||
{ "epic_chain": [919, 920, 921],
|
||||
"chain": true,
|
||||
"verification": {"mode": "owner"},
|
||||
"merge": {"budget": 3,
|
||||
"basis": "one merge per Epic in the chain (919, 920, 921); Tasks are commits on the Epic branch, so there is no per-task PR"},
|
||||
"expires_after_hours": 72 }
|
||||
```
|
||||
|
||||
**Basis for the expiry.** 72 hours because Epic B carries a migration test against a copy of the real 41 MB database, and a grant that outlasts a careful run beats one expiring mid-chain and needing a re-mint.
|
||||
|
||||
**No flash or reset budget.** Nothing in this Feature touches a radio, so both keys are omitted and default to null.
|
||||
|
||||
**Verification is `owner` rather than a command** because two of the three Epics end in a judgement only the owner can make: that the UI no longer freezes under a burst on his device, and that nothing is missing after the migration. A command here would be a check that cannot fail, which the tool flags and which would verify nothing.
|
||||
@ -0,0 +1,175 @@
|
||||
# Feature PLAN: reclaim the stale post-migration message blob
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#962](https://github.com/OffbandMesh/meshcore-client/issues/962) · Citadel `meshcore-open-8xj` |
|
||||
| **Serves** | Follows the #917 storage rewrite. #917's plan deferred this as "a separate owner-gated step, because the moment that delete runs is the moment a mistake stops being recoverable." The owner opened that gate on 2026-10-22. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-22 |
|
||||
|
||||
## At a glance
|
||||
|
||||
- **What:** each migrated message key gets a timestamp; **30 days** later its stale blob is deleted, with a Settings action to do it immediately.
|
||||
- **Why now:** schema 2 has not shipped. Every install that takes it will hold its message history twice, and the fix can be in place before anyone receives it.
|
||||
- **How:** Epic A writes the timestamps and the sweep, Epic B the manual action, Epic C the owner's hardware check.
|
||||
- **Done when:** a key migrated more than 30 days ago has no blob, the file has actually shrunk, and a key whose re-verify fails still has its blob.
|
||||
|
||||
## 1. Diagnosis
|
||||
|
||||
| # | Finding | Evidence | Effect |
|
||||
|---|---|---|---|
|
||||
| 1 | The migrated blob goes **stale**: nothing writes it after a key is marked. | Every blob write is in the fallback branch behind an early `return` in the migrated branch: `channel_message_store.dart:175,235`, `message_store.dart:111,152`. | The blob is a frozen snapshot at the migration moment, not a mirror. Deleting it costs the pre-migration snapshot and nothing else. |
|
||||
| 2 | Nothing ever deletes it. | No caller removes a migrated history blob. `ensureMessageRowsMigrated` documents "**The blob is never deleted**, not even on a verified match." | The database holds the history twice, permanently. |
|
||||
| 3 | `DELETE` frees **no disk space**. | Measured on a copy of the owner's database: 74,350,592 bytes before, **74,350,592 after** deleting all 40 migrated blobs. | A sweep without `VACUUM` reclaims nothing the user can see. |
|
||||
| 4 | `VACUUM` reclaims it, cheaply. | Same copy: 54,919,168 bytes after, **-18.5 MiB in 0.6 s**, `integrity_check ok`, all 28,386 rows intact. | One `VACUUM` after a sweep is the whole win. |
|
||||
| 5 | Migration is **lazy and per key**. | The owner's install had 40 keys migrated (16.2 MB of blob) and **98 not** (23.8 MB), because those radios had not been reconnected. | An install-wide clock would delete nothing for a long time, then a lot at once. The marker must be per key. |
|
||||
| 6 | The marker holds no timestamps. | `__msgrows_migrated` is `jsonEncode(keys.toList())`, a flat array (`blob_store.dart:281`). | There is nothing to age a key against today. |
|
||||
| 7 | Some blobs are **not** reclaimable and must not be touched. | `contacts*`, `discovered_contacts*`, `path_history_*` have no row equivalent; the blob IS their storage. 2.0 MB on his install. | The sweep must be restricted to migrated message-history keys. |
|
||||
| 8 | Clearing history already removes both copies. | `clearChannelMessages` calls `deleteEverywhere` **and** `deleteMessageRows` (`channel_message_store.dart:361,372`). | No stale-history-after-delete hole to fix. Checked because it would be worse than wasted space. |
|
||||
| 9 | Losing the marker after deletion is survivable. | `blob_store.dart:340`: an empty or absent blob re-marks the key and reads rows. | Deletion does not create a new single point of failure beyond the rows themselves. |
|
||||
| 10 | It affects users, not just this install. | ~175 active Android installs (173 on 2026-10-17, Play installs overview) plus desktop. Schema 2 is on `dev` at `4d4d44a6` and absent from v1.6.0. | Shippable before anyone is exposed. |
|
||||
| 11 | `VACUUM` removes nothing. It reclaims only pages the deletes already freed. | Measured on a copy: 40 migrated blobs deleted, 291 keys kept **including all 98 unmigrated history blobs**, each hashed before and after. 0 missing, 0 byte-changed, 0 unexpected; rows 28,389 to 28,389; file 74,350,592 to 54,927,360; `integrity_check ok`. | **All the risk is in the DELETE selection, none in `VACUUM`.** The safety budget belongs on the per-key re-verify and the key-pattern restriction, which is where this plan puts it. |
|
||||
|
||||
**What the snapshot does and does not protect**, so this is not mistaken for removing a backup: it protects the *pre-migration* history against a migration or read-path bug found later; it protects **nothing** that arrived since, which is single-copy from the instant it lands either way; and its coverage decays as new messages accumulate.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
**In:**
|
||||
- A per-key migration timestamp, including a backfill for keys already migrated when this ships.
|
||||
- An automatic sweep, **once per launch**, that deletes a stale blob once its key is older than 30 days, re-verifying the key immediately before each delete rather than trusting the marker.
|
||||
- One `VACUUM`, only after a sweep that actually deleted something.
|
||||
- A Settings action, "Clear Stale History Now", reporting bytes before and after.
|
||||
|
||||
**Out:**
|
||||
- The retention limit (discarding history the user has only one copy of): #963, deliberately later.
|
||||
- Blobs for keys that have **not** migrated. Those are authoritative.
|
||||
- `contacts*`, `discovered_contacts*`, `path_history_*`. The blob is their storage.
|
||||
- Any backup or export story for rows. Raised and not asked for.
|
||||
- Reclaiming the SharedPreferences legacy copies. #853 already purged those.
|
||||
|
||||
## 3. Epics
|
||||
|
||||
### Epic A: the timestamp and the sweep
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **A1 · Reproduce the diagnosis as failing tests:** a key migrated long ago still has its blob; the marker carries no timestamp; `DELETE` without `VACUUM` leaves the file size unchanged. Red before anything is built. | 3 |
|
||||
| **A2 · Per-key timestamps:** a `__msgrows_migrated_at` blob mapping key to epoch ms, written when a key is marked. Pre-existing migrated keys are **stamped on first sight**, not treated as eligible, so no blob is deleted the moment a user updates. | 3 |
|
||||
| **A3 · The sweep:** for each migrated message-history key older than the 30-day constant, re-run the superset check (every blob record present as a row) and delete the blob **only** on a pass. Restricted to `channel_messages_*` and `messages_*`. Wired to run **once per launch**, after startup settles, never mid-session. | 4 |
|
||||
| **A4 · One `VACUUM`,** only if the sweep deleted something, with the reclaimed byte count logged. | 3 |
|
||||
| **A5 · Epic verification:** the named command, plus the sweep run against a copy of a real database. | 1 |
|
||||
|
||||
### Epic B: "Clear Stale History Now"
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **B0 · Mock-ups FIRST, owner-approved before any of it is built.** Every state of every new surface, as a committed HTML file beside this plan, in the format the firmware initiative uses: numbered variants, real chrome and tokens, example values from the owner's own install, and the behaviour to build as bullets under each. **Added 2026-10-23, after this Epic's UI was built and installed on both his machines without him ever seeing the design.** The plan had no such step, which is why that happened. | 2 |
|
||||
| **B1 · The action** in Settings, showing database size before and after and how many keys were cleared, with the same re-verify and refusal path as the sweep. Per decision 4 it **reports keys it refused** in the result, not just the log: "cleared 12, kept 1 that failed verification". | 3 |
|
||||
| **B1a · A confirmation stating the scope** before anything is deleted: how many copies, roughly how much space, how many messages are *not* affected, and that it cannot be undone. Needs a **preview pass** in the sweep, verifying every eligible key and totalling it without deleting, so the numbers are real rather than estimated. Verification then runs twice for a confirmed clear, once to preview and once under the key lock. That is the price of saying what will go before it goes. Owner-required 2026-10-23. | 3 |
|
||||
| **B2 · Widget tests:** the action with nothing eligible, with eligible keys, and with a key whose re-verify fails (which must report a refusal rather than silence). Plus the confirmation: it states the scope, Cancel deletes nothing and leaves the action usable, a forecast refusal is shown before the press, and nothing eligible opens no dialog at all. | 3 |
|
||||
| **B3 · Epic verification** | 1 |
|
||||
|
||||
### Epic C: Integration Testing
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **C1 · Owner hardware run,** Windows and Android: the action reports a real reduction, history still reads correctly afterwards, and an unmigrated radio's history is untouched when that radio is next connected. | 3 |
|
||||
| **C2 · Post-run read-back** of the live database: no migrated key retains a blob, unmigrated keys all do, row count unchanged. | 1 |
|
||||
|
||||
## 4. Order and dependencies
|
||||
|
||||
A before B: the action is a manual trigger for the sweep A builds, so building B first would mean writing the engine twice. C last, per canon, and it is the only Epic needing the owner.
|
||||
|
||||
A and B both touch `blob_store.dart`; B also touches the Settings screen and ARB files. No overlap with #963, which should follow this rather than lead it (see its fourth open question: a row trim makes the blob a superset of the rows, which is this sweep's refusal condition, so the two must agree on authority or a trim permanently blocks reclamation the way #952 did).
|
||||
|
||||
## 5. Grants and authorization
|
||||
|
||||
| Term | Proposed | Why |
|
||||
|---|---|---|
|
||||
| **What merging this plan authorizes** | Building Epics A, B and C, and merging one PR per Epic. | Three Epics, three PRs. |
|
||||
| **Merges** | 3 | One per Epic. Tasks are commits on the Epic branch, so there is no per-task PR. |
|
||||
| **Epic verification** | Owner approves each Epic's PR. | A destructive data operation. Each Epic's PR should be looked at, not auto-verified by a command. |
|
||||
| **Owner steps during the run** | Epic C only. | A and B are test-provable; only the real-hardware reduction needs him. |
|
||||
| **Stops** | Any key whose re-verify fails. The sweep keeps that blob, logs loudly, and never retries into a loop. | The #952 lesson: a refusal that silently repeats forever is worse than a loud one. |
|
||||
| **Flash** | None. | No firmware. |
|
||||
|
||||
```grant-terms
|
||||
{
|
||||
"epic_chain": [965, 966, 967],
|
||||
"chain": true,
|
||||
"verification": { "mode": "owner" },
|
||||
"merge": { "budget": 3, "basis": "one merge per Epic (A the timestamp and sweep, B the manual action, C Integration Testing); Tasks are commits on the Epic branch, so there is no per-task PR" },
|
||||
"flash": null,
|
||||
"reset": null,
|
||||
"expires_after_hours": 168
|
||||
}
|
||||
```
|
||||
|
||||
**`epic_chain` filled 2026-10-23:** [#965](https://github.com/OffbandMesh/meshcore-client/issues/965) (Epic A, the timestamp and sweep), [#966](https://github.com/OffbandMesh/meshcore-client/issues/966) (Epic B, the manual action), [#967](https://github.com/OffbandMesh/meshcore-client/issues/967) (Epic C, Integration Testing). All three are sub-issues of #962, with Citadel tasks `meshcore-open-5vt`, `-gan` and `-2jd` chained A to B to C.
|
||||
|
||||
It was left empty when this plan first merged, which was a sequencing mistake: `grant.py` requires a non-empty chain, so the plan as merged could not have minted a grant and this follow-up was needed. The Epic issues should exist before a plan PR merges.
|
||||
|
||||
**Basis for the expiry.** 168 hours, the maximum. Epic C ends in an owner hardware step on two platforms and he has a day job; a grant expiring between Epic B's merge and Epic C's run would need a re-mint for no reason.
|
||||
|
||||
## 6. Can't-tell branches
|
||||
|
||||
| Where | Can't tell what | Does |
|
||||
|---|---|---|
|
||||
| Sweep: a key's re-verify finds a blob record with no row | whether the rows really hold this key's history | **stop** — keep the blob, log which records are missing, never delete, do not retry in a loop |
|
||||
| Sweep: the blob will not decode during re-verify | what the blob contains | **stop** — keep it, log it |
|
||||
| Sweep: a migrated key has no timestamp | when it migrated | **stop** deleting — stamp it now and let it age the full 30 days |
|
||||
| Sweep: the key is not `channel_messages_*` or `messages_*` | whether a row equivalent exists | **stop** — out of scope, never considered |
|
||||
| `VACUUM` fails, e.g. no temporary space | whether the file can be compacted | **proceeds**, logging the failure. Not fail-open on data: the deletes already happened and are correct, and `VACUUM` only affects file size. The next sweep retries it. |
|
||||
|
||||
No fail-open branch touches data. The one branch that proceeds affects file size only, and the deletes it follows are each individually verified.
|
||||
|
||||
## 7. Verification
|
||||
|
||||
- **Named command:** `flutter test test/storage/ test/screens/` plus `flutter analyze`
|
||||
- **Acceptance bar:**
|
||||
- A key stamped older than 30 days, whose rows hold every blob record, loses its blob; the file shrinks after `VACUUM`.
|
||||
- A key stamped older than 30 days with **one** blob record missing from rows **keeps** its blob, and the refusal names the missing records. This gate must be proved able to fail.
|
||||
- A key stamped inside 30 days keeps its blob, including at 29 days, so the boundary is tested and not just the middle of each range.
|
||||
- A migrated key with no timestamp is stamped, not deleted.
|
||||
- `contacts`, `discovered_contacts` and `path_history_` keys are never considered, asserted by name.
|
||||
- An unmigrated history key keeps its blob.
|
||||
- **Every kept blob is byte-identical after `VACUUM`**, compared by hash before and after, with the unmigrated history keys asserted present by name. Row count unchanged. This is the owner's question answered as a test rather than a paragraph: the sweep must be shown to delete only what it selected, and `VACUUM` to add nothing to that set.
|
||||
- Run against a copy of a real database, reporting bytes reclaimed, and skipping loudly rather than passing when no database is supplied.
|
||||
|
||||
## 8. Done when
|
||||
|
||||
- No key migrated more than 30 days ago retains a message-history blob.
|
||||
- The database file is measurably smaller, verified by reading the live file, not by trusting a log line.
|
||||
- Row count is unchanged across the whole sweep.
|
||||
- A key whose re-verify fails still has its blob, and said so.
|
||||
- The Settings action reports a real before and after on the owner's install, on both platforms.
|
||||
|
||||
## 9. Decisions
|
||||
|
||||
Owner, 2026-10-22: *"X = 30, sweep once per launch, timestamps in separate blob, button reports refusals, agreed."* All four as recommended.
|
||||
|
||||
| # | Question | Decision | Why |
|
||||
|---|---|---|---|
|
||||
| 1 | How long is X? | **30 days** | One full month of real use, and it matches the monthly granularity of the Play installs and crash reports the owner reads, so a migration problem gets a reporting cycle to surface in before the snapshot goes. 14 would have halved the double-storage window and also halved the time to notice. |
|
||||
| 2 | When does the automatic sweep run? | **Once per launch**, after startup settles | Predictable, at most one `VACUUM` per launch, and it cannot fire mid-session while the app is in use. |
|
||||
| 3 | Where do the timestamps live? | **A separate `__msgrows_migrated_at` blob** | `__msgrows_migrated` is read on every save and load through a cached hot path; reshaping it would risk that path and need its own migration. The timestamps are read only by the cold once-per-launch sweep. |
|
||||
| 4 | If a key's re-verify fails, does the user hear about it? | **The manual action reports it. The automatic sweep stays log-only.** | The user pressed a button, so "cleared 12 keys, kept 1 that failed verification" is the honest result. Silence is how #952 went unnoticed. The automatic sweep has no one watching, so a log line is the right place for it. |
|
||||
|
||||
**30 days is a named constant, not a literal scattered through the sweep**, so changing it later is one edit and the tests can set it directly rather than manipulating clocks.
|
||||
|
||||
### Added 2026-10-23, after the mock-up review
|
||||
|
||||
| # | Question | Decision | Why |
|
||||
|---|---|---|---|
|
||||
| 5 | Does the manual action confirm before deleting? | **Yes, stating the scope**: how many copies, roughly how much space, how many messages are not affected, and that it cannot be undone. | It deletes and cannot be undone. See B1a; it needs a preview pass, and the mock-up's variants 8 to 10 are the approved shape. |
|
||||
| 6 | "Compact" or "Clear Stale History"? | **Clear Stale History Now** | Owner's reason, and the better argument: the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. "Compact" describes `VACUUM`, which is an implementation detail. |
|
||||
| 7 | Does an explicit press clear a key that has no timestamp yet? | **Yes.** The automatic sweep still refuses. | Found while building the preview. The "skip anything stamped this pass" guard exists so installing an update never deletes on sight, and it was being applied to the button too. Every install that migrated before #962 has no stamps, so the button would have reported "nothing to clear" against real reclaimable blobs. The owner's install was exactly that: 47 migrated keys, none stamped. `eligibleByAge` is now the one rule both paths share. |
|
||||
|
||||
## 10. Carried-in work
|
||||
|
||||
| Item | Goes to |
|
||||
|---|---|
|
||||
| Retention limit, capping days of history retained | #963 |
|
||||
| Release-text disclosure for the first version carrying schema 2 | #953 |
|
||||
| Whether rows need any backup or export story | not filed; raised on #943 and not asked for |
|
||||
@ -0,0 +1,168 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Storage card mockups</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
/* Material 3, light scheme, blue seed, as main.dart actually configures it
|
||||
(useMaterial3, ThemeMode.system, seed blue). Dark follows automatically and
|
||||
is not drawn. Phone pane shown at 360 wide, the narrowest real target. */
|
||||
:root{
|
||||
--surf:#FDFCFF; --surfC:#FFFFFF; --surfCHigh:#F3F3FA; --surfCHighest:#E5E2EA;
|
||||
--onSurf:#1B1B1F; --onSurfVar:#45464F; --outline:#767680; --outlineVar:#C7C5D0;
|
||||
--prim:#0B57D0; --onPrim:#FFFFFF; --primCont:#D8E2FF; --onPrimCont:#001849;
|
||||
--err:#BA1A1A; --errCont:#FFDAD6; --onErrCont:#410002;
|
||||
--okCont:#C4EED0; --onOkCont:#002110;
|
||||
--warnCont:#FFDEA6; --onWarnCont:#2A1800;
|
||||
--page:#15151A; --pageInk:#D8D8E0; --pageDim:#8E8E99;
|
||||
--sans:'Roboto',system-ui,sans-serif; --mono:'JetBrains Mono',monospace;
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 48px}
|
||||
h1{font-size:26px;font-weight:500;color:#fff}
|
||||
h3{font-size:18px;font-weight:500;color:#9FC2FF;margin:30px 0 10px}
|
||||
.lede{font-size:15px;color:var(--pageDim);margin:8px 0 10px;max-width:980px;line-height:1.5}
|
||||
.lede b{color:var(--pageInk);font-weight:500}
|
||||
.grid{display:flex;flex-wrap:wrap;gap:28px}
|
||||
.card{width:360px}
|
||||
.card h2{font-size:17px;font-weight:500;color:#fff}
|
||||
.card .n{font-family:var(--mono);font-size:12px;color:#9FC2FF;margin-right:6px}
|
||||
.card p{font-size:14px;color:var(--pageInk);margin:4px 0 10px;line-height:1.35;min-height:60px}
|
||||
.card ul{font-size:13px;color:var(--pageDim);margin:10px 0 0 16px;line-height:1.4}
|
||||
.card ul b{color:var(--pageInk);font-weight:500}
|
||||
/* phone pane */
|
||||
.dev{width:360px;border:1px solid #2c2c33;border-radius:12px;overflow:hidden;background:var(--surf)}
|
||||
.appbar{height:56px;display:flex;align-items:center;gap:16px;padding:0 16px;background:var(--surfCHigh);color:var(--onSurf)}
|
||||
.appbar .bk{font-size:20px;color:var(--onSurfVar)}
|
||||
.appbar .t{font-size:20px;font-weight:400}
|
||||
.pane{padding:16px;display:flex;flex-direction:column;gap:16px;background:var(--surf)}
|
||||
.mc{background:var(--surfC);border-radius:12px;padding:16px 20px;color:var(--onSurf);border:1px solid var(--outlineVar)}
|
||||
.mc .ct{font-size:16px;font-weight:500;margin-bottom:8px}
|
||||
.mc .size{font-size:16px;margin-bottom:8px}
|
||||
.mc .hint{font-size:12px;color:var(--onSurfVar);line-height:1.45;margin-bottom:12px}
|
||||
.mc .res{font-size:14px;margin-top:12px;line-height:1.5}
|
||||
.mc .res.kept{color:var(--onWarnCont);background:var(--warnCont);border-radius:8px;padding:8px 10px;margin-top:8px}
|
||||
.mc .res.bad{color:var(--onErrCont);background:var(--errCont);border-radius:8px;padding:8px 10px}
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;height:40px;padding:0 20px;border-radius:20px;
|
||||
font-size:14px;font-weight:500;background:var(--primCont);color:var(--onPrimCont);border:none}
|
||||
.btn.off{background:var(--surfCHighest);color:var(--outline)}
|
||||
.btn.txt{background:none;color:var(--prim);padding:0 12px}
|
||||
.btn.dang{background:var(--errCont);color:var(--onErrCont)}
|
||||
.ghost{font-size:14px;color:var(--onSurfVar)}
|
||||
/* dialog */
|
||||
.scrim{background:rgba(0,0,0,.45);padding:28px 16px;display:flex;justify-content:center}
|
||||
.dlg{background:var(--surfCHigh);border-radius:28px;padding:24px;max-width:312px;width:100%;color:var(--onSurf)}
|
||||
.dlg .dt{font-size:24px;font-weight:400;line-height:1.25;margin-bottom:16px}
|
||||
.dlg .db{font-size:14px;color:var(--onSurfVar);line-height:1.5;margin-bottom:12px}
|
||||
.dlg .db b{color:var(--onSurf);font-weight:500}
|
||||
.dlg .note{font-size:13px;border-radius:8px;padding:10px 12px;margin-bottom:12px;line-height:1.45}
|
||||
.dlg .note.ok{background:var(--okCont);color:var(--onOkCont)}
|
||||
.dlg .note.warn{background:var(--warnCont);color:var(--onWarnCont)}
|
||||
.dlg .acts{display:flex;justify-content:flex-end;gap:8px;margin-top:8px}
|
||||
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--outline);border-top-color:transparent;border-radius:50%;margin-right:8px;vertical-align:-2px}
|
||||
.tag{font-family:var(--mono);font-size:11px;color:#9FC2FF}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Storage card and clear confirmation (Epic B, #966)</h1>
|
||||
<p class="lede">Material 3, light scheme, blue seed, as <span class="tag">main.dart</span> configures it. Dark follows the same tokens and is not drawn. Phone pane at 360 wide, the narrowest real target; the Windows pane is the same widget in a wider column. Numbers are the owner's actual install on 2026-10-22: <b>70.9 MB database, 47 migrated keys, 40 with a stale copy, 29,975 messages, about 16.6 MB reclaimable</b>. Bullets under each card are the behaviour to build. <b>Owner-approved 2026-10-23:</b> all variants as drawn, and the label stays <b>Clear Stale History Now</b> rather than "Compact" — his reason is that the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. Variants 1 to 10 are built; 11 is the rejected label alternative, kept for the record.</p>
|
||||
|
||||
<h3>Where it lives</h3>
|
||||
<div class="grid">
|
||||
<div class="card"><h2><span class="n">1</span>App Settings, bottom of the pane</h2><p>A new <b>Storage</b> card after Cyr2Lat, last in the list. It is a read-only status plus one action, so it sits below the preference cards rather than among them.</p>
|
||||
<div class="dev"><div class="appbar"><span class="bk">‹</span><span class="t">App Settings</span></div>
|
||||
<div class="pane">
|
||||
<div class="mc"><div class="ct">Cyrillic to Latin</div><div class="hint" style="margin:0">Transliterate incoming Cyrillic text.</div></div>
|
||||
<div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span></div>
|
||||
</div></div>
|
||||
<ul><li>Last card, so a destructive action is never the first thing under a thumb.</li><li>Size is read on build and after any clear. A failure to read it hides the row, never blocks the button (variant 7).</li><li>Same widget on Windows; only the column width differs.</li></ul></div>
|
||||
</div>
|
||||
|
||||
<h3>The card's states, as built today</h3>
|
||||
<div class="grid">
|
||||
|
||||
<div class="card"><h2><span class="n">2</span>Working</h2><p>The button disables and relabels while the sweep runs. A second tap in the same frame is also refused in code, because <span class="tag">setState</span> only schedules a rebuild.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn off"><span class="spin"></span>Clearing...</span></div></div></div>
|
||||
<ul><li>Two concurrent sweeps would mean two concurrent <span class="tag">VACUUM</span>s.</li><li>Re-enables on success and on failure, or the action works exactly once per launch.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">3</span>Cleared</h2><p>Count and bytes returned, and the size row updates to what the sweep actually left behind rather than the number it started with.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span>
|
||||
<div class="res">Cleared 40 old copies, 16.6 MB returned.</div></div></div></div>
|
||||
<ul><li>Bytes come from SQLite either side of the sweep, not from adding up blob lengths.</li><li>Pressing again is harmless: those keys have no copy left, so it reports nothing to clear.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">4</span>Cleared, with something kept back</h2><p>A key whose rows could not be verified keeps its copy and is <b>reported</b>, not merely logged. This is the case the Epic exists for.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span>
|
||||
<div class="res">Cleared 39 old copies, 16.2 MB returned.</div>
|
||||
<div class="res kept">Kept 1 that could not be verified. Your messages are intact; nothing was deleted for those.</div></div></div></div>
|
||||
<ul><li>Shown even when a refusal is the reason <b>nothing</b> was cleared, which is the most important case to surface, not the least.</li><li>The automatic 30-day sweep stays log-only: nobody is watching it.</li><li>Which keys and which records are named in the durable audit, not on screen.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">5</span>Nothing to clear</h2><p>The ordinary state for anyone who has already swept, or who has no migrated history yet.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span>
|
||||
<div class="res">Nothing to clear.</div></div></div></div>
|
||||
<ul><li>Says so plainly rather than showing a zero-byte success.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">6</span>Failed</h2><p>It must not read as "something was half-deleted", and it must not claim nothing happened either, because the sweep deletes per key and a throw can follow real deletes.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span>
|
||||
<div class="res bad">Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.</div></div></div></div>
|
||||
<ul><li>No exception text on screen; the reason goes to the log and the audit.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">7</span>Size unreadable</h2><p>A size we cannot read is not a reason to block clearing, so the row is left out and the action stays live.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span></div></div></div>
|
||||
<ul><li>Logged as a warning, never surfaced as an error.</li></ul></div>
|
||||
|
||||
</div>
|
||||
|
||||
<h3>Proposed: confirm before deleting</h3>
|
||||
<p class="lede">None of this exists. It needs a <b>preview pass</b> in the sweep: verify every eligible key and total it, without deleting, so the dialog can state real numbers rather than a guess. The verification then runs twice, once to preview and once under the key lock to delete, which is the cost of saying what will go before it goes.</p>
|
||||
<div class="grid">
|
||||
|
||||
<div class="card"><h2><span class="n">8</span>Confirm, the normal case</h2><p>States what will be cleared, what is not affected, and that it cannot be undone. The action button carries the count so the last thing read is the scope.</p>
|
||||
<div class="dev"><div class="scrim"><div class="dlg">
|
||||
<div class="dt">Clear stale history?</div>
|
||||
<div class="db">This removes <b>40 old copies</b> of history that has already moved to the new format, freeing about <b>16.6 MB</b>.</div>
|
||||
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
|
||||
<div class="note warn">This cannot be undone.</div>
|
||||
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 40 copies</span></div>
|
||||
</div></div></div>
|
||||
<ul><li>Counts come from a real preview pass, not an estimate.</li><li>Cancel is the plain text button and sits left, so the destructive one is never the default target.</li><li>Dismissing by tapping outside or back cancels.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">9</span>Confirm, with a forecast refusal</h2><p>If the preview already knows a key cannot be verified, say so <b>before</b> the press rather than reporting it afterwards.</p>
|
||||
<div class="dev"><div class="scrim"><div class="dlg">
|
||||
<div class="dt">Clear stale history?</div>
|
||||
<div class="db">This removes <b>39 old copies</b> of history that has already moved to the new format, freeing about <b>16.2 MB</b>.</div>
|
||||
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
|
||||
<div class="note warn">1 copy will be kept back because its messages could not be verified. This cannot be undone.</div>
|
||||
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 39 copies</span></div>
|
||||
</div></div></div>
|
||||
<ul><li>The count in the button excludes what will be kept, so it matches what actually goes.</li><li>A refusal discovered only at delete time still reports after the fact, as variant 4.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">10</span>Nothing eligible, no dialog</h2><p>With nothing to clear there is nothing to confirm, so the press reports straight away rather than opening a dialog to say "zero".</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
|
||||
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
|
||||
<span class="btn">Clear Stale History Now</span>
|
||||
<div class="res">Nothing to clear.</div></div></div></div>
|
||||
<ul><li>The preview runs on the press. Empty result means no dialog at all.</li><li>So the preview must be cheap enough to run on a tap: it reads and verifies, it does not write.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">11</span>Label: the open question</h2><p>The owner said "Compact"; the button says "Clear Stale History Now". Drawn here with his word in the title and the plain description in the body.</p>
|
||||
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
|
||||
<div class="hint">Compacting removes the old copy of history that has already moved to the new format, and returns the space. It happens on its own 30 days after the move.</div>
|
||||
<span class="btn">Compact now</span></div></div></div>
|
||||
<ul><li>"Compact" is what <span class="tag">VACUUM</span> does and reads less alarming; "Clear Stale History" says what is removed.</li><li>Owner's call. Either way the dialog in variant 8 states the scope.</li></ul></div>
|
||||
|
||||
</div>
|
||||
</body></html>
|
||||
@ -0,0 +1,280 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Location screen and settings restructure mockups</title>
|
||||
<style>
|
||||
/* Doc chrome: Offband design-doc family, as the firmware GUI mockups.
|
||||
Inside the frames: Flutter Material 3, drawn against the real widgets in
|
||||
lib/screens/settings/settings_shell.dart (ListTile + leading Icon + subtitle
|
||||
+ chevron, inside Cards, under a centred AppBar).
|
||||
Self-contained on purpose: icons are inline SVG, fonts are system stacks.
|
||||
Nothing here needs the network to render. */
|
||||
:root{
|
||||
--bg2:#161C19; --line:#34403A; --line2:#232C28;
|
||||
--ink:#EFF3E8; --ink2:#BAC4B5; --dim:#8B9A91; --sig:#7BEFA8;
|
||||
--warn:#FFA552; --bad:#FF7A6E;
|
||||
--sans:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;
|
||||
--mono:'Cascadia Mono',Consolas,'SF Mono',Menlo,monospace;
|
||||
--page:#0a0d0c; --pageInk:#cfd6cc;
|
||||
/* Material 3, blue seed, light. The client's actual scheme. */
|
||||
--surface:#FDFBFF; --onSurface:#1A1C1E; --onSurfaceVar:#44474F;
|
||||
--cardBg:#F2F3F7; --outline:#74777F; --outlineVar:#C4C6D0;
|
||||
--primary:#0061A4; --secCont:#D6E3FF; --onSecCont:#001D36;
|
||||
--ok:#1E6B39; --amber:#8A5000; --grey:#74777F;
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 56px}
|
||||
h1{font-size:25px;font-weight:600;color:var(--ink);letter-spacing:-.2px}
|
||||
h3{font-size:17px;font-weight:600;color:var(--sig);margin:32px 0 12px}
|
||||
.lede{font-size:14px;color:var(--dim);margin:8px 0 4px;max-width:1040px;line-height:1.55}
|
||||
.lede b{color:var(--ink2);font-weight:500}
|
||||
code{font-family:var(--mono);font-size:11.5px;color:var(--sig)}
|
||||
.why code{color:var(--ink2)}
|
||||
.flag{display:inline-block;font-family:var(--mono);font-size:10.5px;font-weight:600;color:#0a0d0c;background:var(--sig);border-radius:3px;padding:2px 7px}
|
||||
.grid{display:flex;flex-wrap:wrap;gap:30px}
|
||||
.card{width:324px}
|
||||
.card h2{font-size:17px;font-weight:600;color:var(--ink)}
|
||||
.card .n{font-family:var(--mono);font-size:12px;color:var(--sig);margin-right:7px}
|
||||
.card>p{font-size:13.5px;color:var(--ink2);margin:5px 0 12px;line-height:1.45;min-height:58px}
|
||||
.card ul{font-size:12.5px;color:var(--dim);margin:12px 0 0 16px;line-height:1.5}
|
||||
.card li{margin-bottom:5px}
|
||||
.card ul b{color:var(--ink2);font-weight:500}
|
||||
.sub{font-size:12.5px;color:var(--dim);margin-bottom:8px}
|
||||
|
||||
.dev{border:1px solid #2a332f;border-radius:14px;overflow:hidden;background:#000}
|
||||
.d-loc{width:324px;height:468px} .s-loc{width:390px;height:563px;transform:scale(.8308)}
|
||||
.d-set{width:316px;height:600px} .s-set{width:390px;height:740px;transform:scale(.8103)}
|
||||
.d-pan{width:316px;height:268px} .s-pan{width:390px;height:331px;transform:scale(.8103)}
|
||||
.scr{transform-origin:0 0;background:var(--surface);color:var(--onSurface);
|
||||
font-family:'Segoe UI',system-ui,Roboto,sans-serif;display:flex;flex-direction:column}
|
||||
|
||||
/* Material 3 parts */
|
||||
.ic{width:24px;height:24px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;
|
||||
stroke-linecap:round;stroke-linejoin:round}
|
||||
.ic .f{fill:currentColor;stroke:none}
|
||||
.ab{height:64px;flex:none;display:flex;align-items:center;padding:0 4px;position:relative}
|
||||
.ab .nav{width:48px;height:48px;display:flex;align-items:center;justify-content:center;color:var(--onSurface)}
|
||||
.ab .t{position:absolute;left:56px;right:56px;text-align:center;font-size:21px;color:var(--onSurface)}
|
||||
.lv{flex:1;min-height:0;overflow:hidden}
|
||||
.lv.p16{padding:16px}
|
||||
.tile{display:flex;align-items:center;gap:16px;padding:10px 16px;min-height:56px}
|
||||
.tile.two{min-height:72px}
|
||||
.tile .lead{flex:none;color:var(--onSurfaceVar)}
|
||||
.tile .txt{flex:1;min-width:0}
|
||||
.tile .ti{font-size:15.5px;color:var(--onSurface);line-height:1.3}
|
||||
.tile .ts{font-size:13px;color:var(--onSurfaceVar);line-height:1.35;margin-top:3px}
|
||||
.tile .tr{flex:none;color:var(--onSurfaceVar)}
|
||||
.tile .btn{flex:none;font-size:14px;font-weight:500;color:var(--primary);padding:10px 8px 10px 12px}
|
||||
.tile.sel{background:var(--secCont)}
|
||||
.tile.sel .ti,.tile.sel .lead,.tile.sel .ts,.tile.sel .tr{color:var(--onSecCont)}
|
||||
.dv{height:1px;background:var(--outlineVar)}
|
||||
.mcard{background:var(--cardBg);border-radius:12px;box-shadow:0 1px 3px rgba(0,0,0,.10);overflow:hidden;margin-bottom:16px}
|
||||
.lbl{font-size:13px;color:var(--onSurfaceVar);padding:14px 16px 8px}
|
||||
.segwrap{padding:0 16px 14px}
|
||||
.seg{display:grid;border:1px solid var(--outline);border-radius:20px;overflow:hidden;height:40px}
|
||||
.seg.c3{grid-template-columns:repeat(3,minmax(0,1fr))} .seg.c2{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.seg>div{display:flex;align-items:center;justify-content:center;gap:5px;font-size:13.5px;
|
||||
color:var(--onSurface);border-right:1px solid var(--outline);white-space:nowrap}
|
||||
.seg>div:last-child{border-right:0}
|
||||
.seg>div.on{background:var(--secCont);color:var(--onSecCont)}
|
||||
.seg .ck{width:17px;height:17px;flex:none}
|
||||
.ic-ok{color:var(--ok)} .ic-am{color:var(--amber)} .ic-gr{color:var(--grey)}
|
||||
.badge{font-size:10.5px;color:#0a3d1a;background:#B7E6C4;border-radius:100px;padding:2px 8px;margin-left:8px;vertical-align:1px}
|
||||
.keep{font-size:10.5px;color:var(--onSurfaceVar);margin-left:8px}
|
||||
|
||||
.why{display:flex;flex-wrap:wrap;gap:18px}
|
||||
.why>div{width:436px;border-left:2px solid var(--sig);padding:2px 0 2px 13px}
|
||||
.why.red>div{border-left-color:var(--bad)}
|
||||
.why h4{font-size:14.5px;font-weight:600;color:var(--ink);margin-bottom:4px}
|
||||
.why p{font-size:12.5px;color:var(--dim);line-height:1.55}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>
|
||||
<symbol id="i-back" viewBox="0 0 24 24"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></symbol>
|
||||
<symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 5l7 7-7 7"/></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></symbol>
|
||||
<symbol id="i-pin" viewBox="0 0 24 24"><path d="M12 21.5S19 15 19 10a7 7 0 10-14 0c0 5 7 11.5 7 11.5z"/><circle cx="12" cy="10" r="2.6"/></symbol>
|
||||
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M12 6.8V12l3.6 2.1"/></symbol>
|
||||
<symbol id="i-gpsfix" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.4"/><circle class="f" cx="12" cy="12" r="2.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22"/></symbol>
|
||||
<symbol id="i-gpsoff" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22"/><path d="M4.5 19.5l15-15"/></symbol>
|
||||
<symbol id="i-pause" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M10.2 9.3v5.4M13.8 9.3v5.4"/></symbol>
|
||||
<symbol id="i-hour" viewBox="0 0 24 24"><path d="M7 3h10M7 21h10"/><path d="M7 3c0 4.2 5 5.9 5 9s-5 4.8-5 9"/><path d="M17 3c0 4.2-5 5.9-5 9s5 4.8 5 9"/></symbol>
|
||||
<symbol id="i-badge" viewBox="0 0 24 24"><rect x="3.2" y="6" width="17.6" height="14.4" rx="2.4"/><path d="M9 6V4.6A1.4 1.4 0 0110.4 3.2h3.2A1.4 1.4 0 0115 4.6V6"/><circle cx="12" cy="11.6" r="2.2"/><path d="M8.4 17.6c.7-1.5 2-2.2 3.6-2.2s2.9.7 3.6 2.2"/></symbol>
|
||||
<symbol id="i-ant" viewBox="0 0 24 24"><circle cx="12" cy="6.4" r="2.8"/><path d="M12 9.2V21M7.5 21h9"/><path d="M6.6 10.4a7.6 7.6 0 0110.8 0"/><path d="M4.2 7.6a11 11 0 0115.6 0"/></symbol>
|
||||
<symbol id="i-sensor" viewBox="0 0 24 24"><circle class="f" cx="12" cy="12" r="2.2"/><path d="M8.3 8.3a5.2 5.2 0 000 7.4M15.7 8.3a5.2 5.2 0 010 7.4"/><path d="M5.6 5.6a9 9 0 000 12.8M18.4 5.6a9 9 0 010 12.8"/></symbol>
|
||||
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.2l7.2 2.9v5.6c0 4.5-3 7.9-7.2 9.1-4.2-1.2-7.2-4.6-7.2-9.1V6.1z"/></symbol>
|
||||
<symbol id="i-contacts" viewBox="0 0 24 24"><rect x="3.2" y="5.2" width="17.6" height="13.6" rx="2.2"/><circle cx="9.2" cy="10.8" r="2.3"/><path d="M5.8 16.4c.7-1.7 1.9-2.4 3.4-2.4s2.7.7 3.4 2.4"/><path d="M15.2 10h3.4M15.2 13.6h3.4"/></symbol>
|
||||
<symbol id="i-block" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M6 18L18 6"/></symbol>
|
||||
<symbol id="i-sms" viewBox="0 0 24 24"><path d="M20.8 15.2a2 2 0 01-2 2H8l-4.8 4V5a2 2 0 012-2h13.6a2 2 0 012 2z"/><circle class="f" cx="8.4" cy="10.4" r="1.1"/><circle class="f" cx="12" cy="10.4" r="1.1"/><circle class="f" cx="15.6" cy="10.4" r="1.1"/></symbol>
|
||||
<symbol id="i-tune" viewBox="0 0 24 24"><path d="M3.6 7h12M18.4 7h2M3.6 12h4M10 12h10.4M3.6 17h10M16 17h4.4"/><circle cx="16.8" cy="7" r="2"/><circle cx="8.6" cy="12" r="2"/><circle cx="14.6" cy="17" r="2"/></symbol>
|
||||
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M12 11.2v5"/><circle class="f" cx="12" cy="7.9" r="1"/></symbol>
|
||||
<symbol id="i-person" viewBox="0 0 24 24"><circle cx="12" cy="8" r="3.6"/><path d="M4.8 20c1.5-3.6 4-5.2 7.2-5.2s5.7 1.6 7.2 5.2"/></symbol>
|
||||
<symbol id="i-radiobtn" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><circle class="f" cx="12" cy="12" r="4"/></symbol>
|
||||
<symbol id="i-bell" viewBox="0 0 24 24"><path d="M18.4 16.4V11a6.4 6.4 0 10-12.8 0v5.4l-1.8 1.9h16.4z"/><path d="M10 20.2a2.2 2.2 0 004 0"/></symbol>
|
||||
<symbol id="i-vol" viewBox="0 0 24 24"><path d="M4 9.2v5.6h3.6l5 4.2V5L7.6 9.2z"/><path d="M15.8 9.4a3.8 3.8 0 010 5.2M18.4 6.8a7.6 7.6 0 010 10.4"/></symbol>
|
||||
</defs></svg>
|
||||
|
||||
<h1>Location screen and settings restructure (client #969, epic #975)</h1>
|
||||
<p class="lede">Material 3 blue seed, light, drawn at 390×844 against the real widgets: <code>SettingsShell</code> renders each category as a <code>ListTile</code> with a leading <code>Icon</code>, a subtitle and a trailing chevron under a centred <code>AppBar</code>, and detail panes are <code>Card</code>s of <code>ListTile</code>s split by <code>Divider(height: 1)</code>. Icon choices match <code>settings_screen.dart</code>; they are drawn here as inline SVG so this file needs no network to render. Values are examples; <b>the bullets are the behavior to build</b>. GPS mode rides firmware <code>0xC5</code> sub-codes <code>0x0D</code> / <code>0x0E</code>, gated on caps byte 2 <code>0x20</code> (meshcore-firmware#1789). <span class="flag">Owner-approved 2026-10-23</span> <b>Approved as drawn:</b> one three-way GPS control above the coordinates, one consolidated status row between them, Location as a top-level category under Radio Settings, Radio stats unchanged for now, and button and buzzer split across Node Settings and Message Settings. <b>Corrected 2026-10-24:</b> wire facts only (the command is <code>0xC5</code>, not a new <code>0xC7</code>; the buzzer-only example boards; the sleep-interval floor). The design is unchanged.</p>
|
||||
|
||||
<h3>The Location screen, one control and three states</h3><div class="grid">
|
||||
|
||||
<div class="card"><h2><span class="n">1</span>GPS off</h2><p>The selector is the only on/off control. The status row goes quiet and the sleep row is gone, because neither has meaning here.</p>
|
||||
<div class="dev d-loc"><div class="scr s-loc">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
|
||||
<div class="lv p16">
|
||||
<div class="mcard">
|
||||
<div class="lbl">GPS</div>
|
||||
<div class="segwrap"><div class="seg c3"><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>Off</div><div>On</div><div>Power save</div></div></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead ic-gr"><svg class="ic"><use href="#i-gpsoff"/></svg></span><div class="txt"><div class="ti">GPS is off</div><div class="ts">Showing the last stored position</div></div><span class="btn">Query</span></div>
|
||||
</div>
|
||||
<div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div>
|
||||
</div></div></div>
|
||||
<ul><li>Off writes <code>gps.en = 0</code> and <b>leaves the mode byte untouched</b>, matching <code>gpsStoredModeForPick</code>.</li><li>So Off then On returns to Power save, not to continuous On. That property is why this is one control and not two.</li><li>Coordinates stay editable with GPS off; they are the manual fallback.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">2</span>GPS on</h2><p>Continuous acquisition. The sleep row stays hidden: it governs Power save only, and a dead row invites someone to set it.</p>
|
||||
<div class="dev d-loc"><div class="scr s-loc">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
|
||||
<div class="lv p16">
|
||||
<div class="mcard">
|
||||
<div class="lbl">GPS</div>
|
||||
<div class="segwrap"><div class="seg c3"><div>Off</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>On</div><div>Power save</div></div></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead ic-ok"><svg class="ic"><use href="#i-gpsfix"/></svg></span><div class="txt"><div class="ti">GPS is on</div><div class="ts">Fix 2 minutes ago, 3 satellites</div></div><span class="btn">Query</span></div>
|
||||
</div>
|
||||
<div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div>
|
||||
</div></div></div>
|
||||
<ul><li>On writes <code>gps.en = 1</code> and <code>gps.mode = 1</code> together, the way <code>setGpsMode()</code> does on the device.</li><li>A stored <code>0xFF</code> (never set) also displays as On, per <code>gpsModeFromPrefs</code>.</li><li>This is the costly state: about 48 mA, roughly 1.8 days on a 3000 mAh cell against 6.8 days with GPS off.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">3</span>Power save, backed off</h2><p>The state a badge at an event actually sits in. One status row carries activity, next attempt and last fix, so nothing is said twice.</p>
|
||||
<div class="dev d-loc"><div class="scr s-loc">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
|
||||
<div class="lv p16">
|
||||
<div class="mcard">
|
||||
<div class="lbl">GPS</div>
|
||||
<div class="segwrap"><div class="seg c3"><div>Off</div><div>On</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>Power save</div></div></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead ic-am"><svg class="ic"><use href="#i-pause"/></svg></span><div class="txt"><div class="ti">Backed off</div><div class="ts">Next try in 48 min, last fix 2 min ago</div></div><span class="btn">Query</span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-hour"/></svg></span><div class="txt"><div class="ti">Sleep between fix attempts</div><div class="ts">Firmware default, minimum 5 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div>
|
||||
<div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div>
|
||||
</div></div></div>
|
||||
<ul><li>Power save writes <code>gps.en = 1</code> and <code>gps.mode = 2</code>.</li><li><b>Backed off must be named.</b> Otherwise a user sees no fix and reads a working radio as broken. The firmware models five activity states and expects this to be the common one at an event.</li><li><b>0 is a legal value</b> meaning firmware default, so the reporting-interval rule that rejects anything under 60 must not be copied onto this field.</li><li>The radio raises 1 to 299 s to 300, because one fix attempt can run 180 s. The row shows the stored value from the reply, never what was typed.</li><li>No tuned default is offered: every measured indoor attempt at 30 minutes and beyond failed to acquire (firmware #1553).</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">4</span>A build that cannot do Power save</h2><p>Most variants do not compile the duty cycle. The third option is absent rather than offered and ignored.</p>
|
||||
<div class="dev d-loc"><div class="scr s-loc">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
|
||||
<div class="lv p16">
|
||||
<div class="mcard">
|
||||
<div class="lbl">GPS</div>
|
||||
<div class="segwrap"><div class="seg c2"><div>Off</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>On</div></div></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead ic-ok"><svg class="ic"><use href="#i-gpsfix"/></svg></span><div class="txt"><div class="ti">GPS is on</div><div class="ts">Fix 2 minutes ago, 3 satellites</div></div><span class="btn">Query</span></div>
|
||||
</div>
|
||||
<div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div>
|
||||
</div></div></div>
|
||||
<ul><li><code>OFFBAND_GPS_POWER_SAVE</code> is opt-in per variant and today is set <b>only on the QCC badge</b>.</li><li>The device guards its own screen with <code>gpsPowerSaveAvailable()</code> so it never offers a mode nothing drives. The client needs the same signal.</li><li>Firmware sends it as <code>ps_ok</code> in every GPS reply, so Power save is hidden per radio rather than per firmware version. The caps bit <code>0x20</code> alone would not do: a radio can speak the GPS sub-codes without the duty cycle.</li></ul></div>
|
||||
|
||||
</div>
|
||||
|
||||
<h3>Where it lives</h3><div class="grid">
|
||||
|
||||
<div class="card" style="width:688px"><h2><span class="n">5</span>Settings, current and proposed</h2><p>GPS sits two levels down today, inside Node Settings then the Location dialog, with its enable toggle duplicated in both. Location becomes its own category and owns GPS outright.</p>
|
||||
<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px">
|
||||
|
||||
<div><div class="sub">Current</div>
|
||||
<div class="dev d-set"><div class="scr s-set">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Settings</span></div>
|
||||
<div class="lv">
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-badge"/></svg></span><div class="txt"><div class="ti">Node Settings</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-ant"/></svg></span><div class="txt"><div class="ti">Radio Settings</div><div class="ts">Frequency, power, spreading factor</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sensor"/></svg></span><div class="txt"><div class="ti">Radio stats</div><div class="ts">Noise floor, RSSI, SNR, and airtime</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-shield"/></svg></span><div class="txt"><div class="ti">Privacy Settings</div><div class="ts">Control what information is shared.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-contacts"/></svg></span><div class="txt"><div class="ti">Contacts</div><div class="ts">Settings for how contacts are added.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-block"/></svg></span><div class="txt"><div class="ti">Blocked</div><div class="ts">Users you've blocked</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sms"/></svg></span><div class="txt"><div class="ti">Message Settings</div><div class="ts">Notifications and message handling</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-tune"/></svg></span><div class="txt"><div class="ti">App Settings</div><div class="ts">Appearance, translation, and map preferences</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-info"/></svg></span><div class="txt"><div class="ti">Device Info</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div></div></div>
|
||||
|
||||
<div><div class="sub">Proposed</div>
|
||||
<div class="dev d-set"><div class="scr s-set">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Settings</span></div>
|
||||
<div class="lv">
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-badge"/></svg></span><div class="txt"><div class="ti">Node Settings</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-ant"/></svg></span><div class="txt"><div class="ti">Radio Settings</div><div class="ts">Frequency, power, spreading factor</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Location<span class="badge">new</span></div><div class="ts">GPS, coordinates, and reporting</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sensor"/></svg></span><div class="txt"><div class="ti">Radio stats<span class="keep">unchanged for now</span></div><div class="ts">Noise floor, RSSI, SNR, and airtime</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-shield"/></svg></span><div class="txt"><div class="ti">Privacy Settings</div><div class="ts">Control what information is shared.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-contacts"/></svg></span><div class="txt"><div class="ti">Contacts</div><div class="ts">Settings for how contacts are added.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-block"/></svg></span><div class="txt"><div class="ti">Blocked</div><div class="ts">Users you've blocked</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sms"/></svg></span><div class="txt"><div class="ti">Message Settings</div><div class="ts">Notifications and message handling</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-tune"/></svg></span><div class="txt"><div class="ti">App Settings</div><div class="ts">Appearance, translation, and map preferences</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-info"/></svg></span><div class="txt"><div class="ti">Device Info</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div></div></div>
|
||||
|
||||
</div>
|
||||
<ul><li>Location sits directly under Radio Settings and becomes the single home for GPS. The duplicate enable toggle in Node Settings goes away.</li><li>Radio stats stays for now by owner decision, to be revisited (#980). It is also reachable from the app-bar icon.</li><li>Category order otherwise unchanged; Observer still appears conditionally and is not drawn here.</li></ul></div>
|
||||
|
||||
<div class="card" style="width:688px"><h2><span class="n">6</span>Button and buzzer split across two panes</h2><p>One entry today, shown on button matrix or notify scope together. Boards such as the M5Stack Unit C6L, ThinkNode M9 and Wio Tracker L1 e-ink have a buzzer and no button, so they are not one feature.</p>
|
||||
<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px">
|
||||
|
||||
<div><div class="sub">Node Settings keeps the button</div>
|
||||
<div class="dev d-pan"><div class="scr s-pan">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Node Settings</span></div>
|
||||
<div class="lv p16"><div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-person"/></svg></span><div class="txt"><div class="ti">Node name</div><div class="ts">Strycher</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-radiobtn"/></svg></span><div class="txt"><div class="ti">Button actions</div><div class="ts">Assign what the button does</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div>
|
||||
</div></div></div>
|
||||
|
||||
<div><div class="sub">Message Settings gains the buzzer</div>
|
||||
<div class="dev d-pan"><div class="scr s-pan">
|
||||
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Message Settings</span></div>
|
||||
<div class="lv p16"><div class="mcard">
|
||||
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-bell"/></svg></span><div class="txt"><div class="ti">Notifications</div><div class="ts">When this phone alerts you</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-vol"/></svg></span><div class="txt"><div class="ti">Buzzer and tones<span class="badge">new</span></div><div class="ts">When this radio beeps, and which tone</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div>
|
||||
</div></div></div>
|
||||
|
||||
</div>
|
||||
<ul><li>Button actions stay under Node Settings. Buzzer and tones move beside Notifications, which Message Settings already advertises in its subtitle.</li><li>Split apart, each half needs its own capability gate: a buzzer-only radio must show tones and hide button actions.</li><li>Gates: Button actions on caps byte 2 <code>0x02</code>, Buzzer and tones on <code>0x01</code>. Firmware already sets the two independently, and the screen already shows each half from its own bit; what changes is the entry and where it lives.</li></ul></div>
|
||||
|
||||
</div>
|
||||
|
||||
<h3>Why these choices, so a later change knows what it is breaking</h3>
|
||||
<div class="why">
|
||||
<div><h4>One three-way control, not a toggle plus a picker</h4><p>The badge's own screen does exactly this: <code>setGpsMode()</code> at <code>MyMesh.h:458</code> writes both fields, and <code>gpsEnabledForMode</code> exists for the writer that sets both. What is forbidden is a bool-only writer clobbering the mode byte. An earlier draft had two controls and was wrong; #969's original wording pointed that way.</p></div>
|
||||
<div><h4>One status row, not two</h4><p>Activity and last fix were separate blocks in the first draft. In a dense app that is one job taking two slots, so they are merged into a single <code>ListTile</code> between the selector and the coordinates.</p></div>
|
||||
<div><h4>Sleep interval is not the reporting interval</h4><p><code>gps_interval</code> is a reporting cadence; <code>gps_ps_interval_s</code> is a power duty cycle (<code>NodePrefs.h:73-78</code>). They live in different cards so the difference is visible, and are never merged.</p></div>
|
||||
<div><h4>Deferred, tracked separately</h4><p>GPS fix state in the Channels and Contacts headers is #974; it lands in the same shared app-bar widget as epic #613, so it must follow #614 rather than run beside it. Where Radio stats lives is #980.</p></div>
|
||||
</div>
|
||||
<div class="why red" style="margin-top:18px">
|
||||
<div><h4>The save reply must echo what was stored</h4><p>The client renders the device's answer, never its own assumption. Choosing Off does not change the stored mode byte, so a client modelling its own write would show the wrong mode. Clamping has the same shape: the reporting interval is already constrained to 0 through 86400, so the user must see the clamped value, not what they typed. Delivered: the <code>0xC5</code> GPS reply carries the stored values after every write.</p></div>
|
||||
<div><h4>Power save is hidden where the build cannot drive it</h4><p><code>OFFBAND_GPS_POWER_SAVE</code> is per variant and currently only on the QCC badge. The GPS reply's <code>ps_ok</code> byte says whether this radio can run it; without that, the client would offer a mode that does nothing.</p></div>
|
||||
</div>
|
||||
|
||||
</body></html>
|
||||
@ -0,0 +1,362 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Badge settings parity mockups</title>
|
||||
<style>
|
||||
/* Doc chrome: Offband design-doc family. Inside the frames: Flutter Material 3,
|
||||
drawn against the real widgets: the Node Settings card in settings_screen.dart
|
||||
(_identityPane), DeviceUiView(part: buzzer) under the "Buzzer and tones" Scaffold
|
||||
from message_settings_view.dart, the check-list dialog in
|
||||
widgets/channel_notify_mode.dart, and the persistent _ErrorBanner.
|
||||
Self-contained: inline SVG icons, system fonts, no network. */
|
||||
:root{
|
||||
--ink:#EFF3E8; --ink2:#BAC4B5; --dim:#8B9A91; --sig:#7BEFA8; --warn:#FFA552; --bad:#FF7A6E;
|
||||
--sans:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;
|
||||
--mono:'Cascadia Mono',Consolas,'SF Mono',Menlo,monospace;
|
||||
--page:#0a0d0c; --pageInk:#cfd6cc;
|
||||
--surface:#FDFBFF; --onSurface:#1A1C1E; --onSurfaceVar:#44474F;
|
||||
--outline:#74777F; --outlineVar:#C4C6D0; --primary:#0061A4; --onPrimary:#FFFFFF;
|
||||
--secC:#D6E3FF; --onSecC:#001D36; --cardBg:#F3F3FA;
|
||||
--dialog:#F1EDF5; --scrim:rgba(0,0,0,.40);
|
||||
--errC:#FFDAD6; --onErrC:#410002; --red:#BA1A1A; --track:#D1E4FF;
|
||||
}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 56px}
|
||||
h1{font-size:25px;font-weight:600;color:var(--ink)}
|
||||
h3{font-size:17px;font-weight:600;color:var(--sig);margin:32px 0 12px}
|
||||
.lede{font-size:14px;color:var(--dim);margin:8px 0 4px;max-width:1040px;line-height:1.55}
|
||||
.lede b{color:var(--ink2);font-weight:500}
|
||||
code{font-family:var(--mono);font-size:11.5px;color:var(--sig)}
|
||||
.flag{display:inline-block;font-family:var(--mono);font-size:10.5px;font-weight:600;color:#0a0d0c;background:var(--sig);border-radius:3px;padding:2px 7px}
|
||||
table.par{border-collapse:collapse;font-size:12.5px;max-width:1040px;width:100%;margin-top:4px}
|
||||
.par th{text-align:left;color:var(--ink);font-weight:600;padding:7px 10px;border-bottom:1px solid #2a332f}
|
||||
.par td{color:var(--ink2);padding:6px 10px;border-bottom:1px solid #1b2220;vertical-align:top;line-height:1.4}
|
||||
.par td.ok{color:var(--sig)} .par td.new{color:var(--warn)}
|
||||
.par code{color:var(--ink2)}
|
||||
.grid{display:flex;flex-wrap:wrap;gap:30px}
|
||||
.card{width:324px}
|
||||
.card h2{font-size:17px;font-weight:600;color:var(--ink)}
|
||||
.card .n{font-family:var(--mono);font-size:12px;color:var(--sig);margin-right:7px}
|
||||
.card>p{font-size:13.5px;color:var(--ink2);margin:5px 0 12px;line-height:1.45;min-height:58px}
|
||||
.card ul{font-size:12.5px;color:var(--dim);margin:12px 0 0 16px;line-height:1.5}
|
||||
.card li{margin-bottom:5px}
|
||||
.card ul b{color:var(--ink2);font-weight:500}
|
||||
.dev{width:324px;height:620px;border:1px solid #2a332f;border-radius:14px;overflow:hidden;background:#000}
|
||||
.scr{width:390px;height:746px;transform:scale(.8308);transform-origin:0 0;background:var(--surface);color:var(--onSurface);
|
||||
font-family:'Segoe UI',system-ui,Roboto,sans-serif;position:relative;overflow:hidden}
|
||||
.ic{width:24px;height:24px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
|
||||
.ic .f{fill:currentColor;stroke:none}
|
||||
.ab{height:64px;display:flex;align-items:center;padding:0 4px;font-size:21px}
|
||||
.ab .bk{width:48px;height:48px;display:flex;align-items:center;justify-content:center}
|
||||
.ab .tt{flex:1;text-align:center;margin-right:48px}
|
||||
.pad{padding:16px}
|
||||
.mcard{background:var(--cardBg);border-radius:12px;overflow:hidden}
|
||||
.sh{font-size:16px;font-weight:500;padding:16px 16px 4px}
|
||||
.ex{font-size:14px;padding:0 16px 8px;line-height:1.4}
|
||||
.tile{display:flex;align-items:center;gap:16px;padding:8px 16px;min-height:56px}
|
||||
.tile .lead{flex:none;color:var(--onSurfaceVar)}
|
||||
.tile .lead.on{color:var(--primary)}
|
||||
.tile .txt{flex:1;min-width:0}
|
||||
.tile .ti{font-size:15.5px;line-height:1.3}
|
||||
.tile .ts{font-size:13px;color:var(--onSurfaceVar);margin-top:2px;line-height:1.35}
|
||||
.tile .tr{flex:none;color:var(--onSurfaceVar)}
|
||||
.tile .tr.pr{color:var(--primary)}
|
||||
.tile.sel .ti,.tile.sel .ts{color:var(--primary)}
|
||||
.tile.empty .ti{color:var(--onSurfaceVar)}
|
||||
.tile.new{background:#E8DEF8}
|
||||
.dv{height:1px;background:var(--outlineVar)}
|
||||
.scrim{position:absolute;inset:0;background:var(--scrim)}
|
||||
.dlg{position:absolute;left:24px;right:24px;top:60px;background:var(--dialog);border-radius:28px;padding:22px 0 10px}
|
||||
.dlg .dt{font-size:22px;padding:0 24px 4px}
|
||||
.dlg .ds{font-size:13.5px;color:var(--onSurfaceVar);padding:0 24px 10px;line-height:1.4}
|
||||
.dlg .sec{font-size:12.5px;color:var(--onSurfaceVar);padding:10px 24px 2px;letter-spacing:.2px}
|
||||
.dlg .tile{padding:4px 12px 4px 24px;min-height:46px}
|
||||
.dlg .acts{display:flex;justify-content:flex-end;padding:8px 24px 6px;gap:8px}
|
||||
.snack{position:absolute;left:12px;right:12px;bottom:16px;background:#322F35;color:#F5EFF7;border-radius:4px;padding:14px 16px;font-size:14px;line-height:1.4;display:flex;gap:12px;align-items:center}
|
||||
.snack .a{color:#9ECAFF;font-weight:500;flex:none}
|
||||
.seg{display:flex;margin:4px 16px 8px;border:1px solid var(--outline);border-radius:20px;overflow:hidden;height:40px}
|
||||
.seg>span{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;font-size:13.5px;font-weight:500;border-left:1px solid var(--outline)}
|
||||
.seg>span:first-child{border-left:none}
|
||||
.seg>span.on{background:var(--secC);color:var(--onSecC)}
|
||||
.seg .ic{width:18px;height:18px}
|
||||
.lab2{font-size:14px;padding:6px 16px 0;color:var(--onSurfaceVar)}
|
||||
.fld{margin:8px 16px 0;border:1px solid var(--outline);border-radius:4px;padding:10px 12px;position:relative;min-height:150px}
|
||||
.fld.focus{border:2px solid var(--primary);padding:9px 11px}
|
||||
.fld .lab{position:absolute;top:-9px;left:9px;background:var(--surface);padding:0 4px;font-size:12px;color:var(--onSurfaceVar)}
|
||||
.fld.focus .lab{color:var(--primary)}
|
||||
.fld .val{font-family:var(--mono);font-size:13.5px;line-height:1.5;word-break:break-all}
|
||||
.help{display:flex;justify-content:space-between;font-size:12px;color:var(--onSurfaceVar);padding:4px 28px 0}
|
||||
.row{display:flex;gap:8px;justify-content:flex-end;padding:16px 16px 0}
|
||||
.btn{height:40px;border-radius:20px;padding:0 22px;font-size:14px;font-weight:500;display:inline-flex;align-items:center;gap:8px}
|
||||
.btn.fill{background:var(--primary);color:var(--onPrimary)}
|
||||
.btn.tonal{background:var(--secC);color:var(--onSecC)}
|
||||
.btn.outl{border:1px solid var(--outline);color:var(--primary)}
|
||||
.btn.text{color:var(--primary);padding:0 12px}
|
||||
.btn.text.red{color:var(--red)}
|
||||
.btn .ic{width:18px;height:18px}
|
||||
.ban{display:flex;align-items:center;gap:12px;margin:12px;padding:12px;border-radius:8px;background:var(--errC);color:var(--onErrC);font-size:14px;line-height:1.4}
|
||||
.ban .x{flex:none;width:40px;height:40px;display:flex;align-items:center;justify-content:center}
|
||||
.lin{height:4px;background:var(--track);margin:14px 16px 6px;border-radius:2px;overflow:hidden}
|
||||
.lin>div{height:100%;background:var(--primary)}
|
||||
.prog{font-size:13px;color:var(--onSurfaceVar);padding:0 16px}
|
||||
.srch{margin:4px 16px 8px;height:48px;border-radius:24px;background:#ECE6F0;display:flex;align-items:center;gap:12px;padding:0 16px;color:var(--onSurfaceVar);font-size:15px}
|
||||
.big{font-size:32px;font-weight:400;padding:8px 16px 0}
|
||||
.why{display:flex;flex-wrap:wrap;gap:18px}
|
||||
.why>div{width:436px;border-left:2px solid var(--sig);padding:2px 0 2px 13px}
|
||||
.why h4{font-size:14.5px;font-weight:600;color:var(--ink);margin-bottom:4px}
|
||||
.why p{font-size:12.5px;color:var(--dim);line-height:1.55}
|
||||
.why code{color:var(--ink2)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>
|
||||
<symbol id="i-back" viewBox="0 0 24 24"><path d="M20 12H5M11 5l-7 7 7 7"/></symbol>
|
||||
<symbol id="i-rad-on" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle class="f" cx="12" cy="12" r="5"/></symbol>
|
||||
<symbol id="i-rad-off" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></symbol>
|
||||
<symbol id="i-note" viewBox="0 0 24 24"><path d="M9 18V5.5l11-2.2V16"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="17.5" cy="16" r="2.5"/></symbol>
|
||||
<symbol id="i-mute" viewBox="0 0 24 24"><path d="M4 9.2v5.6h3.6l5 4.2V5L7.6 9.2z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/></symbol>
|
||||
<symbol id="i-follow" viewBox="0 0 24 24"><path d="M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"/><path d="M18 3.5v3.4h-3.4M6 20.5v-3.4h3.4"/></symbol>
|
||||
<symbol id="i-play" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path class="f" d="M10 8.3v7.4l5.8-3.7z"/></symbol>
|
||||
<symbol id="i-add" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" stroke-dasharray="3 2.4"/><path d="M12 8v8M8 12h8"/></symbol>
|
||||
<symbol id="i-chev" viewBox="0 0 24 24"><path d="M9.5 6l6 6-6 6"/></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></symbol>
|
||||
<symbol id="i-err" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5"/><circle class="f" cx="12" cy="16.3" r="1.1"/></symbol>
|
||||
<symbol id="i-close" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18"/></symbol>
|
||||
<symbol id="i-person" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.8"/><path d="M4.5 20c.8-3.8 3.8-5.8 7.5-5.8s6.7 2 7.5 5.8"/></symbol>
|
||||
<symbol id="i-btn" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4.2"/></symbol>
|
||||
<symbol id="i-monitor" viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="12" rx="1.5"/><path d="M9 20h6M12 16.5V20"/></symbol>
|
||||
<symbol id="i-batt" viewBox="0 0 24 24"><rect x="7" y="4.5" width="10" height="16.5" rx="1.8"/><path d="M10 2.8h4"/><path class="f" d="M9 9h6v10H9z"/></symbol>
|
||||
<symbol id="i-globe" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.6 2.6 3.8 5.6 3.8 9s-1.2 6.4-3.8 9c-2.6-2.6-3.8-5.6-3.8-9S9.4 5.6 12 3z"/></symbol>
|
||||
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5 5"/></symbol>
|
||||
<symbol id="i-phone" viewBox="0 0 24 24"><rect x="6.5" y="2.8" width="11" height="18.4" rx="2"/><path d="M10.5 18h3"/></symbol>
|
||||
<symbol id="i-bolt" viewBox="0 0 24 24"><path d="M13 3L5 13.5h6L10 21l8-10.5h-6z"/></symbol>
|
||||
</defs></svg>
|
||||
|
||||
<h1>Badge settings, reachable from the app (client #970, #971, #975)</h1>
|
||||
<p class="lede">Material 3 blue seed, light, drawn at 390×844 against the real widgets. Wire: <code>0xC5</code> as of meshcore-firmware <code>3e788e2a</code> (#1801, branch <code>epic/1788-client-settings</code>, running on QCC2), read 2026-10-25 in <code>OffbandConfigProtocol.h</code>; badge screens read in <code>BadgeScreens.cpp</code>, <code>BadgeLayout.h</code>, <code>TimeZones.h</code>, <code>BatteryGauge.h</code> at the same commit. Supersedes the #970 slot mockup sent 2026-10-24. Values are examples; <b>the bullets are the behavior to build</b>. Built under #970, #971, #986 and #987. <span class="flag">APPROVED 2026-10-25</span></p>
|
||||
|
||||
<h3>The badge's screens against the app</h3>
|
||||
<table class="par">
|
||||
<tr><th>Badge screen and row</th><th>Wire (0xC5 sub-code, caps byte 2)</th><th>App before</th><th>App after this</th></tr>
|
||||
<tr><td>Tones › Sound (All, Self, None)</td><td><code>0x01/0x02</code>, <code>0x01</code></td><td class="ok">Buzzer and tones</td><td>unchanged (frame 2)</td></tr>
|
||||
<tr><td>Tones › DM, Channel, Room, New contact, Ack, Sent</td><td><code>0x0F/0x10</code> EVTONE, <code>0x10</code></td><td class="new">missing</td><td>six rows + picker (frames 2, 4)</td></tr>
|
||||
<tr><td>Each picker: Silent, Chime, Kerplop, Tick, Bloop, Drop, Knock, filled slots</td><td>same "picker's rule" on every set</td><td class="new">missing</td><td>one shared picker (frames 4, 7)</td></tr>
|
||||
<tr><td>Picker plays each tune as you move</td><td><code>0x11</code> TUNE_PLAY, <code>0x10</code></td><td class="new">missing</td><td>play button per row (frames 3, 4, 5)</td></tr>
|
||||
<tr><td>Tones › Custom: all eight slots, named or "(empty)"</td><td><code>0x09</code> SLOT_GET, <code>0x10</code></td><td class="new">missing</td><td>slot list (frame 3)</td></tr>
|
||||
<tr><td>Custom › edit a slot (keyboard)</td><td><code>0x12</code> SLOT_READ + <code>0x0A</code> SLOT_SET, <code>0x10</code></td><td class="new">missing</td><td>editor, prefilled (frame 6)</td></tr>
|
||||
<tr><td>Channel's own tone, with Default</td><td><code>0x0B/0x0C</code> CHTUNE, <code>0x10</code></td><td class="new">codec built, no screen</td><td>"Radio tone" in the channel sheet (frame 7)</td></tr>
|
||||
<tr><td>Settings › Nav text, Message text</td><td><code>0x13</code> GET, <code>0x14</code> TEXT_SET, <code>0x40</code></td><td class="new">missing</td><td>Screen page (frame 8)</td></tr>
|
||||
<tr><td>Settings › Screen off (15 s, 30 s, 1 m, 2 m, 5 m)</td><td><code>0x15</code> SCROFF_SET, <code>0x40</code></td><td class="new">missing</td><td>Screen page (frame 8)</td></tr>
|
||||
<tr><td>Settings › Time zone (40 zones plus "not set", which shows ages)</td><td><code>0x16</code> TZ_SET, <code>0x40</code></td><td class="new">missing</td><td>zone list (frame 9)</td></tr>
|
||||
<tr><td>Settings › Battery: 100% point, Set 100% here, Back to auto</td><td><code>0x17</code> BATT_SET, <code>0x40</code></td><td class="new">missing</td><td>Battery page (frames 10, 11)</td></tr>
|
||||
<tr><td>Settings › GPS</td><td><code>0x0D/0x0E</code>, <code>0x20</code></td><td class="ok">Location (#977)</td><td>unchanged</td></tr>
|
||||
<tr><td>Settings › Hibernate, Device pages</td><td>not settings (AmberForge 1350): an action and a navigation</td><td>n/a</td><td>n/a</td></tr>
|
||||
</table>
|
||||
<p class="lede">One caps change to carry into the code already written: <code>0x10</code> is now <b>TUNES</b> (slots, channel tone, event tones, preview), not channel tone alone, and the slot sub-codes moved from the buzzer bit to it. A radio with a buzzer but no tune engine advertises <code>0x01</code> without <code>0x10</code> and keeps today's scope-only screen.</p>
|
||||
|
||||
<h3>Buzzer and tones</h3><div class="grid">
|
||||
|
||||
<div class="card"><h2><span class="n">1</span>Node Settings gains Screen and Battery</h2><p>The badge's own hardware settings sit with Button actions, gated on <code>0x40</code>. A radio without it shows today's card.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Node Settings</span></div>
|
||||
<div class="pad"><div class="mcard">
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-person"/></svg></span><div class="txt"><div class="ti">Node name</div><div class="ts">QCC2</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-btn"/></svg></span><div class="txt"><div class="ti">Button actions</div><div class="ts">Assign what the button does</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-monitor"/></svg></span><div class="txt"><div class="ti">Screen</div><div class="ts">Text size, screen off, time zone</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">Battery</div><div class="ts">100% at 4150 mV, learned</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="dv"></div>
|
||||
<div style="padding:8px 16px 12px"><div style="font-size:13px;color:var(--onSurfaceVar)">Public key</div><div style="font-family:var(--mono);font-size:12px;margin-top:2px">a1f3 07c2 9e44 … 5b10</div></div>
|
||||
</div></div>
|
||||
</div></div>
|
||||
<ul><li>Both rows appear only on a radio advertising caps byte 2 <code>0x40</code>. Today that means firmware built with the Offband screen set; a display fitted to a pyramid badge with that firmware gets them.</li><li>Battery's subtitle is the <code>SCREEN_GET</code> reply: the 100% point and where it came from, in the badge's words (default, learned, set).</li><li>Placement: owner decision 1.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">2</span>The scope, then the six tones</h2><p>The badge's Tones screen, in its order: Sound first, because nothing below can sound while it says None.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
|
||||
<div class="sh">Device notification scope</div>
|
||||
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">All</div><div class="ts">Beep for any received message</div></div></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Self</div><div class="ts">Beep only for direct messages and @[mentions]</div></div></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">None</div><div class="ts">Never beep</div></div></div>
|
||||
<div class="sh">Tones</div>
|
||||
<div class="ex">What this radio plays for each event.</div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">DM</div><div class="ts">Chime (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Channel</div><div class="ts">Kerplop (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Room</div><div class="ts">Mario</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">New contact</div><div class="ts">Bloop</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Ack</div><div class="ts">Silent</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Sent</div><div class="ts">Silent (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div>
|
||||
<ul><li>Labels are the badge's own (<code>kToneEventRows</code>): DM, Channel, Room, New contact, Ack, Sent. <b>DM is one tone for every direct message</b>; there is no per-contact choice (#983 withdrawn).</li><li>Each subtitle is the <code>effective</code> byte from <code>EVTONE_GET</code>. When <code>stored</code> is 0xFF it adds "(radio default)", so a choice and a default never look alike.</li><li>The tones section exists only with caps <code>0x10</code>. With <code>0x01</code> alone the screen is today's scope rows.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">3</span>Custom tunes, every slot</h2><p>Scrolled down. All eight slots are rows, as on the badge: an empty slot is where you go to fill one.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Sent</div><div class="ts">Silent (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
<div class="sh">Custom tunes</div>
|
||||
<div class="ex">Eight tunes stored on this radio, in RTTTL. A saved tune can be picked for any event or channel.</div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">1 Mario</div><div class="ts">142 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">2 Zelda</div><div class="ts">96 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">3 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
|
||||
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">4 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">5 Nokia</div><div class="ts">58 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">6 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
|
||||
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">7 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
|
||||
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">8 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
|
||||
</div></div>
|
||||
<ul><li>"1 Mario" / "3 (empty)" is the badge's own label shape. Names and lengths are <code>SLOT_GET</code> replies, one per slot, read when the screen opens.</li><li>The play button sends <code>TUNE_PLAY</code> with the slot's id (8 + slot). Empty slots have none: there is nothing to hear.</li><li>Tap a row to edit it (frame 6).</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">4</span>Pick a tone, hear it first</h2><p>One picker for all six events, with the badge's list. Play auditions on the radio; tapping the name chooses it.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
|
||||
<div class="scrim"></div>
|
||||
<div class="dlg">
|
||||
<div class="dt">DM tone</div>
|
||||
<div class="ds">Plays for every direct message.</div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Silent</div></div></div>
|
||||
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Chime</div><div class="ts">Now playing for DMs</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Kerplop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Tick</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Bloop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Drop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Knock</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="sec">Your tunes</div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Mario</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Zelda</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Nokia</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="acts"><span class="btn text">Cancel</span></div>
|
||||
</div>
|
||||
</div></div>
|
||||
<ul><li>The list is exactly what firmware accepts: the named built-ins (ids 0 to 6) and filled slots only. Empty slots are not offered, so a set is never refused for that.</li><li>Tapping a name sends <code>EVTONE_SET</code>; the dialog closes and the row changes only on the radio's reply, which carries stored and effective.</li><li><b>No Default row.</b> Firmware refuses 0xFF on an event, as the badge's own picker offers none (owner decision 3).</li><li>"Now playing" marks the effective tune, as the badge marks it "now".</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">5</span>Why a preview made no sound</h2><p>The radio says why it refused. The app says it in words, as the badge does with "Buzzer: OFF".</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
|
||||
<div class="sh">Device notification scope</div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">All</div><div class="ts">Beep for any received message</div></div></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Self</div><div class="ts">Beep only for direct messages and @[mentions]</div></div></div>
|
||||
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">None</div><div class="ts">Never beep</div></div></div>
|
||||
<div class="sh">Custom tunes</div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">1 Mario</div><div class="ts">142 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="snack"><span style="flex:1">Sound is off on this radio. Set the scope to All or Self to hear it.</span><span class="a">OK</span></div>
|
||||
</div></div>
|
||||
<ul><li><code>TUNE_PLAY</code> result 2 (sound off): this message, which stays until OK.</li><li>Result 1 (something more important is sounding): "The radio is playing a notification. Try again in a moment."</li><li>Result 0: nothing shown. The sound is the confirmation.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">6</span>Edit a slot, starting from what is there</h2><p>The editor reads the stored tune back first, so a filled slot opens with its text and can be changed, not only replaced.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Slot 1</span></div>
|
||||
<div style="height:10px"></div>
|
||||
<div class="fld focus"><span class="lab">RTTTL</span><div class="val">Mario:d=4,o=5,b=100:16e6,16e6,32p,8e6,16c6,8e6,8g6,8p,8g,8p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b</div></div>
|
||||
<div class="help"><span>Plays as "Mario"</span><span>142 / 240</span></div>
|
||||
<div class="row"><span class="btn text red">Clear slot</span><span class="btn outl"><svg class="ic"><use href="#i-play"/></svg>Play saved</span><span class="btn fill">Save</span></div>
|
||||
<div class="lin" style="margin-top:22px"><div style="width:100%"></div></div>
|
||||
<div class="prog">Read from the radio: 142 of 142 characters</div>
|
||||
</div></div>
|
||||
<ul><li>Opening sends <code>SLOT_READ</code> at offset 0, then again at offset + bytes while <code>more</code> is 1. The field is read-only and shows this bar until the read completes.</li><li>Typing is checked live with firmware's own <code>rtttlProblem()</code> and its words ("b= must be 1 or more"); Save stays disabled while there is a problem. Saving is the chunked <code>SLOT_SET</code>, then a re-read.</li><li><b>Play saved</b> plays what is on the radio, not unsaved typing: there is no command to play text that has not been saved. It is disabled while the text differs from the saved tune.</li><li>Clear sends the empty commit, after a confirm.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">7</span>A channel's tone names its Default</h2><p>The channel sheet's "Radio tone" picker (#971), now able to say what Default plays, the way the badge shows "Default Kerplop".</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="tt" style="margin:0 0 0 12px;text-align:left">Channels</span></div>
|
||||
<div class="scrim"></div>
|
||||
<div class="dlg">
|
||||
<div class="dt">Radio tone</div>
|
||||
<div class="ds">#okimesh</div>
|
||||
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-follow"/></svg></span><div class="txt"><div class="ti">Default</div><div class="ts">Kerplop, the radio's channel tone</div></div><span class="tr pr"><svg class="ic"><use href="#i-check"/></svg></span></div>
|
||||
<div class="dv" style="margin:4px 0"></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Silent</div></div></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Chime</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Kerplop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Tick</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Bloop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Drop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Knock</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="sec">Your tunes</div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Mario</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Zelda</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
|
||||
</div>
|
||||
</div></div>
|
||||
<ul><li>Same picker as frame 4 plus the Default row a conversation needs. Default writes stored 0; it is the only way to un-set a channel's tone.</li><li>Default's subtitle is the Channel event's <code>effective</code> tune from <code>EVTONE_GET</code> ev 1, so it names a real tune rather than "follows the radio".</li><li>Empty slots are hidden here too: firmware now refuses an empty slot for a channel (<code>3e788e2a</code>), which settles the first #971 question.</li><li>The row also sits in the channel chat screen's menu, from the same widget.</li></ul></div>
|
||||
|
||||
</div>
|
||||
|
||||
<h3>Screen and Battery</h3><div class="grid">
|
||||
|
||||
<div class="card"><h2><span class="n">8</span>Screen</h2><p>The badge's Nav text, Message text and Screen off rows, with the same choices and no others.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Screen</span></div>
|
||||
<div class="sh">Text size</div>
|
||||
<div class="lab2">Menus and lists</div>
|
||||
<div class="seg"><span class="on"><svg class="ic"><use href="#i-check"/></svg>Large</span><span>Medium</span><span>Small</span></div>
|
||||
<div class="lab2">Messages</div>
|
||||
<div class="seg"><span>Large</span><span class="on"><svg class="ic"><use href="#i-check"/></svg>Medium</span><span>Small</span></div>
|
||||
<div class="sh">Screen off</div>
|
||||
<div class="ex">How long the screen stays on after the last key press.</div>
|
||||
<div class="seg"><span>15 s</span><span>30 s</span><span class="on"><svg class="ic"><use href="#i-check"/></svg>1 m</span><span>2 m</span><span>5 m</span></div>
|
||||
<div class="sh">Time zone</div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-globe"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">UTC-4 now. Message times show as clock times.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
|
||||
</div></div>
|
||||
<ul><li>Every control is the <code>SCREEN_GET</code> reply; each change sends its SET and the controls redraw from the 14-byte re-read reply, never from the tap.</li><li>"Menus and lists" is the badge's Nav text, "Messages" its Message text (owner decision 4).</li><li>Screen off offers exactly the five steps firmware accepts. When <code>scr_stored</code> is 0 (compiled default), no segment is selected and the line reads "Board default: 1 m" from <code>scr_secs</code>; picking a step replaces it and there is no way back to 0, on the badge or here.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">9</span>Time zone</h2><p>The badge's 40 zones, its "not set", and a suggestion: the badge suggests from GPS, the app from the phone.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Time zone</span></div>
|
||||
<div class="srch"><svg class="ic"><use href="#i-search"/></svg>Search zones</div>
|
||||
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-phone"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">Matches this phone</div></div><span class="tr">UTC-4</span></div>
|
||||
<div class="dv"></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">not set</div><div class="ts">Messages show their age</div></div></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">UTC</div></div><span class="tr">UTC+0</span></div>
|
||||
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">Current</div></div><span class="tr">UTC-4</span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Central</div></div><span class="tr">UTC-5</span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Mountain</div></div><span class="tr">UTC-6</span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Arizona</div></div><span class="tr">UTC-7</span></div>
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Pacific</div></div><span class="tr">UTC-7</span></div>
|
||||
</div></div>
|
||||
<ul><li>The list is a copy of <code>TimeZones.h</code> <code>kZones</code>, in its order. AmberForge confirms it is append-only, so the index is stable; an index the app does not know is shown by number.</li><li>Offsets are computed with the zone's own daylight rule (US, EU, or none), as the badge's picker shows them.</li><li>"Matches this phone" picks the named zone whose rule and offset equal the phone's, else the fixed UTC offset, else nothing. It is a suggestion; tapping it sends <code>TZ_SET</code> like any row.</li><li>"not set" is storable (index 0), as on the badge.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">10</span>Battery</h2><p>The badge's Battery screen: where 100% is, how it got there, and its two actions.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Battery</span></div>
|
||||
<div class="big">96%</div>
|
||||
<div class="ex" style="padding-top:2px">Reading 4120 mV</div>
|
||||
<div class="pad" style="padding-top:8px"><div class="mcard">
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">100% at 4150 mV</div><div class="ts">Learned after a full charge</div></div></div>
|
||||
</div></div>
|
||||
<div class="ex">The radio learns where full is after a complete charge. Set it by hand only if the bar never reaches 100% when charged.</div>
|
||||
<div class="row" style="justify-content:flex-start"><span class="btn tonal"><svg class="ic"><use href="#i-bolt"/></svg>Set 100% here</span><span class="btn text">Back to auto</span></div>
|
||||
</div></div>
|
||||
<ul><li>The 100% point and its source (default, learned, set by hand) are the <code>batt_stored</code>, <code>batt_full</code> and <code>batt_pinned</code> bytes; the reading and percent are the battery report the app already receives.</li><li><b>Set 100% here</b> sends <code>BATT_SET 1</code>: the radio pins its own current reading, as the badge does. A confirm says "Only do this with the radio fully charged."</li><li><b>Back to auto</b> sends <code>BATT_SET 0</code>, shown only when something is learned or pinned.</li></ul></div>
|
||||
|
||||
<div class="card"><h2><span class="n">11</span>Refused, with the radio's reason</h2><p>The radio refuses a reading that is not a plausible full cell, and says which way it is wrong.</p>
|
||||
<div class="dev"><div class="scr">
|
||||
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Battery</span></div>
|
||||
<div class="ban"><svg class="ic"><use href="#i-err"/></svg><span style="flex:1">Not charged yet. Charge the radio fully, then set 100% again. Nothing was changed.</span><span class="x"><svg class="ic"><use href="#i-close"/></svg></span></div>
|
||||
<div class="big">71%</div>
|
||||
<div class="ex" style="padding-top:2px">Reading 3890 mV</div>
|
||||
<div class="pad" style="padding-top:8px"><div class="mcard">
|
||||
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">100% at 4200 mV</div><div class="ts">Default for this board</div></div></div>
|
||||
</div></div>
|
||||
<div class="row" style="justify-content:flex-start"><span class="btn tonal"><svg class="ic"><use href="#i-bolt"/></svg>Set 100% here</span></div>
|
||||
</div></div>
|
||||
<ul><li><code>ERR_BATT_NOT_CHARGED</code> (9): this message. <code>ERR_BATT_TOO_HIGH</code> (8): "The reading is higher than a full cell, so it was not used."</li><li>The existing persistent <code>_ErrorBanner</code>: it stays until dismissed.</li><li>Back to auto is absent: nothing is learned or pinned, matching the badge, which hides it then.</li></ul></div>
|
||||
|
||||
</div>
|
||||
|
||||
<h3>Owner decisions, 2026-10-25</h3>
|
||||
<div class="why">
|
||||
<div><h4>1. Screen and Battery under Node Settings</h4><p>They are this radio's own hardware settings, beside Button actions, and they appear only on radios that have them. The rejected alternative was a new top-level "Device display" category, which would be empty on most radios.</p></div>
|
||||
<div><h4>2. Play is a separate button</h4><p>The badge auditions as you move because moving and choosing are separate keys. On a phone, a tap is the choice, so play is its own button and the name chooses. A preview never changes the setting.</p></div>
|
||||
<div><h4>3. No way back to "radio default"</h4><p>Firmware refuses 0xFF on an event because the badge's picker has no Default row for events, and Screen off accepts only its five steps. The app matches that. A way back would be a firmware change.</p></div>
|
||||
<div><h4>4. "Menus and lists" and "Messages"</h4><p>The badge says "Nav text" and "Message text", which fit 21 columns. The app has room to say what each governs.</p></div>
|
||||
</div>
|
||||
|
||||
<h3>Why these choices</h3>
|
||||
<div class="why">
|
||||
<div><h4>The radio is the record, everywhere</h4><p>Every reply on this list re-reads after the write: EVTONE and CHTUNE carry stored and effective, SCREEN carries the whole set. The app draws only from replies, stores none of it, and so has nothing per radio to isolate (#853) or to drift.</p></div>
|
||||
<div><h4>The app offers exactly what the badge offers</h4><p>Firmware refuses anything its own screens would not offer. Building each list from the same rule (named built-ins plus filled slots, five Screen off steps, three sizes, the zone table) means the app never offers a choice the radio will reject.</p></div>
|
||||
</div>
|
||||
|
||||
</body></html>
|
||||
@ -0,0 +1,110 @@
|
||||
// Codec for the upstream 1.18 companion CLI frames (interop plan F2, #868):
|
||||
// CMD_RUN_CLI_COMMAND (66) out, RESP_CODE_CLI_REPLY (29) back. Pure codec,
|
||||
// no transport - mirrors the firmware contract at companion-v1.18.0
|
||||
// (INVESTIGATION.md §A1):
|
||||
// request [66][ascii command], frame length >= 3
|
||||
// reply [29][ascii reply], reply text <= 165 bytes (reply_buf[166])
|
||||
// Correlation rides the optional 3-char prefix `cc|`: a command whose third
|
||||
// character is `|` (and length > 4 on the device) has those 3 chars reflected
|
||||
// at the start of the reply. Same grammar the repeater CLI already uses.
|
||||
//
|
||||
// Only emit frame 66 to a device the population classifier places at
|
||||
// stockModern (or post-absorb Offband, via the D1 seam) - see
|
||||
// device_population.dart. The codec itself does not gate.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// `CMD_RUN_CLI_COMMAND`, stock v14+.
|
||||
const int cmdRunCliCommand = 66;
|
||||
|
||||
/// `RESP_CODE_CLI_REPLY`, the reply to [cmdRunCliCommand].
|
||||
const int respCodeCliReply = 29;
|
||||
|
||||
/// The device truncates replies at this many text bytes (`reply_buf[166]`,
|
||||
/// one byte spent on the frame code).
|
||||
const int maxCliReplyPayload = 165;
|
||||
|
||||
final RegExp _prefixShape = RegExp(r'^..\|$');
|
||||
|
||||
/// Builds a `[66][command]` frame, optionally prepending a 3-char
|
||||
/// correlation [prefix] of the `cc|` shape.
|
||||
///
|
||||
/// Throws [ArgumentError] on a blank command, a command too short for the
|
||||
/// firmware's `len >= 3` floor (two command bytes minimum), or a prefix that
|
||||
/// is not exactly three characters ending in `|` - fail closed rather than
|
||||
/// emit a frame the device will misparse.
|
||||
Uint8List buildRunCliCommandFrame(String command, {String? prefix}) {
|
||||
final trimmed = command.trim();
|
||||
if (trimmed.isEmpty) {
|
||||
throw ArgumentError.value(command, 'command', 'must not be blank');
|
||||
}
|
||||
if (prefix != null && !_prefixShape.hasMatch(prefix)) {
|
||||
throw ArgumentError.value(prefix, 'prefix', 'must be 3 chars ending in |');
|
||||
}
|
||||
final payload = '${prefix ?? ''}$trimmed';
|
||||
if (payload.length < 2) {
|
||||
throw ArgumentError.value(
|
||||
command,
|
||||
'command',
|
||||
'firmware requires at least 2 command bytes (frame len >= 3)',
|
||||
);
|
||||
}
|
||||
// The device CLI is an ASCII surface; encode fail-closed so a non-ASCII
|
||||
// command throws here instead of reaching the device malformed (Gemini
|
||||
// review, #881 finding 1).
|
||||
final List<int> bytes;
|
||||
try {
|
||||
bytes = ascii.encode(payload);
|
||||
} on ArgumentError {
|
||||
throw ArgumentError.value(command, 'command', 'must be ASCII');
|
||||
}
|
||||
return Uint8List.fromList([cmdRunCliCommand, ...bytes]);
|
||||
}
|
||||
|
||||
/// One decoded CLI reply.
|
||||
class CliReply {
|
||||
const CliReply({
|
||||
required this.prefix,
|
||||
required this.text,
|
||||
required this.payloadLength,
|
||||
});
|
||||
|
||||
/// The reflected `cc|` correlation token, when the reply carries one.
|
||||
final String? prefix;
|
||||
|
||||
/// Reply text with any prefix stripped.
|
||||
final String text;
|
||||
|
||||
/// Raw payload byte count (prefix included) - truncation happens on the
|
||||
/// device BEFORE the prefix is stripped, so the bound is judged here, not
|
||||
/// on [text] (Gemini review, #881 finding 2).
|
||||
final int payloadLength;
|
||||
|
||||
/// True when the payload sits at the device's truncation bound - the reply
|
||||
/// may have been cut and the UI should say so rather than present it as
|
||||
/// complete.
|
||||
bool get atReplyBound => payloadLength >= maxCliReplyPayload;
|
||||
}
|
||||
|
||||
/// Parses a `[29][reply]` frame; null when [frame] is not a CLI reply.
|
||||
/// Decoding is lenient (malformed bytes become U+FFFD) - a garbled reply is
|
||||
/// still a reply, and dropping it would look like a timeout.
|
||||
///
|
||||
/// Prefix detection is positional (third character `|`), the same rule the
|
||||
/// device and the repeater path use. A prefixless reply whose text happens to
|
||||
/// carry `|` at index 2 mis-splits - inherent to the wire grammar, mitigated
|
||||
/// by callers always sending a prefix so real replies reflect one.
|
||||
CliReply? parseCliReply(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != respCodeCliReply) return null;
|
||||
final payloadLength = frame.length - 1;
|
||||
final raw = utf8.decode(frame.sublist(1), allowMalformed: true);
|
||||
if (raw.length >= 3 && raw[2] == '|') {
|
||||
return CliReply(
|
||||
prefix: raw.substring(0, 3),
|
||||
text: raw.substring(3),
|
||||
payloadLength: payloadLength,
|
||||
);
|
||||
}
|
||||
return CliReply(prefix: null, text: raw, payloadLength: payloadLength);
|
||||
}
|
||||
@ -0,0 +1,217 @@
|
||||
// Population classifier for the connected radio (initiative #860, F1 #862).
|
||||
//
|
||||
// Upstream MeshCore 1.18.0 moved FIRMWARE_VER_CODE into the range the Offband
|
||||
// fork had already spent (stock 14 = "CLI frame 66 exists" vs fork 14..22 =
|
||||
// 0xC0-era contract numbers), so a bare `firmwareVerCode >= N` comparison no
|
||||
// longer means one thing. Every capability decision routes through this
|
||||
// classifier instead of reading ver code or frame offsets directly.
|
||||
//
|
||||
// Interim signal (plan E1.1): the device-info reply's SHAPE. Stock ships
|
||||
// exactly 82 bytes; the fork appends offband_caps at offset 82 and caps
|
||||
// byte 2 at offset 84 [verified against companion-v1.18.0 and firmware-base,
|
||||
// INVESTIGATION.md §A/§B3]. The firmware's durable marker (decision D1)
|
||||
// replaces this at one seam -see classifyDevicePopulation's doc.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// Which firmware family the connected radio belongs to, as far as wire
|
||||
/// behavior is concerned.
|
||||
enum DevicePopulation {
|
||||
/// Stock MeshCore below ver 14, or anything this classifier cannot place:
|
||||
/// the fail-closed default. No fork frames, no CLI frame.
|
||||
stockLegacy,
|
||||
|
||||
/// Stock MeshCore ver 14+ (1.18.0 era): CLI frame 66/29 exists; fork
|
||||
/// frames (0xC0..0xC6) and caps bytes do not.
|
||||
stockModern,
|
||||
|
||||
/// Offband fork: caps byte(s) present; fork frames are gated by the
|
||||
/// advertised cap bits as before. No CLI frame until the fork absorbs
|
||||
/// upstream 1.18 (post-absorb devices flip [Classification.allowsCliFrame]
|
||||
/// at the D1 seam, not here).
|
||||
offband,
|
||||
}
|
||||
|
||||
/// The classifier's verdict plus the coarse capability doors it opens.
|
||||
/// Fine-grained gating (which 0xC command, which cap bit) stays where it is
|
||||
/// today; these booleans only say which FAMILIES of frames may be emitted.
|
||||
class Classification {
|
||||
const Classification({
|
||||
required this.population,
|
||||
required this.conflict,
|
||||
required this.evidence,
|
||||
});
|
||||
|
||||
final DevicePopulation population;
|
||||
|
||||
/// True when the signals contradicted each other (for example a fork-length
|
||||
/// frame carrying a stock version string). Conflicts classify as
|
||||
/// [DevicePopulation.stockLegacy] -fail closed -and [evidence] says why.
|
||||
final bool conflict;
|
||||
|
||||
/// Human-readable signal summary for logs; never parsed.
|
||||
final String evidence;
|
||||
|
||||
/// Fork frames (0xC0..0xC6) may be emitted, subject to the existing
|
||||
/// cap-bit gates.
|
||||
bool get allowsOffbandFrames => population == DevicePopulation.offband;
|
||||
|
||||
/// CMD_RUN_CLI_COMMAND (66) may be emitted. Deliberately false for
|
||||
/// [DevicePopulation.offband] on the current fork base; the absorb flips
|
||||
/// this at the D1 seam together with the durable marker.
|
||||
bool get allowsCliFrame => population == DevicePopulation.stockModern;
|
||||
}
|
||||
|
||||
/// Stock device-info replies are exactly this long; the first fork byte
|
||||
/// (offband_caps) sits at this offset. [verified: CMD_DEVICE_QUERY reply
|
||||
/// construction at companion-v1.18.0 -82 bytes, unchanged from 1.17.x]
|
||||
const int stockDeviceInfoLength = 82;
|
||||
|
||||
/// Upstream ver code that introduces the CLI frame (66/29).
|
||||
const int stockCliMinVerCode = 14;
|
||||
|
||||
/// Highest FIRMWARE_VER_CODE this client knows to exist in the field on any
|
||||
/// population (fork is at 22, moving to 23 on firmware#1448; stock is at 14).
|
||||
/// A report far above this is treated as malformed rather than capable.
|
||||
const int maxKnownVerCode = 32;
|
||||
|
||||
/// Classifies the connected radio from its device-info reply and the parsed
|
||||
/// firmware-version string.
|
||||
///
|
||||
/// [deviceInfo] is the raw RESP_CODE_DEVICE_INFO frame. [firmwareVersion] is
|
||||
/// the version string already extracted from it (null when absent/unreadable);
|
||||
/// it is a SECONDARY signal -absence never blocks, only a positive
|
||||
/// contradiction does. Task #878 replaces the contains-check below with the
|
||||
/// full dual-format parser.
|
||||
///
|
||||
/// D1 SEAM: when the firmware ships its durable population marker, this
|
||||
/// function is the single place that learns to read it; callers and the
|
||||
/// [Classification] contract do not change.
|
||||
Classification classifyDevicePopulation({
|
||||
required Uint8List deviceInfo,
|
||||
required String? firmwareVersion,
|
||||
}) {
|
||||
final length = deviceInfo.length;
|
||||
|
||||
// Malformed: too short to even carry a ver code, per the connector's own
|
||||
// minimum (frame.length < 4 is discarded there too).
|
||||
if (length < 4) {
|
||||
return Classification(
|
||||
population: DevicePopulation.stockLegacy,
|
||||
conflict: false,
|
||||
evidence: 'malformed device-info (len=$length)',
|
||||
);
|
||||
}
|
||||
|
||||
final verCode = deviceInfo[1];
|
||||
final forkShape = length > stockDeviceInfoLength;
|
||||
final versionLooksStock = _versionLooksStock(firmwareVersion);
|
||||
|
||||
if (verCode > maxKnownVerCode) {
|
||||
return Classification(
|
||||
population: DevicePopulation.stockLegacy,
|
||||
conflict: true,
|
||||
evidence: 'ver $verCode above any known population (len=$length)',
|
||||
);
|
||||
}
|
||||
|
||||
if (forkShape) {
|
||||
if (versionLooksStock == false) {
|
||||
// Positively Offband: fork-length frame AND the dual version form.
|
||||
// Every verified fork build reports the dual form, including release
|
||||
// images' X-X shape (firmware#691) and bench builds' git-describe
|
||||
// suffixes, so requiring it costs nothing real and stops a corrupted
|
||||
// stock frame from unlocking fork frames.
|
||||
return Classification(
|
||||
population: DevicePopulation.offband,
|
||||
conflict: false,
|
||||
evidence: 'caps byte present (len=$length, ver=$verCode)',
|
||||
);
|
||||
}
|
||||
// Stock version string, or no readable version at all: the shape says
|
||||
// fork but nothing corroborates it, so no fork frames get emitted on
|
||||
// this connection (Gemini review, task #875 finding 1A).
|
||||
return Classification(
|
||||
population: DevicePopulation.stockLegacy,
|
||||
conflict: true,
|
||||
evidence:
|
||||
'fork-shape frame (len=$length) but version string '
|
||||
'"$firmwareVersion" does not corroborate',
|
||||
);
|
||||
}
|
||||
|
||||
// A stock-shape (82-byte) frame is definitively stock: the Offband fork
|
||||
// always appends at least one caps byte (>=83 bytes), so a stock-shape frame
|
||||
// can never be an Offband device. The version string is therefore NOT used to
|
||||
// force a conflict in the stock direction. This replaces the old inverse
|
||||
// conflict (#875 finding 2), which guarded an impossible case (an Offband
|
||||
// device that failed to append caps) and misfired on real stock firmware:
|
||||
// stock 1.18.0 reports "v1.18.0-81dbae5" (semver + git-describe hash), which
|
||||
// reads as the dual form and hid the console on every real device (#946,
|
||||
// found by E2.2 bench verification). The fork-shape branch above still
|
||||
// requires dual-version corroboration, because emitting fork frames is the
|
||||
// direction where being wrong is dangerous.
|
||||
if (verCode >= stockCliMinVerCode) {
|
||||
return Classification(
|
||||
population: DevicePopulation.stockModern,
|
||||
conflict: false,
|
||||
evidence: 'stock-shape frame, ver=$verCode >= $stockCliMinVerCode',
|
||||
);
|
||||
}
|
||||
|
||||
return Classification(
|
||||
population: DevicePopulation.stockLegacy,
|
||||
conflict: false,
|
||||
evidence: 'stock-shape frame, ver=$verCode',
|
||||
);
|
||||
}
|
||||
|
||||
/// What a firmware-version string positively claims about the population.
|
||||
enum VersionStringShape {
|
||||
/// Single `vX.Y.Z` (or `X.Y.Z`): the stock FIRMWARE_VERSION form.
|
||||
stock,
|
||||
|
||||
/// The Offband dual form: a semver, a dash, then more -covering
|
||||
/// `<ob>-<mc>` ("1.4.0-1.17.0"), the release-image `X-X` shape
|
||||
/// ("1.4.0-1.4.0", firmware#691), and bench builds' git-describe tails
|
||||
/// ("1.1.0-4-g9f2e1c3-dirty").
|
||||
offbandDual,
|
||||
|
||||
/// Absent, empty, or nothing this parser recognizes. Never corroborates
|
||||
/// anything: the classifier treats it as a missing signal, which on a
|
||||
/// fork-shape frame means fail closed.
|
||||
unknown,
|
||||
}
|
||||
|
||||
// A stock version with a suffix (a git-describe hash like "v1.18.0-81dbae5",
|
||||
// or a pre-release like "v1.19.0-rc1") parses as the dual form here. That no
|
||||
// longer mis-classifies a stock device: a stock-shape (82-byte) frame is
|
||||
// classified by its ver code regardless of the version string (#946), because
|
||||
// the frame shape is definitive. This parser's dual verdict only matters on a
|
||||
// FORK-shape frame, where it corroborates the caps bytes.
|
||||
final RegExp _semver = RegExp(r'^v?\d+\.\d+\.\d+$');
|
||||
final RegExp _dualPrefix = RegExp(r'^v?\d+\.\d+\.\d+-.+$');
|
||||
|
||||
/// Parses the device-info firmware-version field into its population claim
|
||||
/// (#878). Pure and total: any input maps to exactly one shape.
|
||||
VersionStringShape classifyVersionString(String? version) {
|
||||
if (version == null) return VersionStringShape.unknown;
|
||||
final v = version.trim();
|
||||
if (v.isEmpty) return VersionStringShape.unknown;
|
||||
if (_semver.hasMatch(v)) return VersionStringShape.stock;
|
||||
if (_dualPrefix.hasMatch(v)) return VersionStringShape.offbandDual;
|
||||
return VersionStringShape.unknown;
|
||||
}
|
||||
|
||||
/// Adapter kept for the classifier's tri-state contract: true = positively
|
||||
/// stock, false = positively Offband, null = no signal.
|
||||
bool? _versionLooksStock(String? version) {
|
||||
switch (classifyVersionString(version)) {
|
||||
case VersionStringShape.stock:
|
||||
return true;
|
||||
case VersionStringShape.offbandDual:
|
||||
return false;
|
||||
case VersionStringShape.unknown:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,150 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'offband_device_ui.dart';
|
||||
|
||||
/// The badge's own display and battery settings over `0xC5` (#987): both
|
||||
/// text sizes, Screen off, time zone and the battery full point. Gated on caps
|
||||
/// byte 2 `0x40` SCREEN_SETTINGS (meshcore-firmware `f3d30a88`).
|
||||
///
|
||||
/// Every reply, GET or SET, is the whole set re-read after the write:
|
||||
/// `[0xC5][sub][nav][msg][scr_stored:2][scr_secs:2][tz][batt_stored:2]
|
||||
/// [batt_full:2][batt_pinned]`, 14 bytes, all little-endian.
|
||||
|
||||
const int offbandUiScreenGet = 0x13;
|
||||
const int offbandUiTextSet = 0x14;
|
||||
const int offbandUiScreenOffSet = 0x15;
|
||||
const int offbandUiTimeZoneSet = 0x16;
|
||||
const int offbandUiBatterySet = 0x17;
|
||||
const int _screenReplyLength = 14;
|
||||
|
||||
/// The three text sizes, in firmware's encoding (`BadgeLayout.h`).
|
||||
enum BadgeTextSize {
|
||||
large(0, 'Large'),
|
||||
medium(1, 'Medium'),
|
||||
small(2, 'Small');
|
||||
|
||||
const BadgeTextSize(this.code, this.label);
|
||||
final int code;
|
||||
final String label;
|
||||
|
||||
static BadgeTextSize? fromCode(int code) {
|
||||
for (final s in BadgeTextSize.values) {
|
||||
if (s.code == code) return s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Which text size a TEXT_SET changes: the badge's Nav text or Message text.
|
||||
enum BadgeTextTarget {
|
||||
navigation(0),
|
||||
messages(1);
|
||||
|
||||
const BadgeTextTarget(this.code);
|
||||
final int code;
|
||||
}
|
||||
|
||||
/// The Screen off steps the badge's row cycles through (`kScreenOffSteps`).
|
||||
/// Firmware accepts exactly these and nothing else.
|
||||
const List<int> screenOffSteps = [15, 30, 60, 120, 300];
|
||||
|
||||
String screenOffLabel(int secs) => secs < 60
|
||||
? '$secs s'
|
||||
: '${secs ~/ 60} m${secs % 60 == 0 ? '' : ' ${secs % 60} s'}';
|
||||
|
||||
/// The radio's screen and battery settings, from any `0x13` to `0x17` reply.
|
||||
class ScreenSettingsState {
|
||||
const ScreenSettingsState({
|
||||
required this.navText,
|
||||
required this.messageText,
|
||||
required this.screenOffStored,
|
||||
required this.screenOffSeconds,
|
||||
required this.timeZone,
|
||||
required this.batteryFullStored,
|
||||
required this.batteryFullMv,
|
||||
required this.batteryPinned,
|
||||
});
|
||||
|
||||
/// Null when a newer firmware reports a size this client does not know.
|
||||
final BadgeTextSize? navText;
|
||||
final BadgeTextSize? messageText;
|
||||
|
||||
/// The Screen off preference in seconds; 0 means the board's compiled
|
||||
/// timeout, which [screenOffSeconds] then reports.
|
||||
final int screenOffStored;
|
||||
final int screenOffSeconds;
|
||||
|
||||
/// Index into the badge's zone table; 0 is not set.
|
||||
final int timeZone;
|
||||
|
||||
/// The learned or pinned full point in mV, 0 when there is neither.
|
||||
final int batteryFullStored;
|
||||
|
||||
/// The mV the radio's battery bar treats as 100%.
|
||||
final int batteryFullMv;
|
||||
|
||||
/// Set by hand, which auto-learn leaves alone.
|
||||
final bool batteryPinned;
|
||||
|
||||
bool get screenOffIsDefault => screenOffStored == 0;
|
||||
}
|
||||
|
||||
Uint8List buildScreenSettingsGetFrame() =>
|
||||
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiScreenGet]);
|
||||
|
||||
Uint8List buildTextSizeSetFrame(BadgeTextTarget target, BadgeTextSize size) =>
|
||||
Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiTextSet,
|
||||
target.code,
|
||||
size.code,
|
||||
]);
|
||||
|
||||
Uint8List buildScreenOffSetFrame(int seconds) {
|
||||
if (seconds < 0 || seconds > 0xFFFF) {
|
||||
throw ArgumentError.value(seconds, 'seconds', 'must be 0 to 65535');
|
||||
}
|
||||
return Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiScreenOffSet,
|
||||
seconds & 0xFF,
|
||||
seconds >> 8,
|
||||
]);
|
||||
}
|
||||
|
||||
Uint8List buildTimeZoneSetFrame(int index) {
|
||||
if (index < 0 || index > 0xFF) {
|
||||
throw ArgumentError.value(index, 'index', 'must be 0 to 255');
|
||||
}
|
||||
return Uint8List.fromList([cmdOffbandDeviceUi, offbandUiTimeZoneSet, index]);
|
||||
}
|
||||
|
||||
/// `pin` true pins the radio's own current reading as 100%; false hands the
|
||||
/// full point back to auto-learn.
|
||||
Uint8List buildBatteryFullSetFrame({required bool pin}) =>
|
||||
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiBatterySet, pin ? 1 : 0]);
|
||||
|
||||
/// Parse a screen-settings reply. Null if this is not one, or if it is
|
||||
/// shorter than the 14 bytes the contract fixes. The shared 0x7F error is
|
||||
/// owned by [parseButtonMatrixReply].
|
||||
OffbandUiReply? parseScreenSettingsReply(Uint8List frame) {
|
||||
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
|
||||
final sub = frame[1];
|
||||
if (sub < offbandUiScreenGet || sub > offbandUiBatterySet) return null;
|
||||
if (frame.length < _screenReplyLength) return null;
|
||||
final data = ByteData.sublistView(frame);
|
||||
return OffbandUiReply(
|
||||
command: respCodeOffbandDeviceUi,
|
||||
sub: sub,
|
||||
screen: ScreenSettingsState(
|
||||
navText: BadgeTextSize.fromCode(frame[2]),
|
||||
messageText: BadgeTextSize.fromCode(frame[3]),
|
||||
screenOffStored: data.getUint16(4, Endian.little),
|
||||
screenOffSeconds: data.getUint16(6, Endian.little),
|
||||
timeZone: frame[8],
|
||||
batteryFullStored: data.getUint16(9, Endian.little),
|
||||
batteryFullMv: data.getUint16(11, Endian.little),
|
||||
batteryPinned: frame[13] != 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,452 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'offband_device_ui.dart';
|
||||
|
||||
/// The radio's tune system over `0xC5` (#970, #971, #986): the built-in tune
|
||||
/// table, the eight custom RTTTL slots, the six event tones and preview.
|
||||
///
|
||||
/// Gated on caps byte 2 `0x10` TUNES (meshcore-firmware `f3d30a88`). The
|
||||
/// contract lives in firmware's `OffbandConfigProtocol.h`; the tables and the
|
||||
/// validator below are ports of `Tunes.h` and `TuneSlots.h` at that commit.
|
||||
|
||||
const int offbandUiSlotGet = 0x09;
|
||||
const int offbandUiSlotSet = 0x0A;
|
||||
const int offbandUiEventToneGet = 0x0F;
|
||||
const int offbandUiEventToneSet = 0x10;
|
||||
const int offbandUiTunePlay = 0x11;
|
||||
const int offbandUiSlotRead = 0x12;
|
||||
|
||||
/// The built-in tunes, by id. Firmware's table is append-only, so this copy
|
||||
/// can only fall behind, never misname an id. A null name is a tune firmware
|
||||
/// keeps out of its own picker (id 7, Trigger), so it is never offered here.
|
||||
const List<String?> builtinTuneNames = [
|
||||
'Silent',
|
||||
'Chime',
|
||||
'Kerplop',
|
||||
'Tick',
|
||||
'Bloop',
|
||||
'Drop',
|
||||
'Knock',
|
||||
null,
|
||||
];
|
||||
|
||||
const int tuneSilent = 0;
|
||||
const int builtinTuneCount = 8;
|
||||
const int tuneSlotCount = 8;
|
||||
const int firstSlotTuneId = builtinTuneCount;
|
||||
|
||||
/// The longest RTTTL a slot holds (`kMaxRtttl`) and the longest name a slot
|
||||
/// shows (`kMaxSlotName`).
|
||||
const int maxSlotRtttl = 240;
|
||||
const int maxSlotName = 12;
|
||||
|
||||
bool isSlotTuneId(int id) =>
|
||||
id >= firstSlotTuneId && id < firstSlotTuneId + tuneSlotCount;
|
||||
|
||||
int slotTuneId(int slot) => firstSlotTuneId + slot;
|
||||
|
||||
/// Built-in ids the badge's picker lists, in its order.
|
||||
List<int> get listedBuiltinTuneIds => [
|
||||
for (var id = 0; id < builtinTuneNames.length; id++)
|
||||
if (builtinTuneNames[id] != null) id,
|
||||
];
|
||||
|
||||
/// One of the six events the badge's Tones screen sets. Values are firmware's
|
||||
/// `offband::ToneEvent`, and the labels are the badge's own (`kToneEventRows`).
|
||||
enum ToneEvent {
|
||||
dm(0, 'DM'),
|
||||
channel(1, 'Channel'),
|
||||
room(2, 'Room'),
|
||||
newContact(3, 'New contact'),
|
||||
ack(4, 'Ack'),
|
||||
sent(5, 'Sent');
|
||||
|
||||
const ToneEvent(this.code, this.label);
|
||||
final int code;
|
||||
final String label;
|
||||
|
||||
static ToneEvent? fromCode(int code) {
|
||||
for (final e in ToneEvent.values) {
|
||||
if (e.code == code) return e;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored byte meaning "nothing chosen": the board's compiled default plays.
|
||||
const int tuneUnset = 0xFF;
|
||||
|
||||
/// An event's tune as the radio reports it. [effective] is what plays.
|
||||
class EventToneState {
|
||||
const EventToneState({required this.stored, required this.effective});
|
||||
final int stored;
|
||||
final int effective;
|
||||
|
||||
bool get isRadioDefault => stored == tuneUnset;
|
||||
}
|
||||
|
||||
class EventToneReply {
|
||||
const EventToneReply({required this.event, required this.state});
|
||||
final ToneEvent event;
|
||||
final EventToneState state;
|
||||
}
|
||||
|
||||
/// What a custom slot holds, from `SLOT_GET`: its length and derived name,
|
||||
/// never the tune itself. Length 0 is an empty slot.
|
||||
class TuneSlotInfo {
|
||||
const TuneSlotInfo({required this.length, required this.name});
|
||||
final int length;
|
||||
final String name;
|
||||
|
||||
bool get isEmpty => length == 0;
|
||||
}
|
||||
|
||||
class TuneSlotReply {
|
||||
const TuneSlotReply({required this.slot, required this.info});
|
||||
final int slot;
|
||||
final TuneSlotInfo info;
|
||||
}
|
||||
|
||||
/// `SLOT_SET` progress: how many bytes the radio holds for the push in flight.
|
||||
class TuneSlotAccepted {
|
||||
const TuneSlotAccepted({required this.slot, required this.accepted});
|
||||
final int slot;
|
||||
final int accepted;
|
||||
}
|
||||
|
||||
/// One `SLOT_READ` chunk.
|
||||
class TuneSlotChunk {
|
||||
const TuneSlotChunk({
|
||||
required this.slot,
|
||||
required this.offset,
|
||||
required this.more,
|
||||
required this.bytes,
|
||||
});
|
||||
final int slot;
|
||||
final int offset;
|
||||
final bool more;
|
||||
final Uint8List bytes;
|
||||
}
|
||||
|
||||
/// Why a preview did or did not sound (`offband::TonePlay`).
|
||||
enum TunePlayResult {
|
||||
played(0),
|
||||
busy(1),
|
||||
soundOff(2);
|
||||
|
||||
const TunePlayResult(this.code);
|
||||
final int code;
|
||||
|
||||
static TunePlayResult? fromCode(int code) {
|
||||
for (final r in TunePlayResult.values) {
|
||||
if (r.code == code) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class TunePlayReply {
|
||||
const TunePlayReply({required this.tuneId, required this.result});
|
||||
final int tuneId;
|
||||
|
||||
/// Null when a newer firmware reports a result this client does not know.
|
||||
final TunePlayResult? result;
|
||||
}
|
||||
|
||||
/// What the client knows of a radio's tunes, for naming an id.
|
||||
///
|
||||
/// [slots] holds the `SLOT_GET` replies read so far, by slot index.
|
||||
String? tuneLabel(int id, Map<int, TuneSlotInfo> slots) {
|
||||
if (id >= 0 && id < builtinTuneNames.length) return builtinTuneNames[id];
|
||||
if (isSlotTuneId(id)) {
|
||||
final info = slots[id - firstSlotTuneId];
|
||||
if (info == null || info.isEmpty) return null;
|
||||
return info.name.isEmpty ? 'Slot ${id - firstSlotTuneId + 1}' : info.name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The ids a picker may offer: firmware's rule, a named built-in or a filled
|
||||
/// slot. Firmware refuses everything else, so nothing else is shown.
|
||||
List<int> offeredTuneIds(Map<int, TuneSlotInfo> slots) => [
|
||||
...listedBuiltinTuneIds,
|
||||
for (var s = 0; s < tuneSlotCount; s++)
|
||||
if (slots[s] != null && !slots[s]!.isEmpty) slotTuneId(s),
|
||||
];
|
||||
|
||||
Uint8List buildEventToneGetFrame(ToneEvent event) =>
|
||||
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiEventToneGet, event.code]);
|
||||
|
||||
Uint8List buildEventToneSetFrame(ToneEvent event, int tuneId) =>
|
||||
Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiEventToneSet,
|
||||
event.code,
|
||||
_byte(tuneId, 'tuneId'),
|
||||
]);
|
||||
|
||||
Uint8List buildTunePlayFrame(int tuneId) => Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiTunePlay,
|
||||
_byte(tuneId, 'tuneId'),
|
||||
]);
|
||||
|
||||
Uint8List buildSlotGetFrame(int slot) =>
|
||||
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiSlotGet, _slotByte(slot)]);
|
||||
|
||||
Uint8List buildSlotReadFrame(int slot, int offset) => Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiSlotRead,
|
||||
_slotByte(slot),
|
||||
_byte(offset, 'offset'),
|
||||
]);
|
||||
|
||||
/// `[0xC5][0x0A][slot][offset][more][bytes...]`. An empty final chunk at
|
||||
/// offset 0 clears the slot.
|
||||
Uint8List buildSlotSetFrame(int slot, int offset, bool more, List<int> bytes) =>
|
||||
Uint8List.fromList([
|
||||
cmdOffbandDeviceUi,
|
||||
offbandUiSlotSet,
|
||||
_slotByte(slot),
|
||||
_byte(offset, 'offset'),
|
||||
more ? 1 : 0,
|
||||
...bytes,
|
||||
]);
|
||||
|
||||
int _slotByte(int slot) {
|
||||
if (slot < 0 || slot >= tuneSlotCount) {
|
||||
throw ArgumentError.value(
|
||||
slot,
|
||||
'slot',
|
||||
'must be 0 to ${tuneSlotCount - 1}',
|
||||
);
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
int _byte(int value, String name) {
|
||||
if (value < 0 || value > 0xFF) {
|
||||
throw ArgumentError.value(value, name, 'must be 0 to 255');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/// Parse a tune reply (0x09, 0x0A, 0x0F, 0x10, 0x11, 0x12). Null if this is
|
||||
/// not one, or if it is truncated. The shared 0x7F error is owned by
|
||||
/// [parseButtonMatrixReply].
|
||||
OffbandUiReply? parseTuneReply(Uint8List frame) {
|
||||
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
|
||||
final sub = frame[1];
|
||||
OffbandUiReply reply({
|
||||
EventToneReply? eventTone,
|
||||
TuneSlotReply? slot,
|
||||
TuneSlotAccepted? accepted,
|
||||
TuneSlotChunk? chunk,
|
||||
TunePlayReply? play,
|
||||
}) => OffbandUiReply(
|
||||
command: respCodeOffbandDeviceUi,
|
||||
sub: sub,
|
||||
eventTone: eventTone,
|
||||
tuneSlot: slot,
|
||||
slotAccepted: accepted,
|
||||
slotChunk: chunk,
|
||||
tunePlay: play,
|
||||
);
|
||||
|
||||
switch (sub) {
|
||||
case offbandUiEventToneGet:
|
||||
case offbandUiEventToneSet:
|
||||
if (frame.length < 5) return null;
|
||||
final event = ToneEvent.fromCode(frame[2]);
|
||||
if (event == null) {
|
||||
return OffbandUiReply(
|
||||
command: respCodeOffbandDeviceUi,
|
||||
sub: sub,
|
||||
errorMessage:
|
||||
'The radio reported an unknown tone event (${frame[2]})',
|
||||
);
|
||||
}
|
||||
return reply(
|
||||
eventTone: EventToneReply(
|
||||
event: event,
|
||||
state: EventToneState(stored: frame[3], effective: frame[4]),
|
||||
),
|
||||
);
|
||||
case offbandUiSlotGet:
|
||||
if (frame.length < 4) return null;
|
||||
// The name is the rest of the frame, at most what the transport carried.
|
||||
final name = String.fromCharCodes(frame.sublist(4));
|
||||
return reply(
|
||||
slot: TuneSlotReply(
|
||||
slot: frame[2],
|
||||
info: TuneSlotInfo(length: frame[3], name: name),
|
||||
),
|
||||
);
|
||||
case offbandUiSlotSet:
|
||||
if (frame.length < 4) return null;
|
||||
return reply(
|
||||
accepted: TuneSlotAccepted(slot: frame[2], accepted: frame[3]),
|
||||
);
|
||||
case offbandUiSlotRead:
|
||||
if (frame.length < 5) return null;
|
||||
return reply(
|
||||
chunk: TuneSlotChunk(
|
||||
slot: frame[2],
|
||||
offset: frame[3],
|
||||
more: frame[4] != 0,
|
||||
bytes: Uint8List.fromList(frame.sublist(5)),
|
||||
),
|
||||
);
|
||||
case offbandUiTunePlay:
|
||||
if (frame.length < 4) return null;
|
||||
return reply(
|
||||
play: TunePlayReply(
|
||||
tuneId: frame[2],
|
||||
result: TunePlayResult.fromCode(frame[3]),
|
||||
),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Why an RTTTL string is not safe to play, as firmware's `rtttlProblem()`
|
||||
/// judges it. The same rule runs on the badge's editor and on every pushed
|
||||
/// tune, so the app checks with it before sending: the radio can only answer
|
||||
/// "malformed", and this says why.
|
||||
enum RtttlProblem {
|
||||
ok('OK'),
|
||||
empty('Empty'),
|
||||
noName('Needs a name'),
|
||||
missingColon('Needs name:notes'),
|
||||
badDefault('Bad d=, o= or b='),
|
||||
zeroTempo('b= must be 1 or more'),
|
||||
noNotes('No notes'),
|
||||
ambiguousNote('Add d=, o= or b= first'),
|
||||
strayColon('Bad name or d=/o=/b=');
|
||||
|
||||
const RtttlProblem(this.text);
|
||||
|
||||
/// Firmware's own words (`rtttlProblemText`), so the app and the badge
|
||||
/// describe the same problem the same way.
|
||||
final String text;
|
||||
}
|
||||
|
||||
bool _isDigit(int c) => c >= 0x30 && c <= 0x39;
|
||||
bool _isDefaultsSep(int c) => c == 0x2C || c == 0x3A;
|
||||
|
||||
const int _colon = 0x3A;
|
||||
|
||||
/// Port of firmware `rtttlProblem()` (`Tunes.h`, `f3d30a88`), step for step.
|
||||
RtttlProblem rtttlProblem(String rtttl) {
|
||||
final s = rtttl.codeUnits;
|
||||
if (s.isEmpty) return RtttlProblem.empty;
|
||||
int at(int i) => i < s.length ? s[i] : 0;
|
||||
|
||||
var p = 0;
|
||||
while (at(p) != 0 && at(p) != _colon) {
|
||||
p++;
|
||||
}
|
||||
if (at(p) == 0) return RtttlProblem.missingColon;
|
||||
if (p == 0) return RtttlProblem.noName;
|
||||
p++;
|
||||
|
||||
var sawDefault = false;
|
||||
|
||||
if (at(p) == 0x64 && at(p + 1) == 0x3D) {
|
||||
p += 2;
|
||||
var digits = 0;
|
||||
while (_isDigit(at(p))) {
|
||||
p++;
|
||||
digits++;
|
||||
}
|
||||
if (digits == 0 || digits > 4) return RtttlProblem.badDefault;
|
||||
if (!_isDefaultsSep(at(p))) return RtttlProblem.badDefault;
|
||||
p++;
|
||||
sawDefault = true;
|
||||
}
|
||||
|
||||
if (at(p) == 0x6F && at(p + 1) == 0x3D) {
|
||||
if (!_isDigit(at(p + 2))) return RtttlProblem.badDefault;
|
||||
if (!_isDefaultsSep(at(p + 3))) return RtttlProblem.badDefault;
|
||||
p += 4;
|
||||
sawDefault = true;
|
||||
}
|
||||
|
||||
if (at(p) == 0x62 && at(p + 1) == 0x3D) {
|
||||
p += 2;
|
||||
var digits = 0;
|
||||
var bpm = 0;
|
||||
while (_isDigit(at(p))) {
|
||||
if (digits < 5) bpm = bpm * 10 + (at(p) - 0x30);
|
||||
p++;
|
||||
digits++;
|
||||
}
|
||||
if (digits == 0) return RtttlProblem.zeroTempo;
|
||||
if (digits > 4) return RtttlProblem.badDefault;
|
||||
if (bpm == 0) return RtttlProblem.zeroTempo;
|
||||
if (!_isDefaultsSep(at(p))) return RtttlProblem.badDefault;
|
||||
p++;
|
||||
sawDefault = true;
|
||||
}
|
||||
|
||||
if (at(p) == 0) return RtttlProblem.noNotes;
|
||||
|
||||
final c = at(p);
|
||||
if (!sawDefault && (c == 0x64 || c == 0x6F || c == 0x62)) {
|
||||
return RtttlProblem.ambiguousNote;
|
||||
}
|
||||
|
||||
for (var q = p; q < s.length; q++) {
|
||||
if (s[q] == _colon) return RtttlProblem.strayColon;
|
||||
}
|
||||
return RtttlProblem.ok;
|
||||
}
|
||||
|
||||
/// The tune with its defaults rewritten into the order the badge's player
|
||||
/// reads them (d=, o=, b=, each once), or null when that is not the fix.
|
||||
///
|
||||
/// The player reads defaults positionally, so RTTTL from elsewhere that lists
|
||||
/// them in another order, or repeats one, is refused as a stray colon. This
|
||||
/// rewrites only the header between the first two colons, and only when every
|
||||
/// item there is a d=, o= or b= and a repeated key repeats the same value: two
|
||||
/// different tempos are a choice the app cannot make for the user. The result
|
||||
/// must pass [rtttlProblem], so a header fix never hides a second problem.
|
||||
String? fixRtttlDefaultsOrder(String rtttl) {
|
||||
if (rtttlProblem(rtttl) == RtttlProblem.ok) return null;
|
||||
final first = rtttl.indexOf(':');
|
||||
if (first < 0) return null;
|
||||
final second = rtttl.indexOf(':', first + 1);
|
||||
if (second < 0) return null;
|
||||
final values = <String, String>{};
|
||||
for (final raw in rtttl.substring(first + 1, second).split(',')) {
|
||||
final item = raw.trim();
|
||||
final eq = item.indexOf('=');
|
||||
if (eq != 1) return null;
|
||||
final key = item[0];
|
||||
final value = item.substring(2).trim();
|
||||
if (!const {'d', 'o', 'b'}.contains(key) || value.isEmpty) return null;
|
||||
final held = values[key];
|
||||
if (held != null && held != value) return null;
|
||||
values[key] = value;
|
||||
}
|
||||
final header = [
|
||||
for (final k in const ['d', 'o', 'b'])
|
||||
if (values[k] != null) '$k=${values[k]}',
|
||||
].join(',');
|
||||
final fixed =
|
||||
'${rtttl.substring(0, first)}:$header:${rtttl.substring(second + 1)}';
|
||||
if (fixed == rtttl || rtttlProblem(fixed) != RtttlProblem.ok) return null;
|
||||
return fixed;
|
||||
}
|
||||
|
||||
/// Port of firmware `deriveSlotName()`: the text before the first colon,
|
||||
/// trimmed and cut to [maxSlotName]. Empty when there is no usable name.
|
||||
String deriveSlotName(String rtttl) {
|
||||
final colon = rtttl.indexOf(':');
|
||||
if (colon < 0) return '';
|
||||
var name = rtttl
|
||||
.substring(0, colon)
|
||||
.replaceAll(RegExp(r'^[ \t]+|[ \t]+$'), '');
|
||||
if (name.length > maxSlotName) name = name.substring(0, maxSlotName);
|
||||
return name;
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
/// The budget for automatic reconnects after a link drops (#997).
|
||||
///
|
||||
/// An automatic retry stops after [maxAttempts] attempts, or once the next one
|
||||
/// would start more than [window] after the first, whichever comes first.
|
||||
/// Only [reset] clears the count: an automatic attempt must never reset it,
|
||||
/// which is what let the client retry an unreachable radio for hours (#995).
|
||||
class ReconnectPolicy {
|
||||
ReconnectPolicy({
|
||||
this.maxAttempts = 5,
|
||||
this.window = const Duration(minutes: 3),
|
||||
});
|
||||
|
||||
final int maxAttempts;
|
||||
final Duration window;
|
||||
|
||||
int _attempts = 0;
|
||||
DateTime? _startedAt;
|
||||
|
||||
/// Attempts scheduled since the last [reset].
|
||||
int get attempts => _attempts;
|
||||
|
||||
/// The delay before the next attempt, or null when the budget is spent.
|
||||
Duration? nextDelay(DateTime now) {
|
||||
if (_attempts >= maxAttempts) return null;
|
||||
final startedAt = _startedAt ??= now;
|
||||
final delay = Duration(seconds: 1 << _attempts);
|
||||
if (now.add(delay).difference(startedAt) >= window) return null;
|
||||
_attempts += 1;
|
||||
return delay;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_attempts = 0;
|
||||
_startedAt = null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
// Mirrors the firmware's `set name` character rejection on the client (#885,
|
||||
// interop plan F2/E2.1). The companion CommonCLI rejects these characters in a
|
||||
// device name [verified: companion built-ins, INVESTIGATION.md section A], and
|
||||
// a name carrying one comes back as a cryptic `ERROR` from the device. Catching
|
||||
// it client-side lets the UI say exactly what is wrong before anything is sent.
|
||||
//
|
||||
// The device stays the authority: this is a convenience check, not a
|
||||
// replacement for the device's own validation.
|
||||
|
||||
/// Characters the firmware's `set name` rejects.
|
||||
const List<String> forbiddenDeviceNameChars = <String>[
|
||||
'[',
|
||||
']',
|
||||
'\\',
|
||||
':',
|
||||
',',
|
||||
'?',
|
||||
'*',
|
||||
];
|
||||
|
||||
/// The distinct forbidden characters present in [name], in the order they
|
||||
/// appear in [forbiddenDeviceNameChars]. Empty when the name is valid.
|
||||
List<String> forbiddenCharsIn(String name) =>
|
||||
forbiddenDeviceNameChars.where(name.contains).toList();
|
||||
|
||||
/// True when [name] carries none of the forbidden characters.
|
||||
bool isValidDeviceName(String name) => forbiddenCharsIn(name).isEmpty;
|
||||
@ -0,0 +1,49 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// Region transport-key derivation, matching the MeshCore firmware
|
||||
/// (`RegionMap.getTransportKeysFor` -> `TransportKeyStore.getAutoKeyFor`).
|
||||
///
|
||||
/// A public "hashtag" region's transport key is the first 16 bytes of
|
||||
/// `SHA256` of the region name carrying exactly one leading `#`: auto-hashtag
|
||||
/// names are hashed as stored, bare names get a `#` prepended. `$`-prefixed
|
||||
/// regions are private, their keys live in a hardware keystore and are not
|
||||
/// derivable from the name. Names discovered over the air arrive `#`-stripped,
|
||||
/// so the client re-adds the `#` here.
|
||||
const int _keyLength = 16;
|
||||
|
||||
/// True for a private (`$`-prefixed) region, whose key is not name-derivable.
|
||||
bool isPrivateRegionName(String name) => name.trim().startsWith(r'$');
|
||||
|
||||
/// The region name as the firmware hashes it: exactly one leading `#`.
|
||||
String normalizeHashtag(String name) {
|
||||
final stripped = name.trim().replaceFirst(RegExp(r'^#+'), '');
|
||||
return '#$stripped';
|
||||
}
|
||||
|
||||
/// First 16 bytes of `SHA256("#"+name)`.
|
||||
///
|
||||
/// Returns null when [name] is blank or a private (`$`) region.
|
||||
Uint8List? transportKeyForName(String name) {
|
||||
final trimmed = name.trim();
|
||||
if (trimmed.isEmpty || isPrivateRegionName(trimmed)) return null;
|
||||
final digest = sha256.convert(utf8.encode(normalizeHashtag(trimmed))).bytes;
|
||||
return Uint8List.fromList(digest.sublist(0, _keyLength));
|
||||
}
|
||||
|
||||
/// The 2-byte on-air transport code the firmware stamps on a scoped packet:
|
||||
/// `HMAC-SHA256(key, payloadType || payload)`, first two bytes read as a
|
||||
/// little-endian `uint16` (firmware `TransportKey::calcTransportCode`).
|
||||
int onAirCode(Uint8List key, int payloadType, Uint8List payload) {
|
||||
final mac = Hmac(sha256, key).convert(<int>[payloadType, ...payload]).bytes;
|
||||
return reserveTransportCode(mac[0] | (mac[1] << 8));
|
||||
}
|
||||
|
||||
/// Firmware reserves `0x0000` and `0xFFFF`, bumping each by one.
|
||||
int reserveTransportCode(int code) {
|
||||
if (code == 0x0000) return 0x0001;
|
||||
if (code == 0xFFFF) return 0xFFFE;
|
||||
return code;
|
||||
}
|
||||
@ -0,0 +1,159 @@
|
||||
/// The badge's time zone table, a copy of firmware `src/helpers/TimeZones.h`
|
||||
/// on meshcore-firmware `firmware-base` at `f3d30a88` (#987).
|
||||
///
|
||||
/// The radio stores a zone as an index into this list, so the order is the
|
||||
/// contract. Firmware keeps it append-only ("Append only; never reorder"), so
|
||||
/// a copy can only fall behind; an index past the end is shown by number.
|
||||
library;
|
||||
|
||||
enum DstRule { none, us, eu }
|
||||
|
||||
class BadgeTimeZone {
|
||||
const BadgeTimeZone(this.name, this.standardMinutes, this.rule);
|
||||
final String name;
|
||||
final int standardMinutes;
|
||||
final DstRule rule;
|
||||
}
|
||||
|
||||
const int timeZoneNotSet = 0;
|
||||
|
||||
const List<BadgeTimeZone> badgeTimeZones = [
|
||||
BadgeTimeZone('not set', 0, DstRule.none),
|
||||
BadgeTimeZone('UTC', 0, DstRule.none),
|
||||
BadgeTimeZone('Eastern', -300, DstRule.us),
|
||||
BadgeTimeZone('Central', -360, DstRule.us),
|
||||
BadgeTimeZone('Mountain', -420, DstRule.us),
|
||||
BadgeTimeZone('Arizona', -420, DstRule.none),
|
||||
BadgeTimeZone('Pacific', -480, DstRule.us),
|
||||
BadgeTimeZone('Alaska', -540, DstRule.us),
|
||||
BadgeTimeZone('Hawaii', -600, DstRule.none),
|
||||
BadgeTimeZone('UK', 0, DstRule.eu),
|
||||
BadgeTimeZone('Central EU', 60, DstRule.eu),
|
||||
BadgeTimeZone('Eastern EU', 120, DstRule.eu),
|
||||
BadgeTimeZone('UTC-12', -720, DstRule.none),
|
||||
BadgeTimeZone('UTC-11', -660, DstRule.none),
|
||||
BadgeTimeZone('UTC-10', -600, DstRule.none),
|
||||
BadgeTimeZone('UTC-9', -540, DstRule.none),
|
||||
BadgeTimeZone('UTC-8', -480, DstRule.none),
|
||||
BadgeTimeZone('UTC-7', -420, DstRule.none),
|
||||
BadgeTimeZone('UTC-6', -360, DstRule.none),
|
||||
BadgeTimeZone('UTC-5', -300, DstRule.none),
|
||||
BadgeTimeZone('UTC-4', -240, DstRule.none),
|
||||
BadgeTimeZone('UTC-3', -180, DstRule.none),
|
||||
BadgeTimeZone('UTC-2', -120, DstRule.none),
|
||||
BadgeTimeZone('UTC-1', -60, DstRule.none),
|
||||
BadgeTimeZone('UTC+1', 60, DstRule.none),
|
||||
BadgeTimeZone('UTC+2', 120, DstRule.none),
|
||||
BadgeTimeZone('UTC+3', 180, DstRule.none),
|
||||
BadgeTimeZone('UTC+4', 240, DstRule.none),
|
||||
BadgeTimeZone('UTC+5', 300, DstRule.none),
|
||||
BadgeTimeZone('UTC+6', 360, DstRule.none),
|
||||
BadgeTimeZone('UTC+7', 420, DstRule.none),
|
||||
BadgeTimeZone('UTC+8', 480, DstRule.none),
|
||||
BadgeTimeZone('UTC+9', 540, DstRule.none),
|
||||
BadgeTimeZone('UTC+10', 600, DstRule.none),
|
||||
BadgeTimeZone('UTC+11', 660, DstRule.none),
|
||||
BadgeTimeZone('UTC+12', 720, DstRule.none),
|
||||
BadgeTimeZone('UTC+13', 780, DstRule.none),
|
||||
BadgeTimeZone('UTC+14', 840, DstRule.none),
|
||||
BadgeTimeZone('UTC-3:30', -210, DstRule.none),
|
||||
BadgeTimeZone('UTC+5:30', 330, DstRule.none),
|
||||
BadgeTimeZone('UTC+9:30', 570, DstRule.none),
|
||||
];
|
||||
|
||||
/// The first fixed-offset zone (`kFirstFixed`).
|
||||
const int _firstFixedZone = 12;
|
||||
|
||||
bool _isSet(int index) => index > 0 && index < badgeTimeZones.length;
|
||||
|
||||
/// The zone's name, or the raw index for one this client does not know.
|
||||
String timeZoneName(int index) => index >= 0 && index < badgeTimeZones.length
|
||||
? badgeTimeZones[index].name
|
||||
: 'Zone $index';
|
||||
|
||||
int _nthSunday(int year, int month, int n) {
|
||||
final first = DateTime.utc(year, month, 1);
|
||||
final toSunday = (DateTime.sunday - first.weekday) % 7;
|
||||
return 1 + toSunday + 7 * (n - 1);
|
||||
}
|
||||
|
||||
int _lastSunday(int year, int month) {
|
||||
final last = DateTime.utc(year, month + 1, 0);
|
||||
return last.day - (last.weekday % 7);
|
||||
}
|
||||
|
||||
/// Port of firmware `inDaylightSaving()`: US from 02:00 local on the second
|
||||
/// Sunday of March to 02:00 local daylight time on the first Sunday of
|
||||
/// November; EU from 01:00 UTC on the last Sunday of March to 01:00 UTC on
|
||||
/// the last Sunday of October.
|
||||
bool _inDaylightSaving(BadgeTimeZone z, DateTime utc) {
|
||||
final y = utc.year;
|
||||
switch (z.rule) {
|
||||
case DstRule.us:
|
||||
final start = DateTime.utc(
|
||||
y,
|
||||
3,
|
||||
_nthSunday(y, 3, 2),
|
||||
2,
|
||||
).subtract(Duration(minutes: z.standardMinutes));
|
||||
final end = DateTime.utc(
|
||||
y,
|
||||
11,
|
||||
_nthSunday(y, 11, 1),
|
||||
2,
|
||||
).subtract(Duration(minutes: z.standardMinutes + 60));
|
||||
return !utc.isBefore(start) && utc.isBefore(end);
|
||||
case DstRule.eu:
|
||||
final start = DateTime.utc(y, 3, _lastSunday(y, 3), 1);
|
||||
final end = DateTime.utc(y, 10, _lastSunday(y, 10), 1);
|
||||
return !utc.isBefore(start) && utc.isBefore(end);
|
||||
case DstRule.none:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Minutes to add to UTC at [utc] in zone [index], daylight saving included.
|
||||
/// Null for "not set" and for an index this client does not know.
|
||||
int? timeZoneOffsetMinutes(int index, DateTime utc) {
|
||||
if (!_isSet(index)) return null;
|
||||
final z = badgeTimeZones[index];
|
||||
return z.standardMinutes + (_inDaylightSaving(z, utc.toUtc()) ? 60 : 0);
|
||||
}
|
||||
|
||||
/// "UTC-4", "UTC+5:30", "UTC+0".
|
||||
String formatUtcOffset(int minutes) {
|
||||
final sign = minutes < 0 ? '-' : '+';
|
||||
final a = minutes.abs();
|
||||
final mins = a % 60;
|
||||
return 'UTC$sign${a ~/ 60}${mins == 0 ? '' : ':${mins.toString().padLeft(2, '0')}'}';
|
||||
}
|
||||
|
||||
/// The zone that matches the phone, as the badge suggests one from GPS.
|
||||
///
|
||||
/// A named zone matches when its offset equals the phone's now, in January and
|
||||
/// in July, so its daylight rule agrees as well as its current offset. Failing
|
||||
/// that, the fixed zone for the phone's current offset. Null when nothing fits.
|
||||
///
|
||||
/// [offsetAt] is the phone's UTC offset at a local instant; injectable so the
|
||||
/// match can be tested without depending on the machine's own zone.
|
||||
int? suggestTimeZone({
|
||||
required DateTime now,
|
||||
required Duration Function(DateTime local) offsetAt,
|
||||
}) {
|
||||
final year = now.year;
|
||||
final probes = [now, DateTime(year, 1, 15, 12), DateTime(year, 7, 15, 12)];
|
||||
// From 2: UTC (1) is the fallback below, so a UK phone in winter is not
|
||||
// offered plain UTC.
|
||||
for (var i = 2; i < _firstFixedZone; i++) {
|
||||
final matches = probes.every(
|
||||
(t) => timeZoneOffsetMinutes(i, t.toUtc()) == offsetAt(t).inMinutes,
|
||||
);
|
||||
if (matches) return i;
|
||||
}
|
||||
final current = offsetAt(now).inMinutes;
|
||||
if (current == 0) return 1;
|
||||
for (var i = _firstFixedZone; i < badgeTimeZones.length; i++) {
|
||||
if (badgeTimeZones[i].standardMinutes == current) return i;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:meshcore_open/helpers/region_key.dart';
|
||||
|
||||
/// A flood region as discovered from a repeater.
|
||||
///
|
||||
/// [name] is the `#`-stripped region name the firmware reports over the air.
|
||||
/// Value equality is by name so a discovery service can dedupe replies.
|
||||
class Region {
|
||||
final String name;
|
||||
|
||||
const Region(this.name);
|
||||
|
||||
/// A wildcard region (matches a family of names) rather than a single one.
|
||||
bool get isWildcard => name.contains('*');
|
||||
|
||||
/// A private region whose key is not derivable from its name.
|
||||
bool get isPrivate => isPrivateRegionName(name);
|
||||
|
||||
/// The 16-byte transport key for this region, or null when it is private
|
||||
/// or blank.
|
||||
Uint8List? get transportKey => transportKeyForName(name);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) => other is Region && other.name == name;
|
||||
|
||||
@override
|
||||
int get hashCode => name.hashCode;
|
||||
|
||||
@override
|
||||
String toString() => 'Region($name)';
|
||||
}
|
||||
@ -0,0 +1,580 @@
|
||||
// CLI console (#883 local, #999 remote; interop plan F2/E2.1 + F3/E3.1). The
|
||||
// local-device counterpart of RepeaterCliScreen, built to the owner-approved
|
||||
// mockup on #883, and - with a [remoteContact] - the surface for remote CLI to
|
||||
// a companion over the mesh. One console, one transcript; the transport
|
||||
// ([CliConsoleTransport]) is what differs (local frame 66/29 vs remote TXT
|
||||
// type-3). Same pattern, minus path/flood selection and retries: one send per
|
||||
// command, a timeout surfaced as its own transcript row.
|
||||
//
|
||||
// Secrecy rule (W3/F4, applied here from day one): a reply to a command that
|
||||
// names a secret (anything containing "pwd"/"password") renders masked and is
|
||||
// only recoverable via long-press-to-copy; its cleartext never enters the
|
||||
// widget tree as selectable text and is never logged by this screen.
|
||||
//
|
||||
// Population gating is NOT here: offering the local console only where the
|
||||
// classifier allows frame 66 is #884; offering the remote console only on a
|
||||
// companion contact is the entry point in chat_screen (#999).
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../connector/device_population.dart';
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../helpers/device_name_validator.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../services/cli_console_transport.dart';
|
||||
|
||||
enum _EntryKind { command, reply, timeout, sendFailed }
|
||||
|
||||
class _ConsoleEntry {
|
||||
_ConsoleEntry.command(this.text)
|
||||
: kind = _EntryKind.command,
|
||||
isError = false,
|
||||
secret = false,
|
||||
truncated = false,
|
||||
latencyMs = null;
|
||||
|
||||
_ConsoleEntry.reply(
|
||||
this.text, {
|
||||
required this.latencyMs,
|
||||
required this.truncated,
|
||||
required this.secret,
|
||||
required this.isError,
|
||||
}) : kind = _EntryKind.reply;
|
||||
|
||||
_ConsoleEntry.timeout(this.text)
|
||||
: kind = _EntryKind.timeout,
|
||||
isError = true,
|
||||
secret = false,
|
||||
truncated = false,
|
||||
latencyMs = null;
|
||||
|
||||
_ConsoleEntry.sendFailed(this.text)
|
||||
: kind = _EntryKind.sendFailed,
|
||||
isError = true,
|
||||
secret = false,
|
||||
truncated = false,
|
||||
latencyMs = null;
|
||||
|
||||
final _EntryKind kind;
|
||||
|
||||
/// For a secret reply this still holds the cleartext (it is the long-press
|
||||
/// copy source) - rendering is what masks it, so nothing here may be handed
|
||||
/// to a logger or a selectable widget when [secret] is set.
|
||||
final String text;
|
||||
final bool isError;
|
||||
final bool secret;
|
||||
final bool truncated;
|
||||
final int? latencyMs;
|
||||
}
|
||||
|
||||
class DeviceCliScreen extends StatefulWidget {
|
||||
const DeviceCliScreen({
|
||||
super.key,
|
||||
this.commandTimeout,
|
||||
this.remoteContact,
|
||||
this.transportOverride,
|
||||
});
|
||||
|
||||
/// Per-command reply window; null uses the transport's default. Tests shrink
|
||||
/// it so a timeout row renders without a 10 s pump. The remote transport
|
||||
/// computes its own mesh window and ignores this.
|
||||
final Duration? commandTimeout;
|
||||
|
||||
/// When set, the console runs CLI on this remote contact over the mesh
|
||||
/// (type-3 for a companion, #999) instead of the connected device.
|
||||
final Contact? remoteContact;
|
||||
|
||||
/// Test seam: a transport to use instead of building one from
|
||||
/// [remoteContact]. Lets a test drive a deterministic reply or timeout. The
|
||||
/// screen takes ownership and disposes it.
|
||||
@visibleForTesting
|
||||
final CliConsoleTransport? transportOverride;
|
||||
|
||||
/// Whether to offer the remote console for [contact]. Two conditions, both
|
||||
/// required: the target is a companion (repeaters and room servers have
|
||||
/// their own CLI via the repeater hub), and the CONNECTED radio speaks the
|
||||
/// 1.18 CLI. A pre-1.18 radio refuses to send a type-3 command
|
||||
/// (companion-v1.17.1 accepts only plain and CLI_DATA in CMD_SEND_TXT_MSG;
|
||||
/// 1.18.0 adds CLI_COMMAND), so offering the console there would only
|
||||
/// produce failures. Type-3 send and the local CLI frame shipped together
|
||||
/// in 1.18, so this reuses the local console's gate. A null classification
|
||||
/// (disconnected, or not yet classified) offers nothing.
|
||||
static bool offersRemoteConsole({
|
||||
required Contact contact,
|
||||
required Classification? classification,
|
||||
}) => contact.isCompanion && (classification?.allowsCliFrame ?? false);
|
||||
|
||||
@override
|
||||
State<DeviceCliScreen> createState() => _DeviceCliScreenState();
|
||||
}
|
||||
|
||||
class _DeviceCliScreenState extends State<DeviceCliScreen> {
|
||||
final TextEditingController _commandController = TextEditingController();
|
||||
final FocusNode _commandFocusNode = FocusNode();
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final List<_ConsoleEntry> _entries = [];
|
||||
int _historyIndex = -1;
|
||||
CliConsoleTransport? _transport;
|
||||
|
||||
bool get _isRemote => widget.remoteContact != null;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
|
||||
_transport =
|
||||
widget.transportOverride ??
|
||||
(widget.remoteContact == null
|
||||
? LocalCliTransport(connector)
|
||||
: RemoteCliTransport(connector, widget.remoteContact!));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_transport?.dispose();
|
||||
_commandController.dispose();
|
||||
_commandFocusNode.dispose();
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// The device-side handlers echo secrets in cleartext (stock `get wifi.pwd`
|
||||
/// reads back the stored password, INVESTIGATION.md section C) - the client
|
||||
/// is the only place masking can happen, so match generously.
|
||||
static bool isSecretCommand(String command) {
|
||||
final c = command.toLowerCase();
|
||||
return c.contains('pwd') || c.contains('password');
|
||||
}
|
||||
|
||||
/// The wire has no error codes; stock firmware answers errors as plain
|
||||
/// "Unknown command" / "Error..." strings (INVESTIGATION.md section A1), so
|
||||
/// error styling is string-matched, exactly as the mockup states.
|
||||
static bool looksLikeErrorReply(String text) {
|
||||
final t = text.trimLeft();
|
||||
return t.startsWith('Unknown command') || t.startsWith('Error');
|
||||
}
|
||||
|
||||
/// Extracts the name argument of a `set name <value>` command (any casing,
|
||||
/// any inner spacing), or null when the command is not one. #885 mirrors the
|
||||
/// device's own name-character rejection before the frame is sent.
|
||||
static String? setNameArg(String command) {
|
||||
final m = RegExp(
|
||||
r'^set\s+name\s+(.+)$',
|
||||
caseSensitive: false,
|
||||
).firstMatch(command.trim());
|
||||
return m?.group(1);
|
||||
}
|
||||
|
||||
Future<void> _sendCommand() async {
|
||||
final command = _commandController.text.trim();
|
||||
if (command.isEmpty) return;
|
||||
final transport = _transport;
|
||||
if (transport == null) return;
|
||||
|
||||
// Mirror the firmware's `set name` character rejection locally: show the
|
||||
// typed command and a rejection row, and never send the frame (#885).
|
||||
final nameArg = setNameArg(command);
|
||||
if (nameArg != null) {
|
||||
final bad = forbiddenCharsIn(nameArg);
|
||||
if (bad.isNotEmpty) {
|
||||
setState(() {
|
||||
_entries.add(_ConsoleEntry.command(command));
|
||||
_entries.add(
|
||||
_ConsoleEntry.sendFailed(
|
||||
context.l10n.deviceCli_nameRejected(bad.join(' ')),
|
||||
),
|
||||
);
|
||||
});
|
||||
_commandController.clear();
|
||||
_historyIndex = -1;
|
||||
_commandFocusNode.requestFocus();
|
||||
_scrollToBottom();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final secret = isSecretCommand(command);
|
||||
setState(() {
|
||||
_entries.add(_ConsoleEntry.command(command));
|
||||
});
|
||||
_commandController.clear();
|
||||
_historyIndex = -1;
|
||||
_commandFocusNode.requestFocus();
|
||||
_scrollToBottom();
|
||||
|
||||
final stopwatch = Stopwatch()..start();
|
||||
_ConsoleEntry entry;
|
||||
try {
|
||||
final reply = await transport.run(
|
||||
command,
|
||||
timeout: widget.commandTimeout,
|
||||
);
|
||||
stopwatch.stop();
|
||||
entry = _ConsoleEntry.reply(
|
||||
reply.text,
|
||||
latencyMs: stopwatch.elapsedMilliseconds,
|
||||
truncated: reply.atReplyBound,
|
||||
secret: secret,
|
||||
isError: looksLikeErrorReply(reply.text),
|
||||
);
|
||||
} on CliConsoleTimeout catch (e) {
|
||||
if (!mounted) return;
|
||||
// A remote companion that has not granted us remote CLI simply never
|
||||
// replies, so a timeout is as likely a permission answer as a lost
|
||||
// packet. The remote row says so and notes we did not retry (#891); the
|
||||
// local row keeps the plain frame-timeout wording. The permission hint
|
||||
// assumes a companion target - the only remote entry (chat_screen) is
|
||||
// companion-gated; a repeater target would need different wording.
|
||||
entry = _ConsoleEntry.timeout(
|
||||
_isRemote
|
||||
? context.l10n.deviceCli_remoteNoReply(command, e.secondsText)
|
||||
: context.l10n.deviceCli_noReply(command, e.secondsText),
|
||||
);
|
||||
} on CliConsoleUnsupported {
|
||||
if (!mounted) return;
|
||||
// The connected radio refused the send itself (pre-1.18 firmware), so
|
||||
// nothing went out: say so now instead of waiting out a timeout that
|
||||
// would blame the target.
|
||||
entry = _ConsoleEntry.sendFailed(
|
||||
context.l10n.deviceCli_remoteUnsupported(command),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
entry = _ConsoleEntry.sendFailed(
|
||||
context.l10n.deviceCli_sendFailed(e.toString()),
|
||||
);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_entries.add(entry);
|
||||
});
|
||||
_scrollToBottom();
|
||||
}
|
||||
|
||||
void _scrollToBottom() {
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _navigateHistory(bool up) {
|
||||
final commands = _entries
|
||||
.where((e) => e.kind == _EntryKind.command)
|
||||
.map((e) => e.text)
|
||||
.toList()
|
||||
.reversed
|
||||
.toList();
|
||||
if (commands.isEmpty) return;
|
||||
|
||||
if (up) {
|
||||
if (_historyIndex < commands.length - 1) {
|
||||
_historyIndex++;
|
||||
}
|
||||
} else {
|
||||
if (_historyIndex > 0) {
|
||||
_historyIndex--;
|
||||
} else {
|
||||
_historyIndex = -1;
|
||||
_commandController.clear();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_historyIndex >= 0 && _historyIndex < commands.length) {
|
||||
_commandController.text = commands[_historyIndex];
|
||||
_commandController.selection = TextSelection.fromPosition(
|
||||
TextPosition(offset: _commandController.text.length),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _clearHistory() {
|
||||
setState(() {
|
||||
_entries.clear();
|
||||
_historyIndex = -1;
|
||||
});
|
||||
}
|
||||
|
||||
void _copySecret(String cleartext) {
|
||||
Clipboard.setData(ClipboardData(text: cleartext));
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.deviceCli_secretCopied),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final String title;
|
||||
final String subtitle;
|
||||
if (_isRemote) {
|
||||
title = l10n.deviceCli_remoteTitle;
|
||||
subtitle = widget.remoteContact!.name;
|
||||
} else {
|
||||
title = l10n.deviceCli_title;
|
||||
final name = connector.selfName;
|
||||
final version = connector.firmwareVersion;
|
||||
subtitle = [
|
||||
if (name != null && name.isNotEmpty) name,
|
||||
if (version != null && version.isNotEmpty) '($version)',
|
||||
].join(' ');
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(title),
|
||||
if (subtitle.isNotEmpty)
|
||||
Text(
|
||||
subtitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
centerTitle: false,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.clear_all),
|
||||
tooltip: l10n.repeater_clearHistory,
|
||||
onPressed: _entries.isEmpty ? null : _clearHistory,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _entries.isEmpty ? _buildEmptyState() : _buildTranscript(),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
_buildCommandInput(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmptyState() {
|
||||
final l10n = context.l10n;
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.terminal, size: 64, color: Colors.grey[400]),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
l10n.repeater_noCommandsSent,
|
||||
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
l10n.deviceCli_emptyHint,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTranscript() {
|
||||
return ListView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: _entries.length,
|
||||
itemBuilder: (context, index) => _buildEntry(_entries[index]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEntry(_ConsoleEntry entry) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final isCommand = entry.kind == _EntryKind.command;
|
||||
|
||||
final badgeColor = entry.isError
|
||||
? scheme.errorContainer
|
||||
: isCommand
|
||||
? scheme.primaryContainer
|
||||
: scheme.secondaryContainer;
|
||||
final badgeIconColor = entry.isError
|
||||
? scheme.onErrorContainer
|
||||
: isCommand
|
||||
? scheme.onPrimaryContainer
|
||||
: scheme.onSecondaryContainer;
|
||||
final badgeIcon = switch (entry.kind) {
|
||||
_EntryKind.command => Icons.chevron_right,
|
||||
_EntryKind.reply when entry.isError => Icons.warning_amber,
|
||||
_EntryKind.reply => Icons.arrow_back,
|
||||
_EntryKind.timeout => Icons.timer_off_outlined,
|
||||
_EntryKind.sendFailed => Icons.warning_amber,
|
||||
};
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeColor,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Icon(badgeIcon, size: 16, color: badgeIconColor),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
entry.secret ? _buildSecretText(entry) : _buildPlainText(entry),
|
||||
if (entry.truncated) _buildTruncationBadge(),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (entry.latencyMs != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
context.l10n.deviceCli_latencyMs(entry.latencyMs!),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: Theme.of(context).colorScheme.outline,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPlainText(_ConsoleEntry entry) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final color = entry.isError
|
||||
? scheme.error
|
||||
: entry.kind == _EntryKind.command
|
||||
? scheme.primary
|
||||
: scheme.onSurface;
|
||||
return SelectableText(
|
||||
entry.text,
|
||||
style: TextStyle(fontFamily: 'monospace', fontSize: 13, color: color),
|
||||
);
|
||||
}
|
||||
|
||||
/// Masked rendering: fixed-width dots regardless of the secret's length
|
||||
/// (the dot count must not leak it), cleartext only via long-press copy.
|
||||
Widget _buildSecretText(_ConsoleEntry entry) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return GestureDetector(
|
||||
onLongPress: () => _copySecret(entry.text),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'●' * 8,
|
||||
style: TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 13,
|
||||
color: scheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
context.l10n.deviceCli_secretLongPressToCopy,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: scheme.outline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTruncationBadge() {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.content_cut, size: 12, color: scheme.tertiary),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
context.l10n.deviceCli_truncatedByDevice,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontStyle: FontStyle.italic,
|
||||
color: scheme.tertiary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCommandInput() {
|
||||
final l10n = context.l10n;
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SafeArea(
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_upward, size: 20),
|
||||
tooltip: l10n.repeater_previousCommand,
|
||||
onPressed: () => _navigateHistory(true),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_downward, size: 20),
|
||||
tooltip: l10n.repeater_nextCommand,
|
||||
onPressed: () => _navigateHistory(false),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _commandController,
|
||||
focusNode: _commandFocusNode,
|
||||
decoration: InputDecoration(
|
||||
hintText: l10n.deviceCli_commandHint,
|
||||
border: const OutlineInputBorder(),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
prefixText: '> ',
|
||||
),
|
||||
style: const TextStyle(fontFamily: 'monospace'),
|
||||
textInputAction: TextInputAction.send,
|
||||
onSubmitted: (_) => _sendCommand(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton.filled(
|
||||
icon: const Icon(Icons.send),
|
||||
onPressed: _sendCommand,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,184 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../services/region_discovery_service.dart';
|
||||
|
||||
/// Discover the flood regions a repeater advertises (Feature #812, Epic #814).
|
||||
///
|
||||
/// Launched from the repeater hub for a specific repeater, so the source node
|
||||
/// is [repeater]; the reply carries only region names and the repeater clock
|
||||
/// (there is no per-region SNR on the wire). Each outcome renders distinctly:
|
||||
/// loading, the region list, no-regions, timeout, or error.
|
||||
class DiscoverRegionsScreen extends StatefulWidget {
|
||||
const DiscoverRegionsScreen({
|
||||
super.key,
|
||||
required this.repeater,
|
||||
this.service,
|
||||
});
|
||||
|
||||
final Contact repeater;
|
||||
|
||||
/// Test seam: inject a service with a fake discoverer. In production the
|
||||
/// service is built from the connector.
|
||||
final RegionDiscoveryService? service;
|
||||
|
||||
@override
|
||||
State<DiscoverRegionsScreen> createState() => _DiscoverRegionsScreenState();
|
||||
}
|
||||
|
||||
class _DiscoverRegionsScreenState extends State<DiscoverRegionsScreen> {
|
||||
late final RegionDiscoveryService _service;
|
||||
late final bool _ownsService;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final injected = widget.service;
|
||||
_ownsService = injected == null;
|
||||
if (injected != null) {
|
||||
_service = injected;
|
||||
} else {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
_service = RegionDiscoveryService(
|
||||
(pub, timeout) =>
|
||||
connector.discoverRegions(repeaterPubKey: pub, timeout: timeout),
|
||||
);
|
||||
}
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _start();
|
||||
});
|
||||
}
|
||||
|
||||
void _start() => _service.discover(widget.repeater.publicKey);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_ownsService) _service.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(l10n.discoverRegions_title),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: ListenableBuilder(
|
||||
listenable: _service,
|
||||
builder: (context, _) => _body(l10n),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(AppLocalizations l10n) {
|
||||
final name = widget.repeater.name;
|
||||
switch (_service.status) {
|
||||
case RegionDiscoveryStatus.idle:
|
||||
case RegionDiscoveryStatus.loading:
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const CircularProgressIndicator(),
|
||||
const SizedBox(height: 16),
|
||||
Text(l10n.discoverRegions_loading(name)),
|
||||
],
|
||||
),
|
||||
);
|
||||
case RegionDiscoveryStatus.success:
|
||||
return _regionList(l10n);
|
||||
case RegionDiscoveryStatus.empty:
|
||||
return _message(
|
||||
stateKey: 'discoverRegionsEmpty',
|
||||
icon: Icons.location_off,
|
||||
text: l10n.discoverRegions_empty(name),
|
||||
l10n: l10n,
|
||||
);
|
||||
case RegionDiscoveryStatus.timeout:
|
||||
return _message(
|
||||
stateKey: 'discoverRegionsTimeout',
|
||||
icon: Icons.timer_off,
|
||||
text: l10n.discoverRegions_timeout(name),
|
||||
l10n: l10n,
|
||||
);
|
||||
case RegionDiscoveryStatus.error:
|
||||
return _message(
|
||||
stateKey: 'discoverRegionsError',
|
||||
icon: Icons.error_outline,
|
||||
text: _service.errorMessage ?? l10n.discoverRegions_error,
|
||||
l10n: l10n,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _regionList(AppLocalizations l10n) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.cell_tower),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.discoverRegions_source(widget.repeater.name),
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: _service.regions.length,
|
||||
itemBuilder: (context, i) {
|
||||
final region = _service.regions[i];
|
||||
return ListTile(
|
||||
leading: Icon(region.isWildcard ? Icons.public : Icons.tag),
|
||||
title: Text(region.name),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _message({
|
||||
required String stateKey,
|
||||
required IconData icon,
|
||||
required String text,
|
||||
required AppLocalizations l10n,
|
||||
}) {
|
||||
return Center(
|
||||
key: Key(stateKey),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 48),
|
||||
const SizedBox(height: 12),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32),
|
||||
child: Text(text, textAlign: TextAlign.center),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: ElevatedButton(
|
||||
key: const Key('discoverRegionsRetry'),
|
||||
onPressed: _start,
|
||||
child: Text(l10n.discoverRegions_retry),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/offband_device_ui.dart';
|
||||
import '../../connector/offband_screen_settings.dart';
|
||||
import '../../widgets/device_ui_error_banner.dart';
|
||||
|
||||
/// Where the badge's battery bar puts 100%, and how it got there (#987):
|
||||
/// the badge's own Battery screen, with its two actions. Gated on caps byte 2
|
||||
/// `0x40`. English-only, matching [DeviceUiView].
|
||||
class BadgeBatteryView extends StatefulWidget {
|
||||
const BadgeBatteryView({super.key});
|
||||
|
||||
@override
|
||||
State<BadgeBatteryView> createState() => _BadgeBatteryViewState();
|
||||
}
|
||||
|
||||
/// Where the full point came from, in the badge's terms (default, learned,
|
||||
/// set). Shared with the Node Settings row.
|
||||
String batteryFullSource(ScreenSettingsState s) => s.batteryFullStored == 0
|
||||
? 'Default for this board'
|
||||
: s.batteryPinned
|
||||
? 'Set by hand'
|
||||
: 'Learned after a full charge';
|
||||
|
||||
class _BadgeBatteryViewState extends State<BadgeBatteryView> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) context.read<MeshCoreConnector>().requestScreenSettings();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pin(MeshCoreConnector connector) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Set 100% here?'),
|
||||
content: const Text(
|
||||
'Only do this with the radio fully charged. The radio uses its '
|
||||
'current reading as full, and stops learning it.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: const Text('Set 100% here'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true) await connector.setBatteryFull(pin: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final s = connector.screenSettings;
|
||||
final error = connector.deviceUiError;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final mv = connector.batteryMillivolts;
|
||||
final pct = connector.batteryPercent;
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
if (error != null &&
|
||||
connector.deviceUiErrorSurface == DeviceUiSurface.screenSettings)
|
||||
DeviceUiErrorBanner(
|
||||
message: error,
|
||||
onDismiss: connector.clearDeviceUiError,
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
),
|
||||
if (pct != null) Text('$pct%', style: textTheme.headlineMedium),
|
||||
if (mv != null) Text('Reading $mv mV'),
|
||||
const SizedBox(height: 12),
|
||||
if (s == null)
|
||||
const ListTile(
|
||||
leading: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
title: Text('Reading battery settings from the radio'),
|
||||
)
|
||||
else ...[
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.battery_std),
|
||||
title: Text('100% at ${s.batteryFullMv} mV'),
|
||||
subtitle: Text(batteryFullSource(s)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'The radio learns where full is after a complete charge. Set it by '
|
||||
'hand only if the bar never reaches 100% when charged.',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: () => _pin(connector),
|
||||
icon: const Icon(Icons.bolt),
|
||||
label: const Text('Set 100% here'),
|
||||
),
|
||||
// Only when there is something to hand back, as on the badge.
|
||||
if (s.batteryFullStored != 0)
|
||||
TextButton(
|
||||
onPressed: () => connector.setBatteryFull(pin: false),
|
||||
child: const Text('Back to auto'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/offband_device_ui.dart';
|
||||
import '../../connector/offband_screen_settings.dart';
|
||||
import '../../models/badge_time_zones.dart';
|
||||
import '../../widgets/device_ui_error_banner.dart';
|
||||
|
||||
/// The badge's own screen settings (#987): its Nav text, Message text, Screen
|
||||
/// off and Time zone rows, with the same choices and no others. Gated on caps
|
||||
/// byte 2 `0x40`; the Node Settings row that leads here is gated the same way.
|
||||
///
|
||||
/// Every control draws from the radio's re-read reply, never from the tap.
|
||||
/// English-only, matching [DeviceUiView].
|
||||
class BadgeScreenView extends StatefulWidget {
|
||||
const BadgeScreenView({super.key});
|
||||
|
||||
@override
|
||||
State<BadgeScreenView> createState() => _BadgeScreenViewState();
|
||||
}
|
||||
|
||||
class _BadgeScreenViewState extends State<BadgeScreenView> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) context.read<MeshCoreConnector>().requestScreenSettings();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final s = connector.screenSettings;
|
||||
final error = connector.deviceUiError;
|
||||
return ListView(
|
||||
children: [
|
||||
if (error != null &&
|
||||
connector.deviceUiErrorSurface == DeviceUiSurface.screenSettings)
|
||||
DeviceUiErrorBanner(
|
||||
message: error,
|
||||
onDismiss: connector.clearDeviceUiError,
|
||||
),
|
||||
if (s == null)
|
||||
const ListTile(
|
||||
leading: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
title: Text('Reading screen settings from the radio'),
|
||||
)
|
||||
else ...[
|
||||
const _Header('Text size'),
|
||||
// The badge's Nav text and Message text, named for what they govern
|
||||
// (owner decision 2026-10-25).
|
||||
_TextSizeRow(
|
||||
label: 'Menus and lists',
|
||||
value: s.navText,
|
||||
onChanged: (v) =>
|
||||
connector.setTextSize(BadgeTextTarget.navigation, v),
|
||||
),
|
||||
_TextSizeRow(
|
||||
label: 'Messages',
|
||||
value: s.messageText,
|
||||
onChanged: (v) =>
|
||||
connector.setTextSize(BadgeTextTarget.messages, v),
|
||||
),
|
||||
const _Header('Screen off'),
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||
child: Text(
|
||||
'How long the screen stays on after the last key press.',
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: SegmentedButton<int>(
|
||||
segments: [
|
||||
for (final secs in screenOffSteps)
|
||||
ButtonSegment(value: secs, label: Text(screenOffLabel(secs))),
|
||||
],
|
||||
selected: {
|
||||
if (screenOffSteps.contains(s.screenOffStored))
|
||||
s.screenOffStored,
|
||||
},
|
||||
emptySelectionAllowed: true,
|
||||
onSelectionChanged: (v) {
|
||||
if (v.isNotEmpty) connector.setScreenOff(v.first);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (!screenOffSteps.contains(s.screenOffStored))
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||
child: Text(
|
||||
s.screenOffIsDefault
|
||||
? 'Board default: ${screenOffLabel(s.screenOffSeconds)}'
|
||||
: 'Set to ${screenOffLabel(s.screenOffStored)} elsewhere',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
const _Header('Time zone'),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.public),
|
||||
title: Text(timeZoneName(s.timeZone)),
|
||||
subtitle: Text(_zoneSubtitle(s.timeZone)),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => TimeZonePickerScreen(current: s.timeZone),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _zoneSubtitle(int index) {
|
||||
final offset = timeZoneOffsetMinutes(index, DateTime.now().toUtc());
|
||||
if (offset == null) {
|
||||
return index == timeZoneNotSet
|
||||
? 'Messages show their age'
|
||||
: 'A zone this app does not know';
|
||||
}
|
||||
return '${formatUtcOffset(offset)} now. Message times show as clock times.';
|
||||
}
|
||||
}
|
||||
|
||||
class _Header extends StatelessWidget {
|
||||
const _Header(this.title);
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
|
||||
child: Text(title, style: Theme.of(context).textTheme.titleMedium),
|
||||
);
|
||||
}
|
||||
|
||||
class _TextSizeRow extends StatelessWidget {
|
||||
const _TextSizeRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final BadgeTextSize? value;
|
||||
final ValueChanged<BadgeTextSize> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label),
|
||||
const SizedBox(height: 4),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: SegmentedButton<BadgeTextSize>(
|
||||
segments: [
|
||||
for (final size in BadgeTextSize.values)
|
||||
ButtonSegment(value: size, label: Text(size.label)),
|
||||
],
|
||||
selected: {?value},
|
||||
emptySelectionAllowed: true,
|
||||
onSelectionChanged: (v) {
|
||||
if (v.isNotEmpty) onChanged(v.first);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge's zone list, with "not set" and a suggestion from the phone's
|
||||
/// own zone, as the badge suggests one from GPS.
|
||||
class TimeZonePickerScreen extends StatefulWidget {
|
||||
const TimeZonePickerScreen({super.key, required this.current});
|
||||
|
||||
final int current;
|
||||
|
||||
@override
|
||||
State<TimeZonePickerScreen> createState() => _TimeZonePickerScreenState();
|
||||
}
|
||||
|
||||
class _TimeZonePickerScreenState extends State<TimeZonePickerScreen> {
|
||||
String _query = '';
|
||||
|
||||
void _choose(int index) {
|
||||
context.read<MeshCoreConnector>().setTimeZone(index);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final now = DateTime.now();
|
||||
final suggested = suggestTimeZone(
|
||||
now: now,
|
||||
offsetAt: (local) => local.timeZoneOffset,
|
||||
);
|
||||
final q = _query.trim().toLowerCase();
|
||||
bool shown(int i) => q.isEmpty || timeZoneName(i).toLowerCase().contains(q);
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
|
||||
Widget zoneTile(int i, {bool suggestion = false}) {
|
||||
final offset = timeZoneOffsetMinutes(i, now.toUtc());
|
||||
final selected = !suggestion && i == widget.current;
|
||||
return ListTile(
|
||||
leading: suggestion
|
||||
? const Icon(Icons.smartphone)
|
||||
: Icon(
|
||||
selected
|
||||
? Icons.radio_button_checked
|
||||
: Icons.radio_button_unchecked,
|
||||
color: selected ? scheme.primary : null,
|
||||
),
|
||||
title: Text(timeZoneName(i)),
|
||||
subtitle: suggestion
|
||||
? const Text('Matches this phone')
|
||||
: selected
|
||||
? const Text('Current')
|
||||
: i == timeZoneNotSet
|
||||
? const Text('Messages show their age')
|
||||
: null,
|
||||
trailing: offset == null ? null : Text(formatUtcOffset(offset)),
|
||||
selected: selected,
|
||||
onTap: () => _choose(i),
|
||||
);
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Time zone'), centerTitle: true),
|
||||
body: ListView(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
child: SearchBar(
|
||||
hintText: 'Search zones',
|
||||
leading: const Icon(Icons.search),
|
||||
onChanged: (v) => setState(() => _query = v),
|
||||
),
|
||||
),
|
||||
if (suggested != null && shown(suggested)) ...[
|
||||
zoneTile(suggested, suggestion: true),
|
||||
const Divider(height: 1),
|
||||
],
|
||||
for (var i = 0; i < badgeTimeZones.length; i++)
|
||||
if (shown(i)) zoneTile(i),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,748 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/offband_device_ui.dart';
|
||||
import '../../helpers/snack_bar_builder.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../models/offband_gps_status.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
|
||||
/// Embeddable view (no Scaffold) for the Location settings pane (#977).
|
||||
///
|
||||
/// The single home for GPS: the GPS control and its status, the node's
|
||||
/// coordinates, and the position reporting interval. These used to sit in Node
|
||||
/// Settings and a Location dialog, with the GPS toggle in both. The radio sees
|
||||
/// the same writes as before: the same custom vars, the same validation, the
|
||||
/// same error messages.
|
||||
///
|
||||
/// One deliberate difference: coordinates and the reporting interval now save
|
||||
/// independently. In the old dialog an empty or invalid interval returned early
|
||||
/// and silently skipped the coordinates as well.
|
||||
///
|
||||
/// On a radio that advertises caps byte 2 `0x20` (#969) the GPS card is one
|
||||
/// Off / On / Power save control with one status row, per the approved mockups
|
||||
/// in `docs/initiatives/standalone/975-settings-restructure/`. Everything shown
|
||||
/// there is the device's reply, never the request. Other radios keep the plain
|
||||
/// on/off toggle above, unchanged.
|
||||
class LocationView extends StatefulWidget {
|
||||
const LocationView({super.key});
|
||||
|
||||
@override
|
||||
State<LocationView> createState() => _LocationViewState();
|
||||
}
|
||||
|
||||
class _LocationViewState extends State<LocationView> {
|
||||
OffbandGpsStatus? _gpsStatus;
|
||||
bool _queryingGps = false;
|
||||
bool _queriedOnce = false;
|
||||
|
||||
/// Activity and the wait to the next attempt change on their own, so while
|
||||
/// this pane is open the GPS state is re-read on a slow cadence. One 2-byte
|
||||
/// request every 30 s, and only while visible.
|
||||
Timer? _gpsRefresh;
|
||||
static const _gpsRefreshEvery = Duration(seconds: 30);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
_refreshGpsMode(context.read<MeshCoreConnector>());
|
||||
});
|
||||
_gpsRefresh = Timer.periodic(_gpsRefreshEvery, (_) {
|
||||
if (mounted) _refreshGpsMode(context.read<MeshCoreConnector>());
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_gpsRefresh?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Re-read GPS mode, and the 0xC1 fix details that give the last-fix line.
|
||||
///
|
||||
/// Unawaited on purpose (a timer and a button call it), so a send that fails
|
||||
/// because the link dropped mid-refresh is logged rather than escaping.
|
||||
void _refreshGpsMode(MeshCoreConnector connector) {
|
||||
if (!connector.supportsGpsMode) return;
|
||||
connector.requestGpsMode().catchError((Object e) {
|
||||
appLogger.warn('GPS mode refresh failed: $e', tag: 'Location');
|
||||
});
|
||||
if (connector.supportsOffbandGps) {
|
||||
connector
|
||||
.requestOffbandGps()
|
||||
.then((s) {
|
||||
if (mounted && s != null) setState(() => _gpsStatus = s);
|
||||
})
|
||||
.catchError((Object e) {
|
||||
appLogger.warn('GPS fix refresh failed: $e', tag: 'Location');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final customVars = connector.currentCustomVars ?? const <String, String>{};
|
||||
// A radio with no GPS hardware reports no `gps` custom var at all, which is
|
||||
// how the old screens decided to hide the GPS controls too.
|
||||
final hasGps = customVars.containsKey('gps');
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
if (connector.supportsGpsMode) ...[
|
||||
_gpsModeCard(connector),
|
||||
const SizedBox(height: 16),
|
||||
] else if (hasGps) ...[
|
||||
Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.gps_fixed),
|
||||
title: Text(l10n.settings_locationGPSEnable),
|
||||
subtitle: Text(l10n.settings_locationGPSEnableSubtitle),
|
||||
value: customVars['gps'] == '1',
|
||||
onChanged: (value) => _setGpsEnabled(connector, value),
|
||||
),
|
||||
if (connector.supportsOffbandGps)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
|
||||
child: _buildGpsQuerySection(
|
||||
context,
|
||||
_gpsStatus ?? connector.offbandGpsStatus,
|
||||
() => _queryGps(connector),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(Icons.location_on_outlined),
|
||||
title: Text(l10n.settings_locationCoordinates),
|
||||
subtitle: Text(_coordinatesText(connector)),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _editCoordinates(connector),
|
||||
),
|
||||
if (hasGps) ...[
|
||||
const Divider(height: 1),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.schedule),
|
||||
title: Text(l10n.settings_locationReportInterval),
|
||||
subtitle: Text(_intervalText(customVars)),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _editReportInterval(connector, customVars),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// #969: one control for whether AND how GPS runs, the way the badge's own
|
||||
/// screen writes it, then one status row, then the Power-save sleep.
|
||||
Widget _gpsModeCard(MeshCoreConnector connector) {
|
||||
final l10n = context.l10n;
|
||||
final state = connector.gpsModeState;
|
||||
final error = connector.deviceUiErrorSurface == DeviceUiSurface.gpsMode
|
||||
? connector.deviceUiError
|
||||
: null;
|
||||
|
||||
final children = <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
|
||||
child: Text(
|
||||
l10n.settings_gpsModeLabel,
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
if (state == null) {
|
||||
children.add(
|
||||
ListTile(
|
||||
leading: const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
title: Text(l10n.settings_gpsReading),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
children.addAll([
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 14),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: SegmentedButton<GpsMode>(
|
||||
segments: [
|
||||
ButtonSegment(
|
||||
value: GpsMode.off,
|
||||
label: Text(l10n.settings_gpsModeOff),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: GpsMode.on,
|
||||
label: Text(l10n.settings_gpsModeOn),
|
||||
),
|
||||
// Offered only where this build can run it: a radio speaking
|
||||
// the GPS sub-codes without the duty cycle says so in ps_ok.
|
||||
if (state.powerSaveAvailable)
|
||||
ButtonSegment(
|
||||
value: GpsMode.powerSave,
|
||||
label: Text(l10n.settings_gpsModePowerSave),
|
||||
),
|
||||
],
|
||||
selected: {state.mode},
|
||||
onSelectionChanged: (picked) =>
|
||||
connector.setGpsMode(picked.first),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
_gpsStatusTile(connector, state),
|
||||
if (state.mode == GpsMode.powerSave) ...[
|
||||
const Divider(height: 1),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.hourglass_empty),
|
||||
title: Text(l10n.settings_gpsSleepTitle),
|
||||
subtitle: Text(
|
||||
state.intervalSeconds == 0
|
||||
? l10n.settings_gpsSleepDefault
|
||||
: _durationText(state.intervalSeconds),
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _editSleepInterval(connector, state),
|
||||
),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
// Held until dismissed: a refusal the user cannot finish reading is not
|
||||
// surfaced at all (SAFELANE §6).
|
||||
children.addAll([
|
||||
const Divider(height: 1),
|
||||
ListTile(
|
||||
leading: Icon(
|
||||
Icons.error_outline,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
title: Text(error),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
|
||||
onPressed: connector.clearDeviceUiError,
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: children,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// One row for what GPS is doing: activity, next attempt, and last fix, so
|
||||
/// nothing on the card is said twice.
|
||||
Widget _gpsStatusTile(MeshCoreConnector connector, GpsModeState state) {
|
||||
final l10n = context.l10n;
|
||||
final activity = state.activity;
|
||||
|
||||
final (IconData icon, Color color, String title) = switch (activity) {
|
||||
GpsActivity.off => (
|
||||
Icons.gps_off,
|
||||
Colors.grey,
|
||||
l10n.settings_gpsActivityOff,
|
||||
),
|
||||
GpsActivity.on => (
|
||||
Icons.gps_fixed,
|
||||
Colors.green,
|
||||
l10n.settings_gpsActivityOn,
|
||||
),
|
||||
GpsActivity.searching => (
|
||||
Icons.gps_not_fixed,
|
||||
Colors.orange,
|
||||
l10n.settings_gpsActivitySearching,
|
||||
),
|
||||
GpsActivity.sleeping => (
|
||||
Icons.bedtime_outlined,
|
||||
Colors.blueGrey,
|
||||
l10n.settings_gpsActivitySleeping,
|
||||
),
|
||||
GpsActivity.backedOff => (
|
||||
Icons.pause_circle_outline,
|
||||
Colors.orange,
|
||||
l10n.settings_gpsActivityBackedOff,
|
||||
),
|
||||
// A state newer firmware knows and this client does not: say what the
|
||||
// mode is rather than guess at what it is doing.
|
||||
null => switch (state.mode) {
|
||||
GpsMode.off => (
|
||||
Icons.gps_off,
|
||||
Colors.grey,
|
||||
l10n.settings_gpsActivityOff,
|
||||
),
|
||||
GpsMode.on => (
|
||||
Icons.gps_fixed,
|
||||
Colors.green,
|
||||
l10n.settings_gpsActivityOn,
|
||||
),
|
||||
GpsMode.powerSave => (
|
||||
Icons.gps_not_fixed,
|
||||
Colors.orange,
|
||||
l10n.settings_gpsModePowerSave,
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
final details = <String>[];
|
||||
if (state.mode == GpsMode.off) {
|
||||
details.add(l10n.settings_gpsOffDetail);
|
||||
} else {
|
||||
if (state.waitSeconds > 0) {
|
||||
details.add(
|
||||
state.waitSeconds >= 60
|
||||
? l10n.settings_gpsNextTryMinutes(
|
||||
(state.waitSeconds / 60).round(),
|
||||
)
|
||||
: l10n.settings_gpsNextTrySeconds(state.waitSeconds),
|
||||
);
|
||||
}
|
||||
final fix = _gpsStatus ?? connector.offbandGpsStatus;
|
||||
final at = fix?.timestampUtc;
|
||||
if (at != null) {
|
||||
final ago = DateTime.now().toUtc().difference(at.toUtc()).inMinutes;
|
||||
details.add(l10n.settings_gpsLastFixMinutes(ago < 0 ? 0 : ago));
|
||||
}
|
||||
final sats = fix?.satellites;
|
||||
if (sats != null && sats > 0 && state.waitSeconds == 0) {
|
||||
details.add(l10n.settings_gpsSatellites(sats));
|
||||
}
|
||||
}
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(icon, color: color),
|
||||
title: Text(title),
|
||||
subtitle: details.isEmpty ? null : Text(details.join(', ')),
|
||||
trailing: TextButton(
|
||||
onPressed: () => _refreshGpsMode(connector),
|
||||
child: Text(l10n.settings_gpsQuery),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _durationText(int seconds) {
|
||||
final l10n = context.l10n;
|
||||
if (seconds % 60 == 0) {
|
||||
return l10n.settings_locationEveryMinutes(seconds ~/ 60);
|
||||
}
|
||||
return l10n.settings_locationEverySeconds(seconds);
|
||||
}
|
||||
|
||||
/// The sleep interval. 0 is a legal value meaning the firmware default, so
|
||||
/// the reporting interval's 60-second floor must not be copied here. The
|
||||
/// radio raises 1 to 299 to 300, and the row shows what it stored.
|
||||
void _editSleepInterval(MeshCoreConnector connector, GpsModeState state) {
|
||||
final l10n = context.l10n;
|
||||
final controller = TextEditingController(
|
||||
text: state.intervalSeconds.toString(),
|
||||
);
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.settings_gpsSleepTitle),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_gpsSleepFieldLabel,
|
||||
helperText: l10n.settings_gpsSleepFieldHint,
|
||||
helperMaxLines: 3,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: false,
|
||||
signed: false,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
final text = controller.text.trim();
|
||||
final seconds = text.isEmpty ? 0 : int.tryParse(text);
|
||||
Navigator.pop(dialogContext);
|
||||
if (seconds == null || seconds < 0 || seconds > 0xFFFFFFFF) {
|
||||
// Held until tapped away: an error that vanishes on a timer
|
||||
// before it is read is not surfaced (SAFELANE §6).
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_gpsSleepInvalid),
|
||||
persist: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
connector.setGpsMode(state.mode, intervalSeconds: seconds);
|
||||
},
|
||||
child: Text(l10n.common_save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _coordinatesText(MeshCoreConnector connector) {
|
||||
final lat = connector.selfLatitude;
|
||||
final lon = connector.selfLongitude;
|
||||
if (lat == null || lon == null) return context.l10n.settings_locationNotSet;
|
||||
return '${lat.toStringAsFixed(6)}, ${lon.toStringAsFixed(6)}';
|
||||
}
|
||||
|
||||
String _intervalText(Map<String, String> customVars) {
|
||||
final l10n = context.l10n;
|
||||
final seconds = int.tryParse(customVars['gps_interval'] ?? '');
|
||||
if (seconds == null || seconds <= 0) return l10n.settings_locationNotSet;
|
||||
if (seconds % 60 == 0) {
|
||||
return l10n.settings_locationEveryMinutes(seconds ~/ 60);
|
||||
}
|
||||
return l10n.settings_locationEverySeconds(seconds);
|
||||
}
|
||||
|
||||
Future<void> _setGpsEnabled(MeshCoreConnector connector, bool value) async {
|
||||
try {
|
||||
await connector.setCustomVar(value ? 'gps:1' : 'gps:0');
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: const Text(
|
||||
'Could not update GPS setting. Please try again.',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _queryGps(MeshCoreConnector connector) async {
|
||||
setState(() => _queryingGps = true);
|
||||
final s = await connector.requestOffbandGps();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_queryingGps = false;
|
||||
_queriedOnce = true;
|
||||
_gpsStatus = s;
|
||||
});
|
||||
}
|
||||
|
||||
Widget _buildGpsQuerySection(
|
||||
BuildContext context,
|
||||
OffbandGpsStatus? status,
|
||||
VoidCallback onRefresh,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
Widget row(String label, String value) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(label),
|
||||
Text(value, style: const TextStyle(fontWeight: FontWeight.w500)),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
final children = <Widget>[
|
||||
const Divider(),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.settings_gpsStatusTitle,
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
),
|
||||
if (_queryingGps)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: l10n.settings_gpsStatusRefresh,
|
||||
onPressed: onRefresh,
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
if (status != null) {
|
||||
final live = status.hasLiveFix;
|
||||
final color = live ? Colors.green : Colors.orange;
|
||||
children.add(
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
live ? Icons.gps_fixed : Icons.gps_off,
|
||||
size: 18,
|
||||
color: color,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
live
|
||||
? l10n.settings_gpsStatusLiveFix
|
||||
: l10n.settings_gpsStatusNoFix,
|
||||
style: TextStyle(color: color, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
children.add(const SizedBox(height: 8));
|
||||
final coords = (status.latitude != null && status.longitude != null)
|
||||
? '${status.latitude!.toStringAsFixed(6)}, '
|
||||
'${status.longitude!.toStringAsFixed(6)}'
|
||||
: '—';
|
||||
children.add(row(l10n.settings_gpsStatusCoords, coords));
|
||||
children.add(
|
||||
row(l10n.settings_gpsStatusSats, status.satellites?.toString() ?? '—'),
|
||||
);
|
||||
children.add(
|
||||
row(
|
||||
l10n.settings_gpsStatusAltitude,
|
||||
status.altitudeCm != null
|
||||
? '${(status.altitudeCm! / 100).toStringAsFixed(1)} m'
|
||||
: '—',
|
||||
),
|
||||
);
|
||||
final t = status.timestampUtc?.toLocal();
|
||||
final ml = MaterialLocalizations.of(context);
|
||||
final timeStr = t == null
|
||||
? '—'
|
||||
: '${ml.formatCompactDate(t)} '
|
||||
'${ml.formatTimeOfDay(TimeOfDay.fromDateTime(t))}';
|
||||
children.add(row(l10n.settings_gpsStatusTime, timeStr));
|
||||
} else {
|
||||
children.add(
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text(
|
||||
_queriedOnce
|
||||
? l10n.settings_gpsStatusNoResponse
|
||||
: l10n.settings_gpsStatusTapRefresh,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: children,
|
||||
);
|
||||
}
|
||||
|
||||
void _editCoordinates(MeshCoreConnector connector) {
|
||||
final l10n = context.l10n;
|
||||
final latController = TextEditingController(
|
||||
text: connector.selfLatitude?.toStringAsFixed(6) ?? '',
|
||||
);
|
||||
final lonController = TextEditingController(
|
||||
text: connector.selfLongitude?.toStringAsFixed(6) ?? '',
|
||||
);
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.settings_locationCoordinates),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: latController,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_latitude,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
signed: true,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: lonController,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_longitude,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
signed: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
Navigator.pop(dialogContext);
|
||||
|
||||
final latText = latController.text.trim();
|
||||
final lonText = lonController.text.trim();
|
||||
if (latText.isEmpty && lonText.isEmpty) return;
|
||||
|
||||
final lat = latText.isNotEmpty
|
||||
? double.tryParse(latText)
|
||||
: connector.selfLatitude;
|
||||
final lon = lonText.isNotEmpty
|
||||
? double.tryParse(lonText)
|
||||
: connector.selfLongitude;
|
||||
if (lat == null || lon == null) {
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_locationBothRequired),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_locationInvalid),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await connector.setNodeLocation(lat: lat, lon: lon);
|
||||
await connector.refreshDeviceInfo();
|
||||
} catch (_) {
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Could not update location. Please try again.',
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_locationUpdated),
|
||||
);
|
||||
},
|
||||
child: Text(l10n.common_save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _editReportInterval(
|
||||
MeshCoreConnector connector,
|
||||
Map<String, String> customVars,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
// Same default the old dialog pre-filled: 900 seconds when the radio has
|
||||
// not reported an interval.
|
||||
final current = int.tryParse(customVars['gps_interval'] ?? '') ?? 900;
|
||||
final intervalController = TextEditingController(text: current.toString());
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.settings_locationReportInterval),
|
||||
content: TextField(
|
||||
controller: intervalController,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_locationIntervalSec,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: false,
|
||||
signed: false,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
Navigator.pop(dialogContext);
|
||||
|
||||
final intervalText = intervalController.text.trim();
|
||||
if (intervalText.isEmpty) return;
|
||||
|
||||
final interval = int.tryParse(intervalText);
|
||||
if (interval == null || interval < 60 || interval >= 86400) {
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_locationIntervalInvalid),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await connector.setCustomVar('gps_interval:$interval');
|
||||
await connector.refreshDeviceInfo();
|
||||
} catch (_) {
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Could not update location. Please try again.',
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(l10n.settings_locationUpdated),
|
||||
);
|
||||
},
|
||||
child: Text(l10n.common_save),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,324 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/offband_device_ui.dart';
|
||||
import '../../connector/offband_tones.dart';
|
||||
import '../../widgets/device_ui_error_banner.dart';
|
||||
import '../../widgets/radio_tone.dart';
|
||||
|
||||
/// Edit one custom tune slot on the radio (#970).
|
||||
///
|
||||
/// Opens with the stored tune read back (`SLOT_READ`), so a filled slot can be
|
||||
/// changed rather than only replaced. Typing is checked with firmware's own
|
||||
/// validator and words before anything is sent, since the radio can only
|
||||
/// answer "malformed". Saving is the chunked `SLOT_SET`; the radio replaces
|
||||
/// the slot only on the final chunk, so a failed save changes nothing.
|
||||
///
|
||||
/// English-only, matching [DeviceUiView].
|
||||
class TuneSlotEditorScreen extends StatefulWidget {
|
||||
const TuneSlotEditorScreen({
|
||||
super.key,
|
||||
required this.slot,
|
||||
required this.info,
|
||||
});
|
||||
|
||||
final int slot;
|
||||
final TuneSlotInfo info;
|
||||
|
||||
@override
|
||||
State<TuneSlotEditorScreen> createState() => _TuneSlotEditorScreenState();
|
||||
}
|
||||
|
||||
class _TuneSlotEditorScreenState extends State<TuneSlotEditorScreen> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
/// What the radio holds, once read. Null while reading, or if the read
|
||||
/// failed: then the slot's content is unknown and Play saved is off.
|
||||
String? _saved;
|
||||
bool _reading = false;
|
||||
int _readBytes = 0;
|
||||
bool _saving = false;
|
||||
int _sentBytes = 0;
|
||||
int _sendTotal = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.addListener(() => setState(() {}));
|
||||
if (widget.info.isEmpty) {
|
||||
_saved = '';
|
||||
} else {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _read());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _read() async {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
setState(() => _reading = true);
|
||||
final text = await connector.readTuneSlot(
|
||||
widget.slot,
|
||||
onProgress: (n) {
|
||||
if (mounted) setState(() => _readBytes = n);
|
||||
},
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_reading = false;
|
||||
_saved = text;
|
||||
if (text != null) _controller.text = text;
|
||||
});
|
||||
}
|
||||
|
||||
bool get _busy => _reading || _saving;
|
||||
String get _text => _controller.text;
|
||||
bool get _dirty => _text != (_saved ?? '');
|
||||
|
||||
Future<void> _save() async {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
final navigator = Navigator.of(context);
|
||||
final text = _text;
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_sentBytes = 0;
|
||||
_sendTotal = text.length;
|
||||
});
|
||||
final ok = await connector.saveTuneSlot(
|
||||
widget.slot,
|
||||
text,
|
||||
onProgress: (sent, total) {
|
||||
if (mounted) setState(() => _sentBytes = sent);
|
||||
},
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_saving = false;
|
||||
if (ok) _saved = text;
|
||||
});
|
||||
if (!ok) return;
|
||||
// Pop after the rebuild, so PopScope sees the saved state and does not
|
||||
// ask to discard a tune that was just saved.
|
||||
await WidgetsBinding.instance.endOfFrame;
|
||||
if (mounted) navigator.pop();
|
||||
}
|
||||
|
||||
Future<void> _clear() async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text('Clear slot ${widget.slot + 1}?'),
|
||||
content: const Text(
|
||||
'The tune is removed from the radio. Events and channels using it '
|
||||
'stop playing it.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: const Text('Clear'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
_controller.text = '';
|
||||
await _save();
|
||||
}
|
||||
|
||||
Future<void> _playSaved() async {
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final note = describeTunePlay(
|
||||
await connector.playTune(slotTuneId(widget.slot)),
|
||||
);
|
||||
if (note == null) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(note),
|
||||
duration: const Duration(days: 1),
|
||||
action: SnackBarAction(label: 'OK', onPressed: () {}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> _confirmDiscard() async {
|
||||
final discard = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Discard changes?'),
|
||||
content: const Text('This tune has not been saved to the radio.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: const Text('Keep editing'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: const Text('Discard'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return discard == true;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final problem = rtttlProblem(_text);
|
||||
final emptyText = _text.isEmpty;
|
||||
// Firmware's own words fit 21 badge columns and do not say that order is
|
||||
// the problem, which it usually is for RTTTL from elsewhere. When the
|
||||
// header is the only fault, say so and offer the fix.
|
||||
final orderFix = emptyText ? null : fixRtttlDefaultsOrder(_text);
|
||||
final helper = emptyText
|
||||
? (_saved == null ? '' : 'Type or paste an RTTTL tune')
|
||||
: problem == RtttlProblem.ok
|
||||
? 'Plays as "${deriveSlotName(_text)}"'
|
||||
: orderFix != null
|
||||
? 'The badge reads d=, o=, b= in that order, each once'
|
||||
: problem.text;
|
||||
final helperIsProblem = !emptyText && problem != RtttlProblem.ok;
|
||||
final savedHasTune = _saved != null && _saved!.isNotEmpty;
|
||||
final error = connector.deviceUiError;
|
||||
final showError =
|
||||
error != null &&
|
||||
(connector.deviceUiErrorSurface == DeviceUiSurface.tuneSlot ||
|
||||
connector.deviceUiErrorSurface == DeviceUiSurface.tunePlay);
|
||||
|
||||
return PopScope(
|
||||
// Held while a read or save is in flight: leaving would abandon it
|
||||
// halfway, and the radio would keep the old tune.
|
||||
canPop: !_dirty && !_busy,
|
||||
onPopInvokedWithResult: (didPop, _) async {
|
||||
if (didPop) return;
|
||||
if (_busy) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Wait for the radio to finish, then go back.'),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final navigator = Navigator.of(context);
|
||||
if (await _confirmDiscard()) navigator.pop();
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('Slot ${widget.slot + 1}'),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
if (showError)
|
||||
DeviceUiErrorBanner(
|
||||
message: error,
|
||||
onDismiss: connector.clearDeviceUiError,
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
readOnly: _busy,
|
||||
minLines: 4,
|
||||
maxLines: 8,
|
||||
maxLength: maxSlotRtttl,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
// RTTTL is plain ASCII on one line; the radio stores bytes.
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[\x20-\x7E]')),
|
||||
],
|
||||
style: const TextStyle(fontFamily: 'monospace'),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'RTTTL',
|
||||
border: const OutlineInputBorder(),
|
||||
helperText: helperIsProblem ? null : helper,
|
||||
errorText: helperIsProblem ? helper : null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
alignment: WrapAlignment.end,
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
if (orderFix != null)
|
||||
TextButton(
|
||||
onPressed: _busy ? null : () => _controller.text = orderFix,
|
||||
child: const Text('Fix order'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _busy || !savedHasTune ? null : _clear,
|
||||
style: TextButton.styleFrom(foregroundColor: scheme.error),
|
||||
child: const Text('Clear slot'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _busy || !savedHasTune || _dirty
|
||||
? null
|
||||
: _playSaved,
|
||||
icon: const Icon(Icons.play_circle_outline),
|
||||
label: const Text('Play saved'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed:
|
||||
_busy ||
|
||||
!_dirty ||
|
||||
emptyText ||
|
||||
problem != RtttlProblem.ok
|
||||
? null
|
||||
: _save,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_reading) ...[
|
||||
const SizedBox(height: 16),
|
||||
LinearProgressIndicator(
|
||||
value: widget.info.length == 0
|
||||
? null
|
||||
: _readBytes / widget.info.length,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Reading from the radio: $_readBytes of '
|
||||
'${widget.info.length} characters',
|
||||
),
|
||||
],
|
||||
if (_saving) ...[
|
||||
const SizedBox(height: 16),
|
||||
LinearProgressIndicator(
|
||||
value: _sendTotal == 0 ? null : _sentBytes / _sendTotal,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_sendTotal == 0
|
||||
? 'Clearing the slot'
|
||||
: 'Sending to the radio: $_sentBytes of $_sendTotal '
|
||||
'characters',
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Play saved plays what is on the radio, so it is off while there '
|
||||
'are unsaved changes.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,589 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../storage/prefs_manager.dart';
|
||||
import 'file_log_service.dart';
|
||||
|
||||
/// One `ApplicationExitInfo` record, as the platform channel delivers it.
|
||||
class ExitRecord {
|
||||
const ExitRecord({
|
||||
required this.reason,
|
||||
required this.reasonName,
|
||||
required this.timestampMs,
|
||||
required this.pid,
|
||||
this.description,
|
||||
this.processName,
|
||||
this.importance = 0,
|
||||
this.pssKb = 0,
|
||||
this.rssKb = 0,
|
||||
this.status = 0,
|
||||
this.traceBytes,
|
||||
this.traceUnavailable,
|
||||
this.traceTruncated = false,
|
||||
});
|
||||
|
||||
factory ExitRecord.fromMap(Map<Object?, Object?> map) {
|
||||
int asInt(Object? v) => v is int ? v : (v is num ? v.toInt() : 0);
|
||||
return ExitRecord(
|
||||
reason: asInt(map['reason']),
|
||||
reasonName: map['reasonName'] as String? ?? 'UNKNOWN',
|
||||
timestampMs: asInt(map['timestampMs']),
|
||||
pid: asInt(map['pid']),
|
||||
description: map['description'] as String?,
|
||||
processName: map['processName'] as String?,
|
||||
importance: asInt(map['importance']),
|
||||
pssKb: asInt(map['pssKb']),
|
||||
rssKb: asInt(map['rssKb']),
|
||||
status: asInt(map['status']),
|
||||
traceBytes: map['traceBytes'] as Uint8List?,
|
||||
traceUnavailable: map['traceUnavailable'] as String?,
|
||||
traceTruncated: map['traceTruncated'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
final int reason;
|
||||
final String reasonName;
|
||||
final int timestampMs;
|
||||
final int pid;
|
||||
final String? description;
|
||||
final String? processName;
|
||||
final int importance;
|
||||
final int pssKb;
|
||||
final int rssKb;
|
||||
final int status;
|
||||
final Uint8List? traceBytes;
|
||||
final String? traceUnavailable;
|
||||
final bool traceTruncated;
|
||||
|
||||
/// Reasons that mean the app was killed or broke, as opposed to a routine
|
||||
/// stop. Drives the log level so an ANR does not read like a normal exit.
|
||||
bool get isNoteworthy => const {
|
||||
'ANR',
|
||||
'CRASH',
|
||||
'CRASH_NATIVE',
|
||||
'LOW_MEMORY',
|
||||
'EXCESSIVE_RESOURCE_USAGE',
|
||||
'FREEZER',
|
||||
'INITIALIZATION_FAILURE',
|
||||
}.contains(reasonName);
|
||||
}
|
||||
|
||||
/// Every message this service can surface, in one place.
|
||||
///
|
||||
/// They live here rather than inline so the tests can assert each one is
|
||||
/// produced by its own failure and absent on the happy path, which is the
|
||||
/// standing requirement for anything handed over for testing. The alternative
|
||||
/// would be faking `path_provider` to read the log file back, and there is no
|
||||
/// precedent for that in this test suite.
|
||||
abstract final class ExitInfoMessages {
|
||||
static const String notAndroid =
|
||||
'exit-info capture is Android only, skipping';
|
||||
|
||||
static const String nullResult =
|
||||
'getExitRecords returned null, nothing logged';
|
||||
|
||||
static String unsupported(Object? reason, Object? sdkInt) =>
|
||||
'exit-info capture unavailable: ${reason ?? 'unknown'} (sdkInt=$sdkInt); '
|
||||
'devices below API 30 keep no exit records';
|
||||
|
||||
static String queryFailed(String code, String? message) =>
|
||||
'exit-info query failed: $code ${message ?? ''}'.trimRight();
|
||||
|
||||
static String captureFailed(Object error) =>
|
||||
'exit-info capture failed: $error';
|
||||
|
||||
static String traceDirMissing(int pid) =>
|
||||
'no logs directory, trace for pid $pid not written';
|
||||
|
||||
static String traceWriteFailed(String name, Object error) =>
|
||||
'could not write trace $name: $error';
|
||||
|
||||
static String pruneFailed(Object error) => 'trace pruning failed: $error';
|
||||
|
||||
static String listFailed(Object error) => 'could not list trace dir: $error';
|
||||
|
||||
static String watermarkReadFailed(Object error) =>
|
||||
'could not read exit watermark, treating as first run: $error';
|
||||
|
||||
static String watermarkWriteFailed(Object error) =>
|
||||
'could not persist exit watermark, may re-log: $error';
|
||||
|
||||
static String forceBlockFailed(Object error) =>
|
||||
'forceMainThreadBlock failed: $error';
|
||||
|
||||
/// Not an error. Logged when the Dart isolate block ran its full duration
|
||||
/// without the system raising an ANR, which means no input went unanswered.
|
||||
/// Says why, so the tester is not left guessing (#931).
|
||||
static String dartBlockSurvived(int millis, int encodedBytes) =>
|
||||
'dart isolate block ran ${millis}ms and encoded $encodedBytes bytes, '
|
||||
'but no ANR was raised: Android raises one only when an input event goes '
|
||||
'unanswered for 5 seconds, so keep tapping the screen during the freeze';
|
||||
|
||||
/// Fragments that must never appear in a line produced on the happy path.
|
||||
static const List<String> failureMarkers = [
|
||||
'unavailable:',
|
||||
'failed',
|
||||
'could not',
|
||||
'no logs directory',
|
||||
];
|
||||
}
|
||||
|
||||
/// What [selectExitRecords] decided to do with a batch of records.
|
||||
class ExitSelection {
|
||||
const ExitSelection({
|
||||
required this.records,
|
||||
required this.backfill,
|
||||
required this.traceBudget,
|
||||
required this.newWatermarkMs,
|
||||
});
|
||||
|
||||
/// Only the records newer than the watermark, newest first.
|
||||
final List<ExitRecord> records;
|
||||
|
||||
/// True on the first run, when there is no watermark yet and the system's
|
||||
/// buffer may hold months of history.
|
||||
final bool backfill;
|
||||
|
||||
/// How many of [records] may have their trace written out.
|
||||
final int traceBudget;
|
||||
|
||||
/// Where the watermark moves to, or null when nothing was new.
|
||||
final int? newWatermarkMs;
|
||||
}
|
||||
|
||||
/// Pick the records that have not been logged yet.
|
||||
///
|
||||
/// [all] arrives newest first, as `getHistoricalProcessExitReasons` returns it.
|
||||
/// Records with a timestamp equal to the watermark were already logged, so the
|
||||
/// comparison is strictly greater. Two records sharing a millisecond are both
|
||||
/// greater than the watermark in the same pass, so both are kept and neither is
|
||||
/// lost when the watermark then advances past them.
|
||||
ExitSelection selectExitRecords(
|
||||
List<ExitRecord> all,
|
||||
int? watermarkMs, {
|
||||
int backfillTraceCap = 3,
|
||||
}) {
|
||||
final backfill = watermarkMs == null;
|
||||
final fresh = backfill
|
||||
? List<ExitRecord>.of(all)
|
||||
: all.where((r) => r.timestampMs > watermarkMs).toList();
|
||||
|
||||
if (fresh.isEmpty) {
|
||||
return const ExitSelection(
|
||||
records: [],
|
||||
backfill: false,
|
||||
traceBudget: 0,
|
||||
newWatermarkMs: null,
|
||||
);
|
||||
}
|
||||
|
||||
var highest = fresh.first.timestampMs;
|
||||
for (final r in fresh) {
|
||||
if (r.timestampMs > highest) highest = r.timestampMs;
|
||||
}
|
||||
|
||||
return ExitSelection(
|
||||
records: fresh,
|
||||
backfill: backfill,
|
||||
traceBudget: backfill
|
||||
? (fresh.length < backfillTraceCap ? fresh.length : backfillTraceCap)
|
||||
: fresh.length,
|
||||
newWatermarkMs: highest,
|
||||
);
|
||||
}
|
||||
|
||||
/// Human-readable form of the `RunningAppProcessInfo` importance value. Whether
|
||||
/// the process was in the foreground is the first thing you want to know about
|
||||
/// an ANR, since a cached-process hang is not user-visible.
|
||||
String importanceName(int importance) {
|
||||
switch (importance) {
|
||||
case 100:
|
||||
return 'FOREGROUND';
|
||||
case 125:
|
||||
return 'FOREGROUND_SERVICE';
|
||||
case 200:
|
||||
return 'VISIBLE';
|
||||
case 230:
|
||||
return 'PERCEPTIBLE';
|
||||
case 300:
|
||||
return 'SERVICE';
|
||||
case 350:
|
||||
return 'CANT_SAVE_STATE';
|
||||
case 400:
|
||||
return 'CACHED';
|
||||
case 1000:
|
||||
return 'GONE';
|
||||
default:
|
||||
return importance == 0 ? 'unknown' : 'IMPORTANCE_$importance';
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory figures are documented in kB and are 0 when the system never sampled
|
||||
/// the process, so 0 is rendered as unknown rather than as a real measurement.
|
||||
String _memory(int kb) => kb <= 0 ? 'unknown' : '${kb}kB';
|
||||
|
||||
String _traceField(ExitRecord record, String? writtenFileName) {
|
||||
if (writtenFileName != null) {
|
||||
return record.traceTruncated
|
||||
? 'trace=$writtenFileName(truncated)'
|
||||
: 'trace=$writtenFileName';
|
||||
}
|
||||
final why = record.traceUnavailable;
|
||||
return 'trace=none${why == null ? '' : '($why)'}';
|
||||
}
|
||||
|
||||
/// The log line for one exit record, in the same shape the app log already
|
||||
/// uses: `<iso8601> [LEVEL/Tag] message`.
|
||||
String formatExitLine(
|
||||
ExitRecord record, {
|
||||
required bool backfill,
|
||||
String? writtenFileName,
|
||||
DateTime? now,
|
||||
}) {
|
||||
final stamp = (now ?? DateTime.now()).toIso8601String();
|
||||
final level = record.isNoteworthy ? 'WARN' : 'INFO';
|
||||
final at = DateTime.fromMillisecondsSinceEpoch(
|
||||
record.timestampMs,
|
||||
isUtc: true,
|
||||
).toIso8601String();
|
||||
final desc = record.description;
|
||||
|
||||
final parts = <String>[
|
||||
'reason=${record.reasonName}(${record.reason})',
|
||||
if (desc != null && desc.isNotEmpty) 'desc="$desc"',
|
||||
'at=$at',
|
||||
'pid=${record.pid}',
|
||||
if (record.processName != null) 'proc=${record.processName}',
|
||||
'importance=${importanceName(record.importance)}',
|
||||
'pss=${_memory(record.pssKb)}',
|
||||
'rss=${_memory(record.rssKb)}',
|
||||
'status=${record.status}',
|
||||
_traceField(record, writtenFileName),
|
||||
if (backfill) 'backfill=true',
|
||||
];
|
||||
|
||||
return '$stamp [$level/ExitInfo] ${parts.join(' ')}';
|
||||
}
|
||||
|
||||
/// `anr-<utc>-<pid>.txt`. The UTC stamp sorts lexicographically, which is what
|
||||
/// lets the pruner treat a plain name sort as chronological.
|
||||
String traceFileName(int timestampMs, int pid) {
|
||||
final t = DateTime.fromMillisecondsSinceEpoch(timestampMs, isUtc: true);
|
||||
String two(int v) => v.toString().padLeft(2, '0');
|
||||
final stamp =
|
||||
'${t.year}${two(t.month)}${two(t.day)}T'
|
||||
'${two(t.hour)}${two(t.minute)}${two(t.second)}Z';
|
||||
return 'anr-$stamp-$pid.txt';
|
||||
}
|
||||
|
||||
/// Which trace files to delete, given every file's name and size.
|
||||
///
|
||||
/// Keeps at most [keep] of the newest and holds the total at or under
|
||||
/// [ceilingBytes], dropping oldest first. Names sort chronologically, so the
|
||||
/// caller does not need file timestamps. The newest file is never deleted, even
|
||||
/// when it alone exceeds the ceiling: a trace too big to keep is still the one
|
||||
/// piece of evidence worth having.
|
||||
List<String> traceFilesToPrune(
|
||||
Map<String, int> sizesByName, {
|
||||
int keep = 5,
|
||||
int ceilingBytes = 1024 * 1024,
|
||||
}) {
|
||||
final names = sizesByName.keys.toList()..sort();
|
||||
final doomed = <String>[];
|
||||
|
||||
final surviving = names.toList();
|
||||
while (surviving.length > keep) {
|
||||
doomed.add(surviving.removeAt(0));
|
||||
}
|
||||
|
||||
var total = surviving.fold<int>(0, (sum, n) => sum + (sizesByName[n] ?? 0));
|
||||
while (total > ceilingBytes && surviving.length > 1) {
|
||||
final oldest = surviving.removeAt(0);
|
||||
total -= sizesByName[oldest] ?? 0;
|
||||
doomed.add(oldest);
|
||||
}
|
||||
|
||||
return doomed;
|
||||
}
|
||||
|
||||
/// Reports why the app's previous processes died, by reading the system's own
|
||||
/// exit records on the next launch and writing them into the debug log (#906).
|
||||
///
|
||||
/// Android only, API 30 and up. Everywhere else this is a no-op that says so
|
||||
/// once. ANR traces go to a file beside `offband.log` with a pointer line in the
|
||||
/// log itself, because the log export only ever ships the active log file, and a
|
||||
/// trace written inline would both evict surrounding context and later rotate
|
||||
/// away.
|
||||
class AppExitInfoService {
|
||||
AppExitInfoService._();
|
||||
static final AppExitInfoService instance = AppExitInfoService._();
|
||||
|
||||
static const MethodChannel _channel = MethodChannel(
|
||||
'meshcore_open/app_exit_info',
|
||||
);
|
||||
|
||||
/// SharedPreferences key holding the highest exit timestamp already logged.
|
||||
static const String watermarkKey = 'anr_last_exit_ts_ms';
|
||||
|
||||
static const String traceDirName = 'anr';
|
||||
static const int keepTraceFiles = 5;
|
||||
static const int traceDirCeilingBytes = 1024 * 1024;
|
||||
static const int backfillTraceCap = 3;
|
||||
|
||||
bool _ran = false;
|
||||
|
||||
/// Exit records exist only on Android. Public so the test trigger in Settings
|
||||
/// can hide itself rather than offering a button that does nothing.
|
||||
static bool get isSupportedPlatform =>
|
||||
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
|
||||
|
||||
static bool get _isAndroid => isSupportedPlatform;
|
||||
|
||||
/// The directory ANR traces are written to, or null when file logging is
|
||||
/// unavailable. Used by the log export so the traces ship with the log.
|
||||
static Directory? get traceDir {
|
||||
final logs = FileLogService.instance.logDir;
|
||||
if (logs == null) return null;
|
||||
return Directory('${logs.path}${Platform.pathSeparator}$traceDirName');
|
||||
}
|
||||
|
||||
/// Any ANR trace files currently on disk, oldest first. Empty when there are
|
||||
/// none, when the directory does not exist, or when it cannot be listed.
|
||||
static Future<List<File>> traceFiles() async {
|
||||
final dir = traceDir;
|
||||
if (dir == null) return const [];
|
||||
try {
|
||||
if (!await dir.exists()) return const [];
|
||||
return (await dir.list().toList()).whereType<File>().toList()
|
||||
..sort((a, b) => a.path.compareTo(b.path));
|
||||
} catch (error) {
|
||||
instance._log('WARN', ExitInfoMessages.listFailed(error));
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the system's exit records and log anything not logged before.
|
||||
///
|
||||
/// Safe to call once per launch; a second call is a no-op. Never throws: a
|
||||
/// diagnostic must not be able to break startup. Every failure path writes a
|
||||
/// line, so nothing here is silent.
|
||||
Future<void> collect() async {
|
||||
if (_ran) return;
|
||||
_ran = true;
|
||||
|
||||
if (!_isAndroid) {
|
||||
_log('INFO', ExitInfoMessages.notAndroid);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final raw = await _channel.invokeMapMethod<String, Object?>(
|
||||
'getExitRecords',
|
||||
);
|
||||
if (raw == null) {
|
||||
_log('WARN', ExitInfoMessages.nullResult);
|
||||
return;
|
||||
}
|
||||
|
||||
if (raw['supported'] != true) {
|
||||
_log(
|
||||
'INFO',
|
||||
ExitInfoMessages.unsupported(raw['unsupportedReason'], raw['sdkInt']),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final records = (raw['records'] as List?)
|
||||
?.whereType<Map<Object?, Object?>>()
|
||||
.map(ExitRecord.fromMap)
|
||||
.toList();
|
||||
if (records == null || records.isEmpty) return;
|
||||
|
||||
await _report(records);
|
||||
} on PlatformException catch (error) {
|
||||
// The query failed. Leave the watermark alone so the next launch retries.
|
||||
_log('WARN', ExitInfoMessages.queryFailed(error.code, error.message));
|
||||
} catch (error) {
|
||||
_log('WARN', ExitInfoMessages.captureFailed(error));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _report(List<ExitRecord> records) async {
|
||||
final selection = selectExitRecords(
|
||||
records,
|
||||
_readWatermark(),
|
||||
backfillTraceCap: backfillTraceCap,
|
||||
);
|
||||
if (selection.records.isEmpty) return;
|
||||
|
||||
var tracesWritten = 0;
|
||||
for (final record in selection.records) {
|
||||
String? writtenName;
|
||||
final bytes = record.traceBytes;
|
||||
if (bytes != null &&
|
||||
bytes.isNotEmpty &&
|
||||
tracesWritten < selection.traceBudget) {
|
||||
writtenName = await _writeTrace(record, bytes);
|
||||
if (writtenName != null) tracesWritten++;
|
||||
}
|
||||
FileLogService.instance.write(
|
||||
formatExitLine(
|
||||
record,
|
||||
backfill: selection.backfill,
|
||||
writtenFileName: writtenName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await _prune();
|
||||
await _writeWatermark(selection.newWatermarkMs);
|
||||
|
||||
// FileLogService batches on a 2 second timer, so without this the lines
|
||||
// above can be lost if the process dies again before the next flush,
|
||||
// leaving a trace file on disk with nothing pointing at it.
|
||||
await FileLogService.instance.flushAndGetActiveFile();
|
||||
}
|
||||
|
||||
Future<String?> _writeTrace(ExitRecord record, Uint8List bytes) async {
|
||||
final dir = traceDir;
|
||||
if (dir == null) {
|
||||
_log('WARN', ExitInfoMessages.traceDirMissing(record.pid));
|
||||
return null;
|
||||
}
|
||||
final name = traceFileName(record.timestampMs, record.pid);
|
||||
try {
|
||||
await dir.create(recursive: true);
|
||||
await File(
|
||||
'${dir.path}${Platform.pathSeparator}$name',
|
||||
).writeAsBytes(bytes, flush: true);
|
||||
return name;
|
||||
} catch (error) {
|
||||
// Reported into the main log, which is a different file and so is likely
|
||||
// still writable even when this one is not.
|
||||
_log('WARN', ExitInfoMessages.traceWriteFailed(name, error));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _prune() async {
|
||||
final files = await traceFiles();
|
||||
if (files.isEmpty) return;
|
||||
try {
|
||||
final sizes = <String, int>{};
|
||||
for (final f in files) {
|
||||
sizes[f.uri.pathSegments.last] = await f.length();
|
||||
}
|
||||
final doomed = traceFilesToPrune(
|
||||
sizes,
|
||||
keep: keepTraceFiles,
|
||||
ceilingBytes: traceDirCeilingBytes,
|
||||
);
|
||||
for (final name in doomed) {
|
||||
for (final f in files) {
|
||||
if (f.uri.pathSegments.last == name) {
|
||||
await f.delete();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
_log('WARN', ExitInfoMessages.pruneFailed(error));
|
||||
}
|
||||
}
|
||||
|
||||
int? _readWatermark() {
|
||||
try {
|
||||
return PrefsManager.instance.getInt(watermarkKey);
|
||||
} catch (error) {
|
||||
// Treated as a first run, which backfills under a cap and says so.
|
||||
_log('WARN', ExitInfoMessages.watermarkReadFailed(error));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _writeWatermark(int? value) async {
|
||||
if (value == null) return;
|
||||
try {
|
||||
await PrefsManager.instance.setInt(watermarkKey, value);
|
||||
} catch (error) {
|
||||
// Worth surfacing: the same records will be logged again next launch.
|
||||
_log('WARN', ExitInfoMessages.watermarkWriteFailed(error));
|
||||
}
|
||||
}
|
||||
|
||||
/// Test-only hook, called from the owner-only Experimental section in builds
|
||||
/// compiled with `OFFBAND_ANR_TEST`. Hangs the Android main thread so the
|
||||
/// system raises a real ANR, which is the only way to produce a record to
|
||||
/// read back (#911).
|
||||
Future<void> forceMainThreadBlock({int millis = 20000}) async {
|
||||
if (!_isAndroid) return;
|
||||
try {
|
||||
await _channel.invokeMethod<int>('forceMainThreadBlock', {
|
||||
'millis': millis,
|
||||
});
|
||||
} catch (error) {
|
||||
_log('WARN', ExitInfoMessages.forceBlockFailed(error));
|
||||
}
|
||||
}
|
||||
|
||||
/// Test-only, same double gating as [forceMainThreadBlock]. Blocks the **Dart
|
||||
/// UI isolate** instead of the Android main thread, and blocks it the way the
|
||||
/// real ANRs do rather than with an artificial spin (#931).
|
||||
///
|
||||
/// Why this exists separately. The Kotlin block produces a Java stack, so it
|
||||
/// proved the capture works but could say nothing about whether our own Dart
|
||||
/// frames survive into a trace. The Play clusters show the real ANRs blocking
|
||||
/// on this isolate inside the JSON stringifier and under allocation pressure,
|
||||
/// so encoding a large nested structure in a loop should yield a trace of the
|
||||
/// same shape, and answer whether any of our Dart frames resolve.
|
||||
///
|
||||
/// It spins on purpose. Any `await` inside the loop would yield to the event
|
||||
/// loop, the isolate would keep answering input, and no ANR would fire.
|
||||
Future<void> forceDartIsolateBlock({int millis = 20000}) async {
|
||||
if (!isSupportedPlatform) return;
|
||||
final payload = _blockPayload();
|
||||
// Stopwatch, not DateTime.now(): the wall clock can move backwards (NTP, or
|
||||
// the tester changing it) and would push the deadline away, leaving the app
|
||||
// frozen well past the intended window or indefinitely. The Kotlin block
|
||||
// already uses a monotonic source, so this matches it.
|
||||
final elapsed = Stopwatch()..start();
|
||||
var encoded = 0;
|
||||
while (elapsed.elapsedMilliseconds < millis) {
|
||||
encoded += jsonEncode(payload).length;
|
||||
}
|
||||
// Only reached when the process survived, so the tester gets told why.
|
||||
_log('WARN', ExitInfoMessages.dartBlockSurvived(millis, encoded));
|
||||
await FileLogService.instance.flushAndGetActiveFile();
|
||||
}
|
||||
|
||||
/// Shaped like the stores #334 is about: many keyed entries, each a nested
|
||||
/// object, which is what gets JSON-encoded on this isolate in the real bug.
|
||||
static Map<String, Object?> _blockPayload() => {
|
||||
for (var i = 0; i < 400; i++)
|
||||
'entry_$i': {
|
||||
'id': i,
|
||||
'name': 'contact-$i',
|
||||
'path': List<int>.generate(24, (j) => (i + j) & 0xFF),
|
||||
'meta': {
|
||||
'lastSeen': i * 1000,
|
||||
'snr': -(i % 40),
|
||||
'flags': const ['a', 'b', 'c'],
|
||||
},
|
||||
'text': 'x' * 64,
|
||||
},
|
||||
};
|
||||
|
||||
/// Visible for tests so a second `collect()` can be exercised.
|
||||
@visibleForTesting
|
||||
void resetForTest() => _ran = false;
|
||||
|
||||
void _log(String level, String message) {
|
||||
FileLogService.instance.write(
|
||||
'${DateTime.now().toIso8601String()} [$level/ExitInfo] $message',
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,259 @@
|
||||
// What the CLI console (device_cli_screen) talks to (#999, plan F3/E3.1). The
|
||||
// console renders the same transcript whether the CLI runs on the connected
|
||||
// radio (local frame 66/29) or on a remote contact over the mesh (TXT type
|
||||
// chosen by role, #888/#889). This abstracts the two transports behind one
|
||||
// run()->CliReply call and one timeout type, so the screen holds no
|
||||
// transport-specific branches.
|
||||
//
|
||||
// No auto-retry on the remote leg: a companion that has not granted us remote
|
||||
// CLI (contact flag 0x10 on its side) queues our command as a plain message and
|
||||
// never replies, so retrying only spams the mesh. One send, then a timeout the
|
||||
// console explains (#891). Repeaters use their own screen and keep their retry
|
||||
// behavior there.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../connector/cli_command_codec.dart';
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/contact.dart';
|
||||
import 'local_cli_service.dart';
|
||||
import 'repeater_command_service.dart';
|
||||
|
||||
/// A CLI command's window closed with no reply, regardless of transport. Both
|
||||
/// underlying services carry their own timeout type; the console catches only
|
||||
/// this one so its handling reads the same for a local or a remote command.
|
||||
class CliConsoleTimeout implements Exception {
|
||||
const CliConsoleTimeout({required this.command, required this.secondsText});
|
||||
|
||||
final String command;
|
||||
|
||||
/// The armed window in seconds to one decimal, e.g. `10.0`.
|
||||
final String secondsText;
|
||||
|
||||
@override
|
||||
String toString() => 'CLI command timed out after $secondsText s';
|
||||
}
|
||||
|
||||
/// The connected radio refused to send a remote CLI command at all: its
|
||||
/// firmware does not accept TXT_TYPE_CLI_COMMAND (pre-1.18 answers
|
||||
/// ERR_CODE_UNSUPPORTED_CMD). Distinct from [CliConsoleTimeout], which means
|
||||
/// the command went out and the target never answered.
|
||||
class CliConsoleUnsupported implements Exception {
|
||||
const CliConsoleUnsupported({required this.command});
|
||||
|
||||
final String command;
|
||||
|
||||
@override
|
||||
String toString() => 'The connected radio does not support remote CLI';
|
||||
}
|
||||
|
||||
/// One CLI transport for the console: the connected device, or a remote contact.
|
||||
abstract class CliConsoleTransport {
|
||||
/// Runs [command] and completes with the correlated reply, or throws
|
||||
/// [CliConsoleTimeout] when the window closes with no answer. Other failures
|
||||
/// (codec rejection, send error) surface as their own exceptions.
|
||||
Future<CliReply> run(String command, {Duration? timeout});
|
||||
|
||||
void dispose();
|
||||
}
|
||||
|
||||
/// CLI on the connected radio, over frame 66/29.
|
||||
class LocalCliTransport implements CliConsoleTransport {
|
||||
LocalCliTransport(MeshCoreConnector connector, {LocalCliService? service})
|
||||
: _service = service ?? LocalCliService(connector);
|
||||
|
||||
final LocalCliService _service;
|
||||
|
||||
@override
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
try {
|
||||
return await _service.run(command, timeout: timeout);
|
||||
} on LocalCliTimeout catch (e) {
|
||||
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() => _service.dispose();
|
||||
}
|
||||
|
||||
/// CLI on a remote contact over the mesh. The txt type is chosen by the
|
||||
/// target's role (#888/#889): a companion gets TXT_TYPE_CLI_COMMAND, a
|
||||
/// repeater/room server the universal CLI_DATA. The reply returns as a contact
|
||||
/// message carrying the reflected `cc|` prefix; this listens for it and feeds it
|
||||
/// to the shared correlation in [RepeaterCommandService].
|
||||
class RemoteCliTransport implements CliConsoleTransport {
|
||||
RemoteCliTransport(
|
||||
this._connector,
|
||||
this._target, {
|
||||
RepeaterCommandService? service,
|
||||
}) : _service = service ?? RepeaterCommandService(_connector) {
|
||||
// A companion is a human chat node, so a late/unmatched reply must never
|
||||
// log its text: a slow `get wifi.pwd` round trip would otherwise write the
|
||||
// password to the app log, which the console's masking cannot undo. Match
|
||||
// LocalCliService, which always withholds (#999 review).
|
||||
_service.redactUnmatchedReplyText = true;
|
||||
_sub = _connector.receivedFrames.listen(_onFrame);
|
||||
}
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
final Contact _target;
|
||||
final RepeaterCommandService _service;
|
||||
StreamSubscription<Uint8List>? _sub;
|
||||
bool _disposed = false;
|
||||
|
||||
/// Rejection channel for the command in flight: completed with
|
||||
/// [CliConsoleUnsupported] when the radio refuses the send outright.
|
||||
///
|
||||
/// It only listens while [_armed]: from the moment the text frame is written
|
||||
/// (the `onAttempt` hook fires after the path update and runs straight into
|
||||
/// the frame write, with no yield in between) until the radio answers that
|
||||
/// write. The firmware answers each CMD_SEND_TXT_MSG at once, in order: a
|
||||
/// pre-1.18 radio with ERR_CODE_UNSUPPORTED_CMD for type 3; a 1.18 radio with
|
||||
/// RESP_CODE_SENT carrying an expected-ack of 0, since a CLI command expects
|
||||
/// no ack (companion-v1.18.0 CMD_SEND_TXT_MSG). A plain DM's SENT carries a
|
||||
/// real ack hash, so it never closes the window.
|
||||
///
|
||||
/// ERR_CODE_UNSUPPORTED_CMD is also the firmware's answer to any unknown
|
||||
/// command. Arming at the write, rather than at [run], keeps an unrelated
|
||||
/// refusal from failing a valid command. The residual exposure is one
|
||||
/// landing inside our own send's round trip, on a radio where the connector
|
||||
/// already withholds fork frames.
|
||||
///
|
||||
/// One command at a time: a new [run] replaces the channel, and the replaced
|
||||
/// command falls back to its timeout rather than risk misattribution.
|
||||
Completer<CliReply>? _sendWindow;
|
||||
String? _sendWindowCommand;
|
||||
bool _armed = false;
|
||||
|
||||
void _onFrame(Uint8List frame) {
|
||||
if (_disposed || frame.isEmpty) return;
|
||||
if (frame[0] == respCodeSent) {
|
||||
// [RESP_CODE_SENT][is_flood][expected_ack x4][est_timeout x4]. Only a
|
||||
// command send's SENT (ack 0) answers ours.
|
||||
if (_armed &&
|
||||
frame.length >= 6 &&
|
||||
frame[2] == 0 &&
|
||||
frame[3] == 0 &&
|
||||
frame[4] == 0 &&
|
||||
frame[5] == 0) {
|
||||
_armed = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (frame[0] == respCodeErr) {
|
||||
final code = frame.length > 1 ? frame[1] : -1;
|
||||
final window = _sendWindow;
|
||||
if (_armed &&
|
||||
code == errCodeUnsupportedCmd &&
|
||||
window != null &&
|
||||
!window.isCompleted) {
|
||||
_armed = false;
|
||||
window.completeError(
|
||||
CliConsoleUnsupported(command: _sendWindowCommand ?? ''),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (frame[0] != respCodeContactMsgRecv &&
|
||||
frame[0] != respCodeContactMsgRecvV3) {
|
||||
return;
|
||||
}
|
||||
final parsed = parseContactMessageText(frame);
|
||||
if (parsed == null) return;
|
||||
if (!_matchesTargetPrefix(parsed.senderPrefix)) return;
|
||||
// Only a CLI_DATA reply answers a command. A plain chat message, or an
|
||||
// inbound type-3 command, from the SAME companion must not complete our
|
||||
// pending command - without this it would hit handleResponse's unprefixed
|
||||
// sole-pending fallback and render "hey, you there?" as the CLI reply
|
||||
// (#999 review). Some layouts carry the type shifted; check both.
|
||||
final t = parsed.txtType;
|
||||
if (t != txtTypeCliData && (t >> 2) != txtTypeCliData) return;
|
||||
// Routes to the waiting command's future (or is logged if its window
|
||||
// already closed, #589). handleResponse resolves the target from its key,
|
||||
// so the possibly-stale [_target] is fine here.
|
||||
_service.handleResponse(_resolveTarget(), parsed.text);
|
||||
}
|
||||
|
||||
bool _matchesTargetPrefix(Uint8List prefix) {
|
||||
final key = _target.publicKey;
|
||||
if (key.length < 6 || prefix.length < 6) return false;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
if (prefix[i] != key[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The contact's path can be updated after this transport is built, so re-read
|
||||
/// the live contact by key at send time and fall back to the original.
|
||||
Contact _resolveTarget() {
|
||||
for (final c in _connector.contacts) {
|
||||
if (c.publicKeyHex == _target.publicKeyHex) return c;
|
||||
}
|
||||
return _target;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
final window = Completer<CliReply>();
|
||||
_sendWindow = window;
|
||||
_sendWindowCommand = command;
|
||||
_armed = false;
|
||||
try {
|
||||
// Whichever lands first: the reply (or its timeout), or the radio
|
||||
// refusing the send. Future.any keeps handlers on the loser, so its later
|
||||
// timeout is absorbed rather than surfacing as an unhandled error.
|
||||
return await Future.any([_send(command, window), window.future]);
|
||||
} finally {
|
||||
if (identical(_sendWindow, window)) {
|
||||
_sendWindow = null;
|
||||
_armed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<CliReply> _send(String command, Completer<CliReply> window) async {
|
||||
// retries: 1 - one send, no auto-retry. See the file header.
|
||||
try {
|
||||
final text = await _service.sendCommand(
|
||||
_resolveTarget(),
|
||||
command,
|
||||
retries: 1,
|
||||
// Fires after the path update, immediately before the text frame is
|
||||
// written: arm the rejection window here, not earlier.
|
||||
onAttempt: (_) {
|
||||
if (identical(_sendWindow, window)) _armed = true;
|
||||
},
|
||||
);
|
||||
// payloadLength drives CliReply.atReplyBound (the local 165-byte device
|
||||
// bound). A remote reply is a reassembled mesh message, so that bound is
|
||||
// not meaningful and truncation cannot be detected here; the stripped
|
||||
// text length keeps atReplyBound false rather than faking a cut (#999).
|
||||
return CliReply(
|
||||
prefix: null,
|
||||
text: text,
|
||||
payloadLength: utf8.encode(text).length,
|
||||
);
|
||||
} on RepeaterCommandTimeout catch (e) {
|
||||
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
// Release a command still waiting, so its run() cannot hang.
|
||||
final window = _sendWindow;
|
||||
_sendWindow = null;
|
||||
_armed = false;
|
||||
if (window != null && !window.isCompleted) {
|
||||
window.completeError(StateError('RemoteCliTransport disposed'));
|
||||
}
|
||||
_service.dispose();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
// Shared `cc|` correlation grammar (#882): one allocator and one splitter for
|
||||
// every CLI path - the repeater text-message CLI (RepeaterCommandService) and
|
||||
// the local frame-66 console (LocalCliService). The grammar is the device's:
|
||||
// a 3-char token ending in `|`, reflected at the start of the reply when the
|
||||
// command carried one.
|
||||
|
||||
/// Allocates `XX|` correlation tokens: two uppercase hex digits and a pipe,
|
||||
/// cycling through 256 values and skipping any currently in flight.
|
||||
class PrefixAllocator {
|
||||
int _counter = 0;
|
||||
|
||||
String next(Set<String> inUse) {
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final value = _counter++ & 0xFF;
|
||||
final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|';
|
||||
if (!inUse.contains(token)) return token;
|
||||
}
|
||||
return '00|';
|
||||
}
|
||||
}
|
||||
|
||||
/// A reply split into its reflected correlation token and payload.
|
||||
class Correlated {
|
||||
const Correlated({required this.prefix, required this.payload});
|
||||
|
||||
final String? prefix;
|
||||
final String payload;
|
||||
}
|
||||
|
||||
/// Splits [raw] on the positional prefix rule (third character `|`). The
|
||||
/// payload keeps its leading whitespace trimmed, matching the repeater path's
|
||||
/// long-standing behavior.
|
||||
Correlated splitCorrelated(String raw) {
|
||||
if (raw.length >= 3 && raw[2] == '|') {
|
||||
return Correlated(
|
||||
prefix: raw.substring(0, 3),
|
||||
payload: raw.substring(3).trimLeft(),
|
||||
);
|
||||
}
|
||||
return Correlated(prefix: null, payload: raw);
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
// Local device CLI over frame 66/29 (#882, plan F2/E2.1). Sends
|
||||
// CMD_RUN_CLI_COMMAND to the CONNECTED radio and completes with the
|
||||
// correlated RESP_CODE_CLI_REPLY. No mesh legs, so no retries: the transport
|
||||
// is the connected link, and a lost frame surfaces as a timeout.
|
||||
//
|
||||
// Population gating is NOT here: callers (the console entry point, #884)
|
||||
// must only construct/offer this where the classifier allows frame 66.
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import '../connector/cli_command_codec.dart';
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'command_correlation.dart';
|
||||
|
||||
/// Thrown when the device does not answer inside the window.
|
||||
class LocalCliTimeout implements Exception {
|
||||
const LocalCliTimeout({required this.command, required this.timeout});
|
||||
|
||||
final String command;
|
||||
final Duration timeout;
|
||||
|
||||
/// The armed window in seconds to one decimal, e.g. `10.0` - same shape as
|
||||
/// [RepeaterCommandTimeout.secondsText] so UI strings read alike.
|
||||
String get secondsText => (timeout.inMilliseconds / 1000).toStringAsFixed(1);
|
||||
|
||||
@override
|
||||
String toString() => 'CLI command timed out after $secondsText s';
|
||||
}
|
||||
|
||||
class LocalCliService {
|
||||
LocalCliService(this._connector) {
|
||||
_detach = _connector.addCliReplyListenerForLocalCli(_handleReply);
|
||||
}
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
final PrefixAllocator _prefixes = PrefixAllocator();
|
||||
final Map<String, Completer<CliReply>> _pending = {};
|
||||
final Map<String, Timer> _timeouts = {};
|
||||
void Function()? _detach;
|
||||
|
||||
/// Default window for a local round trip. Generous: some device handlers
|
||||
/// (WiFi status on a busy radio) run tens of milliseconds, and BLE
|
||||
/// notification scheduling adds more; nothing on the local link should
|
||||
/// legitimately take longer than this.
|
||||
static const Duration defaultTimeout = Duration(seconds: 10);
|
||||
|
||||
/// Sends [command] to the connected device; completes with the correlated
|
||||
/// reply or throws [LocalCliTimeout] / [ArgumentError] (codec rejections).
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
final window = timeout ?? defaultTimeout;
|
||||
final prefix = _prefixes.next(_pending.keys.toSet());
|
||||
final frame = buildRunCliCommandFrame(command, prefix: prefix);
|
||||
|
||||
final completer = Completer<CliReply>();
|
||||
_pending[prefix] = completer;
|
||||
_timeouts[prefix] = Timer(window, () {
|
||||
final waiting = _pending.remove(prefix);
|
||||
_timeouts.remove(prefix);
|
||||
if (waiting != null && !waiting.isCompleted) {
|
||||
waiting.completeError(
|
||||
LocalCliTimeout(command: command, timeout: window),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await _connector.sendFrame(frame);
|
||||
} catch (e) {
|
||||
_cleanup(prefix);
|
||||
rethrow;
|
||||
}
|
||||
|
||||
try {
|
||||
return await completer.future;
|
||||
} finally {
|
||||
_cleanup(prefix);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleReply(CliReply reply) {
|
||||
final prefix = reply.prefix;
|
||||
final waiting = prefix != null ? _pending.remove(prefix) : null;
|
||||
if (waiting != null && !waiting.isCompleted) {
|
||||
_timeouts.remove(prefix)?.cancel();
|
||||
waiting.complete(reply);
|
||||
return;
|
||||
}
|
||||
// Every command this service sends carries a prefix, so an unmatched or
|
||||
// prefixless reply answers something that already timed out (or another
|
||||
// sender). Log it - never guess it onto a waiting command (#532's rule).
|
||||
// The reply TEXT is withheld: a late reply to a secret command (e.g.
|
||||
// `get wifi.pwd`) would otherwise write cleartext to the app log, which the
|
||||
// screen's masking cannot undo (Gemini review, #883). The correlation token
|
||||
// and byte length carry the debug value without the content.
|
||||
appLogger.warn(
|
||||
'CLI reply matched no pending command '
|
||||
'(prefix: ${prefix ?? 'none'}, ${reply.payloadLength} bytes); '
|
||||
'text withheld',
|
||||
tag: 'LocalCli',
|
||||
);
|
||||
}
|
||||
|
||||
void _cleanup(String prefix) {
|
||||
_timeouts.remove(prefix)?.cancel();
|
||||
_pending.remove(prefix);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_detach?.call();
|
||||
_detach = null;
|
||||
for (final t in _timeouts.values) {
|
||||
t.cancel();
|
||||
}
|
||||
_timeouts.clear();
|
||||
for (final c in _pending.values) {
|
||||
if (!c.isCompleted) {
|
||||
c.completeError(
|
||||
const LocalCliTimeout(command: '(disposed)', timeout: Duration.zero),
|
||||
);
|
||||
}
|
||||
}
|
||||
_pending.clear();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,106 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/region.dart';
|
||||
|
||||
/// Where a discovery run can land. Each non-success state is distinct so the UI
|
||||
/// can render it as itself (an empty reply is not success; a timeout is not an
|
||||
/// error). (#814)
|
||||
enum RegionDiscoveryStatus { idle, loading, success, empty, timeout, error }
|
||||
|
||||
/// Sends one regions-discovery request to a repeater and returns the reply, or
|
||||
/// null on timeout. In production this is [MeshCoreConnector.discoverRegions];
|
||||
/// tests inject a fake so the lifecycle can be exercised without a radio.
|
||||
typedef RegionsDiscoverer =
|
||||
Future<RegionsReply?> Function(Uint8List repeaterPubKey, Duration timeout);
|
||||
|
||||
/// Drives Discover Regions: ask a chosen repeater which flood regions it
|
||||
/// advertises, dedupe them, and expose a single discovery state for the UI.
|
||||
class RegionDiscoveryService extends ChangeNotifier {
|
||||
RegionDiscoveryService(this._discover);
|
||||
|
||||
final RegionsDiscoverer _discover;
|
||||
|
||||
RegionDiscoveryStatus _status = RegionDiscoveryStatus.idle;
|
||||
List<Region> _regions = const [];
|
||||
int? _clock;
|
||||
String? _errorMessage;
|
||||
bool _disposed = false;
|
||||
|
||||
RegionDiscoveryStatus get status => _status;
|
||||
List<Region> get regions => _regions;
|
||||
|
||||
/// The repeater's clock from the last successful reply (for clock display).
|
||||
int? get clock => _clock;
|
||||
|
||||
/// A human-readable reason when [status] is [RegionDiscoveryStatus.error].
|
||||
String? get errorMessage => _errorMessage;
|
||||
|
||||
bool get isLoading => _status == RegionDiscoveryStatus.loading;
|
||||
|
||||
/// Discover regions from [repeaterPubKey] (a 32-byte node key). Concurrent
|
||||
/// starts are ignored while one is in flight.
|
||||
Future<void> discover(
|
||||
Uint8List repeaterPubKey, {
|
||||
Duration timeout = const Duration(seconds: 10),
|
||||
}) async {
|
||||
if (_status == RegionDiscoveryStatus.loading) return;
|
||||
_status = RegionDiscoveryStatus.loading;
|
||||
_regions = const [];
|
||||
_errorMessage = null;
|
||||
_safeNotify();
|
||||
|
||||
try {
|
||||
final reply = await _discover(repeaterPubKey, timeout);
|
||||
if (reply == null) {
|
||||
_status = RegionDiscoveryStatus.timeout;
|
||||
} else {
|
||||
_clock = reply.clock;
|
||||
final regions = _dedupe(reply.regionNames);
|
||||
if (regions.isEmpty) {
|
||||
_status = RegionDiscoveryStatus.empty;
|
||||
} else {
|
||||
_regions = regions;
|
||||
_status = RegionDiscoveryStatus.success;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_status = RegionDiscoveryStatus.error;
|
||||
_errorMessage = e.toString();
|
||||
}
|
||||
// The screen may have been popped (and this service disposed) while the
|
||||
// discovery future was in flight; notifying a disposed ChangeNotifier
|
||||
// throws, so guard it.
|
||||
_safeNotify();
|
||||
}
|
||||
|
||||
/// Return to the idle state, clearing any prior result.
|
||||
void reset() {
|
||||
_status = RegionDiscoveryStatus.idle;
|
||||
_regions = const [];
|
||||
_clock = null;
|
||||
_errorMessage = null;
|
||||
_safeNotify();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _safeNotify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
/// Dedupe by [Region] value-equality, preserving first-seen order.
|
||||
List<Region> _dedupe(List<String> names) {
|
||||
final seen = <Region>{};
|
||||
final out = <Region>[];
|
||||
for (final name in names) {
|
||||
final region = Region(name);
|
||||
if (seen.add(region)) out.add(region);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,344 @@
|
||||
import '../storage/channel_message_store.dart';
|
||||
import '../storage/drift/blob_store.dart';
|
||||
import '../storage/message_store.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// How long a migrated key keeps its stale blob before the sweep reclaims it.
|
||||
///
|
||||
/// Owner decision, 2026-10-22: 30 days. One full month of real use, matching
|
||||
/// the monthly granularity of the Play install and crash reports he reads, so
|
||||
/// a migration problem has a reporting cycle to surface in before the snapshot
|
||||
/// goes. A named constant so changing it is one edit and tests can pass their
|
||||
/// own window instead of manipulating clocks.
|
||||
const Duration staleHistoryWindow = Duration(days: 30);
|
||||
|
||||
/// What a sweep did. Byte counts come from SQLite, not from adding up blob
|
||||
/// lengths, so they are what actually changed rather than what should have.
|
||||
class StaleHistoryOutcome {
|
||||
const StaleHistoryOutcome({
|
||||
required this.cleared,
|
||||
required this.refused,
|
||||
required this.bytesBefore,
|
||||
required this.bytesAfter,
|
||||
});
|
||||
|
||||
/// Keys whose stale blob was verified redundant and deleted.
|
||||
final List<String> cleared;
|
||||
|
||||
/// Keys that were eligible by age but **kept**, because the blob could not
|
||||
/// be verified against the rows. Surfaced to the user by the manual action
|
||||
/// (#966); the automatic sweep logs them.
|
||||
final List<String> refused;
|
||||
|
||||
final int bytesBefore;
|
||||
final int bytesAfter;
|
||||
|
||||
int get bytesReclaimed => bytesBefore - bytesAfter;
|
||||
|
||||
bool get didAnything => cleared.isNotEmpty;
|
||||
}
|
||||
|
||||
/// What a sweep WOULD do, for the confirmation dialog (#962).
|
||||
class StaleHistoryPreview {
|
||||
const StaleHistoryPreview({
|
||||
required this.eligible,
|
||||
required this.refused,
|
||||
required this.approximateBytes,
|
||||
required this.messagesKept,
|
||||
});
|
||||
|
||||
/// Keys whose stale copy is verified redundant and would be deleted.
|
||||
final List<String> eligible;
|
||||
|
||||
/// Keys already known to be unverifiable, so they would be kept. Saying so
|
||||
/// before the press beats reporting it afterwards.
|
||||
final List<String> refused;
|
||||
|
||||
/// Blob bytes that would go.
|
||||
///
|
||||
/// **Approximate on purpose.** It is the sum of the blob lengths, which is
|
||||
/// not the same as what `VACUUM` returns to the filesystem: page rounding
|
||||
/// and existing free pages both move the real figure. The dialog says
|
||||
/// "about", and the result afterwards reports what actually changed.
|
||||
final int approximateBytes;
|
||||
|
||||
/// Total stored messages, so the dialog can say what is NOT affected. The
|
||||
/// reassurance is the point: this action deletes, and the user needs to know
|
||||
/// their history is not what is being deleted.
|
||||
final int messagesKept;
|
||||
|
||||
bool get hasWork => eligible.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Deletes the frozen pre-migration blob of a key that has been on rows long
|
||||
/// enough, and returns the space to the filesystem (#962).
|
||||
///
|
||||
/// The blob a migrated key leaves behind is a snapshot taken at the migration
|
||||
/// moment, not a mirror: nothing writes it afterwards. So it protects the
|
||||
/// pre-migration history against a migration or read-path bug found later, and
|
||||
/// protects nothing that arrived since, which is single-copy from the instant
|
||||
/// it lands either way. After [staleHistoryWindow] that protection has had its
|
||||
/// chance and the duplicate is just cost.
|
||||
///
|
||||
/// Every delete is gated on asking the rows again, immediately, rather than
|
||||
/// trusting the marker. A key that cannot be verified keeps its blob and says
|
||||
/// so, and is never retried in a loop: a refusal that silently repeats forever
|
||||
/// is what made #952 invisible for days.
|
||||
class StaleHistorySweep {
|
||||
StaleHistorySweep(this._blobs);
|
||||
|
||||
final BlobStore _blobs;
|
||||
|
||||
/// Only these two key shapes have a row equivalent. `contacts`,
|
||||
/// `discovered_contacts` and `path_history_` live in blobs as their ONLY
|
||||
/// storage, so they are never candidates, and this is asserted by name in
|
||||
/// the tests rather than left to the marker to get right.
|
||||
static const List<String> _historyPrefixes = [
|
||||
'channel_messages_',
|
||||
'messages_',
|
||||
];
|
||||
|
||||
static bool isHistoryKey(String key) => _historyPrefixes.any(key.startsWith);
|
||||
|
||||
/// The converter for a key, chosen by its shape. Channel and direct
|
||||
/// histories encode differently, and using the wrong one would make every
|
||||
/// record look missing, which refuses rather than deletes.
|
||||
static BlobToRowsCallback converterFor(String key) =>
|
||||
key.startsWith('channel_messages_')
|
||||
? channelHistoryToRows
|
||||
: dmHistoryToRows;
|
||||
|
||||
/// Whether a key is old enough to reclaim. The ONE age rule, shared by
|
||||
/// [preview] and [run], so the dialog cannot promise what the sweep will not
|
||||
/// do.
|
||||
///
|
||||
/// A key with no timestamp, or one stamped during this pass, has no age to
|
||||
/// judge. For the automatic sweep that means **not eligible**: the stamp
|
||||
/// exists so installing an update never deletes a blob on sight. For an
|
||||
/// explicit press it means **eligible**, because a user asking to clear now
|
||||
/// is not an app update. Treating the two the same made the button report
|
||||
/// "nothing to clear" on any install that migrated before #962, which is
|
||||
/// every real install, since none of their keys carry a stamp yet.
|
||||
static bool eligibleByAge({
|
||||
required DateTime? migratedAt,
|
||||
required bool freshlyStamped,
|
||||
required Duration window,
|
||||
required DateTime at,
|
||||
required bool includeNewlyStamped,
|
||||
}) {
|
||||
if (freshlyStamped || migratedAt == null) return includeNewlyStamped;
|
||||
return at.difference(migratedAt) >= window;
|
||||
}
|
||||
|
||||
/// What a sweep would do, without doing any of it (#962).
|
||||
///
|
||||
/// The confirmation dialog states real numbers rather than an estimate, so
|
||||
/// the verification has to run before the delete rather than as part of it.
|
||||
/// The cost is that it happens twice for a confirmed clear: once here, once
|
||||
/// under the key lock in [run]. That is the price of saying what will go
|
||||
/// before it goes.
|
||||
///
|
||||
/// Writes nothing. In particular it does not stamp, so calling it never
|
||||
/// changes what a later [run] does.
|
||||
Future<StaleHistoryPreview> preview({
|
||||
Duration? olderThan,
|
||||
DateTime? now,
|
||||
bool includeNewlyStamped = false,
|
||||
}) async {
|
||||
final window = olderThan ?? staleHistoryWindow;
|
||||
final at = now ?? DateTime.now();
|
||||
|
||||
final eligible = <String>[];
|
||||
final refused = <String>[];
|
||||
var bytes = 0;
|
||||
|
||||
for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) {
|
||||
if (!isHistoryKey(key)) continue;
|
||||
if (!await _blobs.isOnMessageRows(key)) continue;
|
||||
if (!eligibleByAge(
|
||||
migratedAt: await _blobs.messageRowsMigratedAt(key),
|
||||
freshlyStamped: false,
|
||||
window: window,
|
||||
at: at,
|
||||
includeNewlyStamped: includeNewlyStamped,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final blob = await _blobs.read(key);
|
||||
if (blob == null) continue; // already reclaimed
|
||||
|
||||
final missing = await _blobs.missingFromRows(key, converterFor(key));
|
||||
if (missing == null || missing.isNotEmpty) {
|
||||
refused.add(key);
|
||||
continue;
|
||||
}
|
||||
eligible.add(key);
|
||||
bytes += blob.length;
|
||||
}
|
||||
|
||||
return StaleHistoryPreview(
|
||||
eligible: eligible,
|
||||
refused: refused,
|
||||
approximateBytes: bytes,
|
||||
messagesKept: await _blobs.totalMessageRows(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs one sweep.
|
||||
///
|
||||
/// [olderThan] defaults to [staleHistoryWindow]; [now] exists so tests can
|
||||
/// choose a moment rather than wait. Backfills a timestamp onto any
|
||||
/// already-migrated key that has none. [includeNewlyStamped] decides whether
|
||||
/// such a key can be cleared on the same pass: false for the automatic
|
||||
/// sweep, true for an explicit press. See [eligibleByAge].
|
||||
Future<StaleHistoryOutcome> run({
|
||||
Duration? olderThan,
|
||||
DateTime? now,
|
||||
bool includeNewlyStamped = false,
|
||||
}) async {
|
||||
final window = olderThan ?? staleHistoryWindow;
|
||||
final at = now ?? DateTime.now();
|
||||
final bytesBefore = await _blobs.databaseSizeBytes();
|
||||
|
||||
// Stamp first. A key seen for the first time gets the full window from
|
||||
// now, so updating the app never deletes a blob on the spot.
|
||||
final stamped = await _blobs.backfillMigratedAt(now: at);
|
||||
|
||||
final cleared = <String>[];
|
||||
final refused = <String>[];
|
||||
|
||||
for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) {
|
||||
if (!isHistoryKey(key)) continue;
|
||||
if (!await _blobs.isOnMessageRows(key)) continue;
|
||||
if (!eligibleByAge(
|
||||
migratedAt: await _blobs.messageRowsMigratedAt(key),
|
||||
freshlyStamped: stamped.contains(key),
|
||||
window: window,
|
||||
at: at,
|
||||
includeNewlyStamped: includeNewlyStamped,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verify and delete under the key's own lock, as one step. Deciding on
|
||||
// one call and deleting on another leaves a window, and a delete made on
|
||||
// a stale answer cannot be taken back.
|
||||
final result = await _blobs.reclaimVerifiedHistoryBlob(
|
||||
key,
|
||||
converterFor(key),
|
||||
);
|
||||
|
||||
if (result.deleted) {
|
||||
cleared.add(key);
|
||||
continue;
|
||||
}
|
||||
final missing = result.missing;
|
||||
if (missing == null) {
|
||||
// Unverifiable, NOT verified-empty. Keep it.
|
||||
refused.add(key);
|
||||
continue;
|
||||
}
|
||||
if (missing.isNotEmpty) {
|
||||
appLogger.error(
|
||||
'Keeping the stale blob for $key: ${missing.length} of its records '
|
||||
'have no row (e.g. ${missing.take(3).join(', ')}). The blob stays '
|
||||
'the only copy of those and is not deleted.',
|
||||
tag: 'Storage',
|
||||
);
|
||||
refused.add(key);
|
||||
}
|
||||
// Otherwise there was no blob left to reclaim: not cleared, not refused.
|
||||
}
|
||||
|
||||
if (cleared.isNotEmpty) {
|
||||
// VACUUM takes an exclusive lock and rebuilds the file, so database
|
||||
// access queues behind it. It does NOT block the UI thread: drift_flutter
|
||||
// runs SQLite in a spawned isolate (`_isolateEntrypoint` ->
|
||||
// `DriftIsolate.inCurrent`), so this is a stall on history-backed reads
|
||||
// rather than an ANR, which is the distinction that matters for an app
|
||||
// whose storage work started as an ANR investigation.
|
||||
//
|
||||
// It is also close to once per install: a key is cleared once and then
|
||||
// has no blob to consider, so later launches delete nothing and never
|
||||
// reach here. Measured at 0.6 s on the owner's 70.9 MiB database. The
|
||||
// duration is logged because that is a number worth watching in the
|
||||
// field rather than assuming.
|
||||
final sw = Stopwatch()..start();
|
||||
try {
|
||||
await _blobs.vacuum();
|
||||
appLogger.info(
|
||||
'VACUUM took ${sw.elapsedMilliseconds} ms after clearing '
|
||||
'${cleared.length} stale blob(s).',
|
||||
tag: 'Storage',
|
||||
);
|
||||
} catch (e) {
|
||||
// The deletes already happened and were each verified; VACUUM only
|
||||
// affects file size, so a failure here costs space and not data. The
|
||||
// next sweep retries it.
|
||||
appLogger.warn(
|
||||
'Deleted ${cleared.length} stale blob(s) but VACUUM failed, so the '
|
||||
'space is free for reuse and not yet returned to the filesystem: '
|
||||
'$e',
|
||||
tag: 'Storage',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A sweep that deleted blobs correctly must not be reported as a failure
|
||||
// because the closing size read threw. The deletes are the work; the byte
|
||||
// count is reporting. Falling back to `bytesBefore` makes the reclaimed
|
||||
// figure read as 0, which understates rather than invents, and keeps the
|
||||
// manual action from telling the user nothing happened when something did
|
||||
// (Gemini review).
|
||||
int bytesAfter;
|
||||
try {
|
||||
bytesAfter = await _blobs.databaseSizeBytes();
|
||||
} catch (e) {
|
||||
appLogger.warn(
|
||||
'Cleared ${cleared.length} stale blob(s) but could not read the '
|
||||
'database size afterwards, so the reclaimed figure reads as 0: $e',
|
||||
tag: 'Storage',
|
||||
);
|
||||
bytesAfter = bytesBefore;
|
||||
}
|
||||
|
||||
if (cleared.isNotEmpty || refused.isNotEmpty) {
|
||||
// Names the keys, not just a count. "Cleared 40" is not an audit trail
|
||||
// for a delete that cannot be undone.
|
||||
appLogger.info(
|
||||
'Stale history sweep: cleared ${cleared.length}, kept '
|
||||
'${refused.length} that could not be verified, '
|
||||
'${bytesBefore - bytesAfter} bytes returned.\n'
|
||||
'cleared: ${cleared.join(', ')}'
|
||||
'${refused.isEmpty ? '' : '\nkept: ${refused.join(', ')}'}',
|
||||
tag: 'Storage',
|
||||
);
|
||||
|
||||
// And durably, because the log above is gated on the app-debug-logging
|
||||
// setting, which is off by default. Without this an irreversible delete
|
||||
// would leave no trail at all on a normal install.
|
||||
try {
|
||||
await _blobs.appendReclaimAudit(
|
||||
at: at,
|
||||
cleared: cleared,
|
||||
refused: refused,
|
||||
bytesBefore: bytesBefore,
|
||||
bytesAfter: bytesAfter,
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.warn(
|
||||
'Could not write the reclaim audit entry: $e',
|
||||
tag: 'Storage',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return StaleHistoryOutcome(
|
||||
cleared: cleared,
|
||||
refused: refused,
|
||||
bytesBefore: bytesBefore,
|
||||
bytesAfter: bytesAfter,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
import '../utils/app_logger.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// Per-channel region scope, persisted per device (Feature #812, Epic #815).
|
||||
///
|
||||
/// Stores the region name a channel's outgoing messages should ride, keyed by
|
||||
/// the first 10 hex chars of the connected device's public key (the same
|
||||
/// scoping the other channel stores use). The name is the `#`-stripped region
|
||||
/// name from discovery; null/absent means the channel is unscoped.
|
||||
class ChannelRegionScopeStore {
|
||||
static const String _keyPrefix = 'channel_region_scope_';
|
||||
|
||||
String publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||
|
||||
String _key(int channelIndex) => '$_keyPrefix${publicKeyHex}_$channelIndex';
|
||||
|
||||
/// The region name scoping [channelIndex], or null when unscoped.
|
||||
Future<String?> scopeFor(int channelIndex) async {
|
||||
if (publicKeyHex.isEmpty) return null;
|
||||
return PrefsManager.instance.getString(_key(channelIndex));
|
||||
}
|
||||
|
||||
/// Scope [channelIndex] to [regionName].
|
||||
Future<void> setScope(int channelIndex, String regionName) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('No device key set; cannot save channel region scope.');
|
||||
return;
|
||||
}
|
||||
await PrefsManager.instance.setString(_key(channelIndex), regionName);
|
||||
}
|
||||
|
||||
/// Remove the region scope on [channelIndex] (back to unscoped).
|
||||
Future<void> clearScope(int channelIndex) async {
|
||||
if (publicKeyHex.isEmpty) return;
|
||||
await PrefsManager.instance.remove(_key(channelIndex));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,365 @@
|
||||
/// The declared scoping verdict for every persistence surface (#853, #936).
|
||||
///
|
||||
/// Feature #853's acceptance bar is that "every store has a verified scoping
|
||||
/// verdict (per-radio or deliberately-global) and no hole remains". Until this
|
||||
/// file existed, the only way to check that was for a human to re-read an audit
|
||||
/// in an issue body, which is how #754 and #856 survived three earlier bleed
|
||||
/// fixes. This file is that audit, in code, with a test that fails when a new
|
||||
/// candidate key appears undeclared.
|
||||
///
|
||||
/// **Adding a storage key means adding a row here.** The test in
|
||||
/// `test/storage/scoping_inventory_test.dart` scans `lib/` for the shape every
|
||||
/// key in this repo uses, a `const String` whose value is lower snake_case, and
|
||||
/// fails if one is not classified below. A key that is not a storage key goes
|
||||
/// in [nonStorageConstants] with a reason, so "it isn't a key" is a written
|
||||
/// claim rather than a silence.
|
||||
library;
|
||||
|
||||
enum ScopingVerdict {
|
||||
/// Scoped by the first 10 hex of the connected radio's public key, the
|
||||
/// scheme every per-radio store in this repo uses. Radio A's data is never
|
||||
/// visible while radio B is connected.
|
||||
perRadio,
|
||||
|
||||
/// Global, and that is correct. The reason is mandatory: without it a later
|
||||
/// audit re-opens the surface as a hole, which is exactly the churn #853
|
||||
/// exists to end.
|
||||
globalOnPurpose,
|
||||
|
||||
/// Global, and that is a defect. Each of these has an open issue. The test
|
||||
/// asserts the set matches the known holes, so a NEW hole cannot hide among
|
||||
/// them and a FIXED one cannot be left mislabelled.
|
||||
knownHole,
|
||||
}
|
||||
|
||||
class StorageSurface {
|
||||
const StorageSurface(
|
||||
this.key, {
|
||||
required this.verdict,
|
||||
required this.reason,
|
||||
required this.owner,
|
||||
this.issue,
|
||||
});
|
||||
|
||||
/// The key or key prefix exactly as the source declares it.
|
||||
final String key;
|
||||
|
||||
final ScopingVerdict verdict;
|
||||
|
||||
/// Why this verdict. For [ScopingVerdict.perRadio], where the scoping comes
|
||||
/// from. For [ScopingVerdict.globalOnPurpose], why radio scoping would be
|
||||
/// wrong. For [ScopingVerdict.knownHole], what bleeds.
|
||||
final String reason;
|
||||
|
||||
/// The file that owns the key, so a reader can go check.
|
||||
final String owner;
|
||||
|
||||
/// Required for [ScopingVerdict.knownHole], so every hole is tracked.
|
||||
final int? issue;
|
||||
}
|
||||
|
||||
/// Every persistence surface in the client, with its verdict.
|
||||
const List<StorageSurface> storageSurfaces = [
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-radio. Each is fed the device-key prefix on connect.
|
||||
// ---------------------------------------------------------------------------
|
||||
StorageSurface(
|
||||
'channel_messages_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key, then PSK identity within the radio (#194), '
|
||||
'so history survives a channel rename and does not follow a reused '
|
||||
'slot. The cross-radio bleed was #472',
|
||||
owner: 'lib/storage/channel_message_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'messages_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key + contact key',
|
||||
owner: 'lib/storage/message_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'channels',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key',
|
||||
owner: 'lib/storage/channel_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'channel_order_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key; display order is per radio because the '
|
||||
'channel list is',
|
||||
owner: 'lib/storage/channel_order_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'channel_region_scope_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key',
|
||||
owner: 'lib/storage/channel_region_scope_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'contacts',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key; a contact list belongs to the radio that '
|
||||
'holds it',
|
||||
owner: 'lib/storage/contact_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'contact_groups',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key; groups reference that radio\'s contacts',
|
||||
owner: 'lib/storage/contact_group_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'contact_unread_count',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key; unread counts follow the message history',
|
||||
owner: 'lib/storage/unread_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'discovered_contacts',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key since #754. A discovered node is what THIS '
|
||||
'radio heard. An unset key loads nothing and never writes, so it '
|
||||
'cannot touch the orphaned legacy blob',
|
||||
owner: 'lib/storage/contact_discovery_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'communities_v1',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key',
|
||||
owner: 'lib/storage/community_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'channel_cyr2lat_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key + channel index, via keyForCyr2Lat. NOT '
|
||||
'previously audited: #853\'s audit listed channel_settings_store as '
|
||||
'one surface, but it owns two keys and this inventory found the '
|
||||
'second',
|
||||
owner: 'lib/storage/channel_settings_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'contact_cyr2lat_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key + contact key. NOT previously audited, same '
|
||||
'reason as channel_cyr2lat_',
|
||||
owner: 'lib/storage/contact_settings_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'contact_customname_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key + contact key, via keyForCustomName. The user\'s '
|
||||
'own label for a contact (#750). Per-radio for the same reason as its '
|
||||
'neighbour in this store. Deliberately NOT in contact_store: that '
|
||||
'record is rebuilt from radio contact-sync data, where no custom name '
|
||||
'exists, so a save after a sync would wipe the rename',
|
||||
owner: 'lib/storage/contact_settings_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'block_keys_v1',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key. A blank radio is no longer offloaded the '
|
||||
'client list (#471)',
|
||||
owner: 'lib/storage/block_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'block_names_v1',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason: 'prefix + device key, alongside block_keys_v1',
|
||||
owner: 'lib/storage/block_store.dart',
|
||||
),
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Known holes. Each has an issue and each is fixed in Epic B (#937).
|
||||
// ---------------------------------------------------------------------------
|
||||
StorageSurface(
|
||||
'path_history_',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key + contact key, in DRIFT, since #854 and #924. '
|
||||
'Was keyed by contact alone in prefs, so a route measured by a 1 W '
|
||||
'handheld was applied to a repeater. The move out of prefs went with '
|
||||
'the scoping because that one store held 2,092 keys and 86% of a '
|
||||
'4.28 MB file, and every prefs write re-encodes the whole file '
|
||||
'(#923). Unset key loads nothing and never writes',
|
||||
owner: 'lib/services/storage_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'delivery_observations',
|
||||
verdict: ScopingVerdict.perRadio,
|
||||
reason:
|
||||
'prefix + device key since #856. Was one global list, so a '
|
||||
'repeater\'s 45-second deliveries trained the ACK-timeout model a '
|
||||
'1 W handheld then used. Stays in prefs unlike path history: one '
|
||||
'small key, 3,091 bytes and 14 entries on the owner\'s install, so '
|
||||
'there is no cost argument for moving it',
|
||||
owner: 'lib/services/storage_service.dart',
|
||||
),
|
||||
// `pending_messages` (#855) was listed here and is GONE, not reclassified.
|
||||
// It had no callers anywhere in lib/ or test/ and the key was absent from
|
||||
// the owner's live prefs, so the fix was deletion rather than scoping. The
|
||||
// inventory's "declared but vanished from source" check is what keeps that
|
||||
// honest in the other direction: if the key ever comes back, the gate fails
|
||||
// until somebody declares it and says why.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Global on purpose. The reason is the point: it stops a later audit
|
||||
// re-opening these as holes.
|
||||
// ---------------------------------------------------------------------------
|
||||
StorageSurface(
|
||||
'client_install_id',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'the identity of this app INSTALL, not of any radio. Scoping it '
|
||||
'per radio would mint a new install id per radio, which is the '
|
||||
'opposite of what it is for',
|
||||
owner: 'lib/storage/client_id_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'app_settings',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'app-wide UX: theme, language, units, map and notification '
|
||||
'preferences. The per-radio data it does carry is scoped INSIDE it, by '
|
||||
'channelNotifyModesByRadio: device key -> channel PSK -> mode (#839). '
|
||||
'So the blob is global and the radio-specific part within it is not',
|
||||
owner: 'lib/models/app_settings.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'repeater_passwords',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'keyed by the repeater NODE, not by the radio connecting to it. '
|
||||
'The same repeater has the same password whichever radio reaches it, '
|
||||
'so per-radio scoping would make the user re-enter it per radio',
|
||||
owner: 'lib/services/storage_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'repeater_auto_clock_sync_after_login',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason: 'keyed by repeater node, same reasoning as repeater_passwords',
|
||||
owner: 'lib/services/storage_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'map_removed_marker_ids',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'a set of node ids the user dismissed from the map. "Do not show '
|
||||
'me this node" is a statement about the NODE, like repeater_passwords, '
|
||||
'not about the radio that happened to hear it. NOT previously audited: '
|
||||
'surfaced by this inventory, see #936',
|
||||
owner: 'lib/services/map_marker_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'map_tile_cache',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'cached OSM tiles. Geography does not depend on which radio is '
|
||||
'connected, and per-radio caching would multiply the download',
|
||||
owner: 'lib/services/map_tile_cache_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'radio_presets_v1_',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'prefix + preset FILE name. A cached catalogue of region presets '
|
||||
'fetched from assets or upstream, not state belonging to a radio. NOT '
|
||||
'previously audited: surfaced by this inventory',
|
||||
owner: 'lib/services/radio_preset_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'anr_last_exit_ts_ms',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'watermark for which ApplicationExitInfo records have been '
|
||||
'processed (#906). A property of the app process, not of a radio. NOT '
|
||||
'previously audited: surfaced by this inventory',
|
||||
owner: 'lib/services/app_exit_info_service.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'__msgrows_migrated',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'the set of store keys whose blob has been moved into message rows '
|
||||
'(#920). Global because the keys it lists are themselves already '
|
||||
'radio-scoped, so scoping the marker would scope it twice',
|
||||
owner: 'lib/storage/drift/blob_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'__msgrows_migrated_at',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'when each migrated store key migrated, for the stale-blob sweep '
|
||||
'(#962). Global for the same reason as __msgrows_migrated: it is keyed '
|
||||
'BY those store keys, which already carry the radio, so scoping it '
|
||||
'would scope it twice. Kept separate from that marker because the '
|
||||
'marker is read on every save and load through a cache, and reshaping '
|
||||
'it into a map would put a migration on the hottest storage path',
|
||||
owner: 'lib/storage/drift/blob_store.dart',
|
||||
),
|
||||
StorageSurface(
|
||||
'__msgrows_reclaim_audit',
|
||||
verdict: ScopingVerdict.globalOnPurpose,
|
||||
reason:
|
||||
'a durable record of what each stale-blob sweep deleted (#962). Global '
|
||||
'because one sweep spans every radio and the entries name store keys, '
|
||||
'which already carry the radio. It exists because the app log is gated '
|
||||
'on a setting that is off by default, so an irreversible delete would '
|
||||
'otherwise leave no trail at all; capped at the last few sweeps',
|
||||
owner: 'lib/storage/drift/blob_store.dart',
|
||||
),
|
||||
];
|
||||
|
||||
/// Constants that match the key shape but are not persistence keys.
|
||||
///
|
||||
/// This list exists so "that is not a storage key" has to be written down and
|
||||
/// justified, instead of a new key slipping through because nobody looked.
|
||||
const Map<String, String> nonStorageConstants = {
|
||||
'offband_store': 'the drift database FILE name, not a key within it',
|
||||
'__all__':
|
||||
'the sentinel value for "all groups" in the contacts filter '
|
||||
'(UiViewStateService). A filter VALUE, not a key, and not persisted '
|
||||
'under this name',
|
||||
'__reaction_send__':
|
||||
'a prefix for an in-memory send-queue id in the '
|
||||
'connector, distinguishing a reaction send from a message send. Never '
|
||||
'reaches storage',
|
||||
'psk_':
|
||||
'a marker inside a channel-history key, distinguishing a PSK '
|
||||
'identity from a legacy slot index (#194). Not a key by itself',
|
||||
'anr':
|
||||
'a log tag / exit-reason discriminator in the ANR capture path, not '
|
||||
'persisted under this name',
|
||||
'los_error_select_start_end':
|
||||
'an in-memory error sentinel in the line-of-sight screen, assigned to '
|
||||
'_error and compared against. Never written to storage',
|
||||
'los_error_invalid_input': 'the same, for invalid input',
|
||||
'los_error_elevation_unavailable':
|
||||
'the same, raised by the line-of-sight service when elevation data is '
|
||||
'missing. Never written to storage',
|
||||
// MQTT broker config field names. These are keys within a config map that is
|
||||
// itself persisted under another surface, not top-level storage keys.
|
||||
'auth_type': 'MQTT broker config field name',
|
||||
'ca_cert': 'MQTT broker config field name',
|
||||
'enabled': 'MQTT broker config field name',
|
||||
'password': 'MQTT broker config field name',
|
||||
'port': 'MQTT broker config field name',
|
||||
'topic_prefix': 'MQTT broker config field name',
|
||||
'transport': 'MQTT broker config field name',
|
||||
'url': 'MQTT broker config field name',
|
||||
'username': 'MQTT broker config field name',
|
||||
'jwt_aud': 'JWT claim name in a broker auth payload',
|
||||
'jwt_email': 'JWT claim name',
|
||||
'jwt_owner': 'JWT claim name',
|
||||
'jwt_refresh': 'JWT claim name',
|
||||
'jwt_token': 'JWT claim name',
|
||||
'iata_override': 'a field name within a config payload, not a storage key',
|
||||
};
|
||||
@ -0,0 +1,232 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/region_discovery_service.dart';
|
||||
|
||||
/// A repeater the user can discover regions from (name + 32-byte key).
|
||||
/// [hasPath] is whether a stored path to it exists; without one the companion
|
||||
/// can only flood the request and the repeater ignores it, so it cannot be
|
||||
/// selected.
|
||||
class RepeaterChoice {
|
||||
const RepeaterChoice({
|
||||
required this.name,
|
||||
required this.pubKey,
|
||||
this.hasPath = true,
|
||||
});
|
||||
final String name;
|
||||
final Uint8List pubKey;
|
||||
final bool hasPath;
|
||||
}
|
||||
|
||||
/// Pick the flood region a channel's outgoing messages ride (Feature #812,
|
||||
/// Epic #815). Discovers regions from a chosen repeater (via the injected
|
||||
/// [service]) and lets the user select one, or None to leave the channel
|
||||
/// unscoped. Persisting the choice is the caller's job, via [onSave].
|
||||
class ChannelRegionScopeDialog extends StatefulWidget {
|
||||
const ChannelRegionScopeDialog({
|
||||
super.key,
|
||||
required this.channelName,
|
||||
required this.currentScope,
|
||||
required this.repeaters,
|
||||
required this.service,
|
||||
required this.onSave,
|
||||
});
|
||||
|
||||
final String channelName;
|
||||
final String? currentScope;
|
||||
final List<RepeaterChoice> repeaters;
|
||||
final RegionDiscoveryService service;
|
||||
final Future<void> Function(String? region) onSave;
|
||||
|
||||
@override
|
||||
State<ChannelRegionScopeDialog> createState() =>
|
||||
_ChannelRegionScopeDialogState();
|
||||
}
|
||||
|
||||
class _ChannelRegionScopeDialogState extends State<ChannelRegionScopeDialog> {
|
||||
// Alpha-sorted once (case-insensitive), so the picker is predictable even
|
||||
// with many repeater contacts (D1 finding: an unsorted list was unusable).
|
||||
late final List<RepeaterChoice> _sortedRepeaters = [...widget.repeaters]
|
||||
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
||||
|
||||
late RepeaterChoice? _repeater = _firstWithPath();
|
||||
String _repeaterFilter = '';
|
||||
late String? _selected = widget.currentScope;
|
||||
|
||||
RepeaterChoice? _firstWithPath() {
|
||||
for (final r in _sortedRepeaters) {
|
||||
if (r.hasPath) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _discover() {
|
||||
final repeater = _repeater;
|
||||
if (repeater != null && repeater.hasPath) {
|
||||
widget.service.discover(repeater.pubKey);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
return AlertDialog(
|
||||
title: Text(l10n.setRegionScope_title(widget.channelName)),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
child: ListenableBuilder(
|
||||
listenable: widget.service,
|
||||
builder: (context, _) => _content(l10n),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(MaterialLocalizations.of(context).cancelButtonLabel),
|
||||
),
|
||||
ElevatedButton(
|
||||
key: const Key('regionScopeSave'),
|
||||
onPressed: () async {
|
||||
await widget.onSave(_selected);
|
||||
if (context.mounted) Navigator.of(context).pop();
|
||||
},
|
||||
child: Text(l10n.setRegionScope_save),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _content(AppLocalizations l10n) {
|
||||
final repeaterName = _repeater?.name ?? '';
|
||||
final children = <Widget>[];
|
||||
|
||||
if (_sortedRepeaters.isNotEmpty) {
|
||||
final filter = _repeaterFilter.toLowerCase();
|
||||
final searching = filter.isNotEmpty;
|
||||
// Default view shows only repeaters with a stored path (the only ones
|
||||
// that can answer). A search surfaces pathless matches too, but greyed
|
||||
// out and non-selectable, so the user sees it exists and why it is
|
||||
// blocked (D1 Option 1).
|
||||
final filtered = _sortedRepeaters.where((r) {
|
||||
if (!r.name.toLowerCase().contains(filter)) return false;
|
||||
return searching || r.hasPath;
|
||||
}).toList();
|
||||
children.add(
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
l10n.setRegionScope_pathNote,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
);
|
||||
children.add(
|
||||
TextField(
|
||||
key: const Key('regionScopeRepeaterSearch'),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
hintText: l10n.setRegionScope_searchRepeaters,
|
||||
),
|
||||
onChanged: (v) => setState(() => _repeaterFilter = v),
|
||||
),
|
||||
);
|
||||
children.add(
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 180),
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (final r in filtered)
|
||||
ListTile(
|
||||
dense: true,
|
||||
enabled: r.hasPath,
|
||||
leading: const Icon(Icons.cell_tower),
|
||||
title: Text(r.name),
|
||||
subtitle: r.hasPath ? null : Text(l10n.setRegionScope_noPath),
|
||||
trailing: identical(r, _repeater)
|
||||
? const Icon(Icons.check)
|
||||
: null,
|
||||
selected: identical(r, _repeater),
|
||||
onTap: r.hasPath ? () => setState(() => _repeater = r) : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
children.add(
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: TextButton.icon(
|
||||
key: const Key('regionScopeDiscover'),
|
||||
icon: const Icon(Icons.travel_explore),
|
||||
label: Text(l10n.setRegionScope_discover),
|
||||
onPressed:
|
||||
(widget.service.isLoading ||
|
||||
_repeater == null ||
|
||||
!_repeater!.hasPath)
|
||||
? null
|
||||
: _discover,
|
||||
),
|
||||
),
|
||||
);
|
||||
children.add(const Divider(height: 1));
|
||||
}
|
||||
|
||||
switch (widget.service.status) {
|
||||
case RegionDiscoveryStatus.loading:
|
||||
children.add(
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(12),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
);
|
||||
case RegionDiscoveryStatus.timeout:
|
||||
children.add(Text(l10n.discoverRegions_timeout(repeaterName)));
|
||||
case RegionDiscoveryStatus.error:
|
||||
children.add(
|
||||
Text(widget.service.errorMessage ?? l10n.discoverRegions_error),
|
||||
);
|
||||
case RegionDiscoveryStatus.empty:
|
||||
children.add(Text(l10n.discoverRegions_empty(repeaterName)));
|
||||
case RegionDiscoveryStatus.idle:
|
||||
case RegionDiscoveryStatus.success:
|
||||
break;
|
||||
}
|
||||
|
||||
children.add(
|
||||
ListTile(
|
||||
key: const Key('regionScopeNone'),
|
||||
title: Text(l10n.setRegionScope_none),
|
||||
trailing: _selected == null ? const Icon(Icons.check) : null,
|
||||
selected: _selected == null,
|
||||
onTap: () => setState(() => _selected = null),
|
||||
),
|
||||
);
|
||||
|
||||
// Current scope first (so it stays visible even before a re-discovery),
|
||||
// then the discovered regions, alpha-sorted, deduped by name.
|
||||
final names = <String>{};
|
||||
if (widget.currentScope != null) names.add(widget.currentScope!);
|
||||
final discovered = widget.service.regions.map((r) => r.name).toList()
|
||||
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
|
||||
names.addAll(discovered);
|
||||
for (final name in names) {
|
||||
children.add(
|
||||
ListTile(
|
||||
title: Text(name),
|
||||
trailing: _selected == name ? const Icon(Icons.check) : null,
|
||||
selected: _selected == name,
|
||||
onTap: () => setState(() => _selected = name),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: children),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue