diff --git a/.build_version b/.build_version index 88c5fb89..9df886c4 100644 --- a/.build_version +++ b/.build_version @@ -1 +1 @@ -1.4.0 +1.4.2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6711d2a..2d5608d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,7 @@ jobs: - uses: subosito/flutter-action@v2 with: channel: 'stable' + flutter-version: '3.47.5' - run: flutter pub get - run: dart run build_runner build --delete-conflicting-outputs diff --git a/.gitignore b/.gitignore index 22607258..c662f637 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,10 @@ android/key.properties *.jks *.keystore +# App Store Connect API keys and Google Play service accounts (never commit) +*.p8 +service-account*.json + # iOS generated files /ios/Flutter/Flutter.framework /ios/Flutter/Flutter.podspec @@ -73,6 +77,8 @@ ios/Flutter/flutter_export_environment.sh # Debug logs debug/ +!lib/debug/ +!test/debug/ debuglog/ meshmapper-debug-*.txt diff --git a/Build.sh b/Build.sh index a0d2dabb..907e8aeb 100755 --- a/Build.sh +++ b/Build.sh @@ -5,6 +5,11 @@ set -e # Exit on any error +# The Flutter SDK every release is built with. Bump this when Flutter is +# upgraded, together with flutter-version in .github/workflows/ci.yml, so the +# store builds and CI never drift onto different SDKs. +REQUIRED_FLUTTER_VERSION="3.47.5" + # CLI flags for scripted use: ./Build.sh [--type dev|prod] [--version X.Y.Z] [--dry-run] # With no flags the script behaves exactly as before (interactive prompts). CLI_TYPE="" @@ -224,6 +229,22 @@ fi ANDROID_DIR="$HOME/Documents/MeshMapper_Apps/Andriod" IOS_DIR="$HOME/Documents/MeshMapper_Apps/IOS" +# The Flutter SDK on PATH builds everything, and regenerates code with it too +FLUTTER_BIN="$(command -v flutter || true)" +if [ -z "$FLUTTER_BIN" ]; then + echo "Error: flutter not found on PATH" + exit 1 +fi +FLUTTER_VERSION_LINE="$(flutter --version 2>/dev/null | head -1)" +FLUTTER_FRAMEWORK_VERSION="$(flutter --version --machine 2>/dev/null | sed -n 's/.*"frameworkVersion": *"\([^"]*\)".*/\1/p' | head -1)" +if [ "$FLUTTER_FRAMEWORK_VERSION" != "$REQUIRED_FLUTTER_VERSION" ]; then + echo "Error: Flutter $REQUIRED_FLUTTER_VERSION is required, but the flutter on PATH" + echo "($FLUTTER_BIN) is ${FLUTTER_FRAMEWORK_VERSION:-unknown}." + echo "Install or switch to $REQUIRED_FLUTTER_VERSION, or bump REQUIRED_FLUTTER_VERSION" + echo "at the top of Build.sh (and ci.yml) if you are upgrading on purpose." + exit 1 +fi + # Dry run: everything is resolved and validated - print the plan and stop if [ "$DRY_RUN" = "1" ]; then echo "" @@ -234,6 +255,11 @@ if [ "$DRY_RUN" = "1" ]; then echo "Build name: $VERSION_NUMBER" echo "Build number: $EPOCH" echo "Secrets: present (API key + signing passwords)" + echo "Flutter SDK: $FLUTTER_VERSION_LINE ($FLUTTER_BIN)" + echo "" + echo "Would run first:" + echo " flutter pub run build_runner build --delete-conflicting-outputs" + echo " (fails the build if it fails or rewrites pubspec.lock)" echo "" echo "Would produce:" echo " APK: $ANDROID_DIR/MeshMapper-$FILE_TAG.apk" @@ -250,9 +276,28 @@ echo "============================================" echo "MeshMapper Build Script" echo "Version: $APP_VERSION" echo "Build number: $EPOCH" +echo "Flutter SDK: $FLUTTER_VERSION_LINE ($FLUTTER_BIN)" echo "============================================" echo "" +# Regenerate generated code (Hive adapters). *.g.dart is gitignored, so a +# stale local copy would otherwise ship and silently drop newer Hive fields. +echo "[0/3] Regenerating generated code (build_runner)..." +LOCK_BEFORE="$(shasum pubspec.lock 2>/dev/null || true)" +if ! flutter pub run build_runner build --delete-conflicting-outputs; then + echo "Error: build_runner failed, not building" + exit 1 +fi +LOCK_AFTER="$(shasum pubspec.lock 2>/dev/null || true)" +if [ "$LOCK_BEFORE" != "$LOCK_AFTER" ]; then + echo "Error: build_runner rewrote pubspec.lock. The Flutter SDK on PATH" + echo "($FLUTTER_VERSION_LINE) is likely not the one the lock was resolved" + echo "with. Restore pubspec.lock and put the right SDK first on PATH." + exit 1 +fi +echo "✓ Generated code is up to date" +echo "" + # Ensure output directories exist mkdir -p "$ANDROID_DIR" mkdir -p "$IOS_DIR" diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 358bd105..e0c6d0db 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -8,7 +8,7 @@ MeshMapper Flutter App is a cross-platform wardriving application for MeshCore m **Purpose**: Connect to MeshCore devices via Bluetooth Low Energy, send GPS-tagged pings to the `#wardriving` channel, track repeater echoes, and post coverage data to the MeshMapper API for community mesh mapping. -**Tech Stack**: Flutter 3.2.0+, Dart 3.2.0+, Hive for local storage, Provider for state management +**Tech Stack**: Flutter 3.47.5 (Dart 3.13.4), Hive for local storage, Provider for state management ## Common Commands @@ -62,6 +62,10 @@ delivery races still need a wrist. ### Building for Release ```bash +# Build.sh regenerates the Hive adapters (build_runner) with the Flutter SDK on PATH +# before building, and stops if that fails or rewrites pubspec.lock. +# It also refuses to build unless the flutter on PATH is REQUIRED_FLUTTER_VERSION +# (top of Build.sh). Bump it together with flutter-version in ci.yml. # Use Build.sh — prompts for API key and signing passwords ./Build.sh @@ -90,10 +94,26 @@ updated by adding the developer-portal capability. ### Debug Logging - Web: Add `?debug=1` to URL to enable debug logging in browser console -- Mobile: Debug logging enabled in debug builds via `kDebugMode`; disabled in release builds +- Mobile: Debug logging is enabled in every build, release included (`DebugLogger.initialize` in `lib/utils/debug_logger_stub.dart`), and is also written to rotating files (see Bug Report / Debug File System) ## Architecture +### Renderer Compatibility and Production Diagnostics + +The 1.4.1 beta uses Flutter 3.47.5, including its Vulkan image-allocation +recovery for exhausted compression resources. Impeller and automatic backend +selection remain enabled. The app retains the 1.4.0 rendering behavior, without +the diagnostic probes, native log capture, forced OpenGLES or marker retries. + +Debug log headers include the Flutter version and engine revision supplied by +the build tool, and Android's OS build ID and security patch. No device serial +or fingerprint is collected. Marker registration failures name the image and +whether rendering or registration failed, with coverage registration reported +as a group. These are lightweight diagnostics, not additional rendering work. + +Use Flutter 3.47.5 for release builds, matching the version pinned in CI. A +successful build and tests do not replace confirmation on the affected Pixel. + ### First-Run Quick Guide The iOS and Android apps show a versioned Quick Guide after the required @@ -154,6 +174,22 @@ pixels) for every ID length and state, on both map modes and in the detail popup header. Cluster badges remain circular. The matching server change is implemented in the server repository. +### GPS Marker Color + +Settings > Map > Markers > GPS Marker Color (`UserPreferences.gpsMarkerColor`, +JSON key `gpsMarkerColor`: `default` or `green`; anything else reads as +`default`). It applies to every GPS marker style. `default` keeps each style's +own colour (blue, cyan for Chomper). The colours live in `GpsMarkerColors` +(`lib/utils/gps_marker_colors.dart`) and the painters in `map_widget.dart` take +them as a parameter. `_registerMapImages` bakes every style in every colour +(`gps_car`, `gps_car_green`, ...) in its one existing pass, so a colour change +only swaps the puck's `iconImage`, through the same version-gated GPS sync a +style change uses. The marker colour does not follow Color Vision, the same as +the blue never did: it is the user's own pick and carries no meaning, and every +style's white outline is what separates it from the coverage under any palette. +The green is a dark one, so it also stands apart from the pale green +bidirectional squares of the default palette. + ### Repeater Identity and Collision Handling Repeater identity is the cleaned full public key. The server's short `id` @@ -169,11 +205,95 @@ conflict warning, since a wider-addressable device may still share two bytes. These use the existing duplicate marker style. No collision pass runs on a position tick or map rebuild. Load completion uses `_notifyMapNow()`. +A heard hop id carries the width its sender chose, so a 3-byte region can +still hear repeater `A81EA4` as `A8`. Top Heard (and through it the watch, +Live Activity and CarPlay rows) shows and groups such an id as the one +repeater it can mean: `ShortHopIds` (`lib/utils/short_hop_ids.dart`) follows +the server's `rc_resolve_token` rule (key = hex id, else legacy id; matches +whose keys form one prefix chain are one device; anything else stays the +short id) and widens a match to the wider of its advertised width and the +device/region hop width. The provider builds it once per repeater list +(prefix map for 1-3 byte ids). It is display only: logs, RX pins and uploads +keep the raw hop id, and the server resolves it again itself. + Labels and detail/Manage sheets use each repeater's `advert_bytes`, falling back to `hop_bytes`, independently of regional TX path-width enforcement. Coverage requests use up to 40 characters of the full key to meet the API's prefix limit. Legacy narrow coverage tokens can remain inherently ambiguous. +### Repeater Nicknames + +A user can give a repeater a short personal nickname ("Mell" for the repeater +whose key starts 5007) that is shown where a heard repeater is named. It stays +on the phone: no account sync and no server involvement. Nicknames are kept in +the Hive `user_preferences` box under `repeater_nicknames`, a map of full +64-hex public key to `{nickname, name, hex}`, and read back through +`RepeaterNicknames.sanitize` (`lib/utils/repeater_nicknames.dart`), which drops +a bad entry instead of throwing. `name` and `hex` are snapshots of the server +name and display hex taken at save time, so the Settings list can describe a +repeater outside the current zone's catalogue; they are display-only and never +used to match. A nickname is capped at 8 characters +(`RepeaterNicknames.maxLength`), and only a repeater with a full public key can +take one. + +Nicknames are global to the phone and never scoped to a zone or IATA, so they +survive leaving a region and coming back. Nothing clears them on a zone change, +catalogue reload, disconnect, log clear or session end, and resolving against +whatever catalogue is loaded brings one back when its repeater is in view +again. The only thing that drops them is the existing corrupt-box recovery +(`_openBoxSafely`) that deletes the whole `user_preferences` box, like every +other preference. + +Matching is by full key. A heard ID shows a nickname only when it resolves to +exactly one catalogue repeater, trying the fullest identity the row arrived +with first and the display hash second; an ambiguous ID keeps its hex, because +a confidently wrong name is worse than none. Top Heard +(`AppStateProvider.topHeardLabel`, via `RepeaterNicknames.labelFor`), the Live +Activity and Siri all resolve through `ExternalSurfaceGeoBuilder.resolveOverlayRow`; +the watch's heard rows use `resolveOverlayRepeaters`, which applies the same +identity-first, unique-only rule to the whole set of rows at once. + +The nickname replaces the hex on the Top Heard overlay. On the Live Activity and +CarPlay heard rows (`_resolveRepeaterDisplayName`) it wins over the server name +in the existing name slot beside the hex, still behind "Repeater Names on Live +Activity". It also appears on the Apple Watch heard rows +(`buildHeard(nicknames:)`) and in Siri's heard observations +(`buildRecentHeard(nicknames:)`). `_resolveRepeaterDisplayName` also feeds +`_targetRepeaterDisplayName`, so in Trace mode the nickname names the target in +the session phase text on the Live Activity and watch ("Tracing ", +"Waiting for to reply", "To "). That text was never behind the +"Repeater Names on Live Activity" toggle; only the heard rows are. It is not +used in log chips, ping popups, map markers or the Siri/Shortcuts repeater +catalogue, which keep server names. A change goes through +`setRepeaterNickname` or `setRepeaterNicknameByKey`, which bump +`_siriRepeaterCatalogRevision`, call `_notifyMapNow()` (the overlay rebuilds on +`mapRevision`) and schedule the Live Activity, watch and Siri sync. + +The "Repeater Names in Top Heard" setting (`UserPreferences.topHeardShowNames`, +Settings > Map, off by default and phone-local like the nicknames) lets a Top +Heard row with no nickname show the repeater's server name in place of the hex. +`RepeaterNicknames.labelFor(useServerName:)` cuts the name to +`RepeaterNicknames.maxLength` (8) grapheme clusters plus "…". A name of +'Unknown' or a hidden 🚫 name keeps the hex. It uses the same unique-match rule +as a nickname, and a nickname always wins. It affects only the in-app Top Heard +box; the Live Activity and watch have their own name rules above. + +On the map, the minimized repeater pill shows the nickname as a small tag after +the name. The expanded repeater sheet has a Nickname button beside Manage, the +same height and shape, reading "Nickname" until one is set and then the +nickname itself, for repeaters with a full public key only (without one, Manage +keeps the full width). The tag, the button and the hex badge are the shared +`RepeaterNicknameTag`, `RepeaterNicknameButton` and `RepeaterHexBadge` in +`lib/widgets/repeater_nickname_widgets.dart`. The +other entry point is Settings > Map > Repeater Nicknames +(`RepeaterNicknameList` in `lib/screens/settings/repeater_nicknames_page.dart`): +list, add through the repeater picker (which offers only repeaters with a full +key), edit and remove. A removal offers Undo, and removals made while that bar +is up share it (`NicknameRemovalBatch`), so one Undo brings them all back. The +sheet and the list's add share one ask-then-save flow, `editRepeaterNickname` +in `lib/widgets/repeater_nickname_dialog.dart`, and nicknames made only of +invisible characters are treated as blank. + ### Service-Oriented Architecture The app uses a layered service architecture with clear separation of concerns: @@ -189,7 +309,7 @@ The app uses a layered service architecture with clear separation of concerns: - `StreamFrameCodec`: Framing codec for TCP/USB Serial (`[0x3C][len_lo][len_hi][payload]` out, `[0x3E][len_lo][len_hi][payload]` in) - `StreamTransportBase`: Abstract base for TCP and USB Serial transports, owns codec and connection lifecycle - `TcpService`: TCP socket transport with saved connections persistence (Android/iOS) -- `AndroidSerialService`: USB Serial via USB OTG on Android using `usb_serial` package +- `AndroidSerialService`: USB Serial via USB OTG on Android, through the app's own `net.meshmapper.app/usb_serial` method and event channels (native side `MeshMapperUsbService.kt`) - `WebSerialService`: USB Serial via Web Serial API (Chrome/Edge) using `dart:js_interop` - Platform matrix: BLE (all platforms), TCP (Android/iOS), USB Serial (Android/Web) @@ -197,14 +317,14 @@ The app uses a layered service architecture with clear separation of concerns: - `MeshCoreConnection`: Implements the 9-step connection workflow and MeshCore companion protocol - `PacketParser`: Binary packet parsing with BufferReader/Writer utilities - `UnifiedRxHandler`: Routes ALL incoming BLE packets to TX tracking or RX logging -- `TxTracker`: Detects repeater echoes during 7-second window after TX ping +- `TxTracker`: Detects repeater echoes during 5-second window after TX ping - `DiscTracker`: Detects discovery responses during 7-second window after discovery request - `RxLogger`: Logs passive mesh observations, buffers by repeater ID - `ChannelService`: Channel hash computation and management - `CryptoService`: SHA-256 channel key derivation, AES-ECB message decryption **Application Services** (`lib/services/`): -- `GpsService`: GPS tracking with server-side zone validation +- `GpsService`: GPS tracking with server-side zone validation; resolves each fix's altitude reference through `FixAltitudeResolver` - `PingService`: TX/RX/Discovery ping orchestration, coordinates with TxTracker/DiscTracker/RxLogger - `ApiQueueService`: Hive-based persistent upload queue with batch POST and retry logic - `ApiService`: HTTP client for MeshMapper API endpoints @@ -300,17 +420,50 @@ iOS and web skip the resync. The history view answers re-syncs (the marker data version reads it) and the cleanup loop takes the now-unwanted pins off the map. +### Remembered Map View + +The map comes back the way the user left it (#470). `MapViewState` +(`lib/models/map_view_state.dart`) holds the last camera zoom and the panel fold +state: the control panel minimised (both orientations), the landscape control +panel closed, the landscape map control column open, and the portrait map control +column open. It is its own key, `map_view_state`, in the `user_preferences` Hive +box, NOT a `UserPreferences` field: it changes during a pinch, so a write must not +run the settings save path or notify anything keyed on the preferences. A missing +or malformed entry reads as today's defaults (no zoom, panel expanded, portrait +column open), so a first launch is unchanged. `AppStateProvider` reads it in +`_loadPreferences` (which now ends with `_notifyMapNow()` so the cached map +applies its saved toggles on the next build) and owns it; `HomeScreen`'s +`_isControlsMinimized` / `_showControlPanel` / `_mapControlsExpanded` are getters +and setters over it. Store capture mode keeps its fold state local and never +writes. Writes go through a 1.5 s `Debouncer` (`lib/utils/debouncer.dart`), +flushed when the app is paused. + +Zoom: `_onCameraIdle` calls `_rememberCameraZoom`, which skips a focus camera +(`_cameraFocusActive`: tapped ping, cell or repeater) and the history session fit, +and the provider drops a zoom within 0.01 of the stored one (auto-follow ends +every GPS tick in a camera idle at the same zoom). `MapViewState.clampZoom` clamps +to the map's 3..17 range and nudges an integer zoom off the integer. The restored +zoom replaces the first-launch zooms only: `initialCameraPosition` (15), the +one-time zoom to the last known position (15) and the one-time zoom to the first +GPS fix (16). With auto-follow on, that GPS zoom also seeds +`_autoFollowDesiredZoom`, so a follow tick landing mid-animation aims at it, and +the next camera idle hands zoom back to the camera as before. Until a startup +zoom has run, a camera idle at the creation zoom is not recorded (the map may +have been created before preferences loaded and would overwrite the zoom about +to be restored); a user zoom off the creation zoom is. Tap-to-follow still jumps +to max zoom, and that zoom is then remembered like any other. + ### 9-Step Connection Workflow Critical safety: The connection sequence MUST complete in order. -1. **Transport Connect**: Platform-specific transport connection (BLE GATT, TCP socket, or USB Serial port) +1. **Transport Connect**: Platform-specific transport connection (BLE GATT, TCP socket, or USB Serial port). On mobile BLE this is the one step the user can cancel (`AppStateProvider.cancelConnect`, the Cancel button on the progress screen): it bumps `_connectGeneration` so the in-flight attempt fails silently, and `MobileBluetoothService.cancelConnect` stops the retry loop and drops the pending GATT connect with `disconnect(queue: false)`, which also stops iOS completing it later. Past this step the handshake is not cancellable. Starting a scan also resets a failed connect's `error` step to `disconnected`, or the bottom Scan button stays disabled. 2. **Protocol Handshake**: `deviceQuery()` with protocol version 3. **Device Info**: `deviceQuery()` returns manufacturer string, then `getSelfInfo()` acquires device public key (required for geo-auth API authentication). If `getSelfInfo()` fails, the entire connection fails. 4. **Device Identification**: Resolve the queried manufacturer against the current server-managed catalog. With nothing cached, this connect may arm one more refresh and waits at most 3 s for it. Recognition is advisory and never modifies radio settings. 5. **Time Sync**: `sendTime()` syncs device clock 6. **Session Acquisition**: POST to `/wardrive-api.php/auth` for geo-auth session. Two-stage flow: first attempt with device public key, fallback to registration with signed contact URI if device not registered. Returns `session_id`, `tx_allowed`, `rx_allowed`, `expires_at`, and regional channels. -7. **Channel Setup**: Create or use existing `#wardriving` channel, plus any regional channels from auth response +7. **Channel Setup**: Create or use existing `#wardriving` channel, plus any regional channels from auth response. The slot scan uses the channel capacity from device-info byte 3, reading only indices below that count. MeshCore returns ERR 2 beyond its table and ZephCore returns ERR 6; neither boundary needs probing when capacity is known. A missing or zero capacity keeps the legacy ERR 2 end-of-list fallback. Any failure inside the advertised range, including ERR 2, is retried once and then fails setup rather than creating after an incomplete scan. Empty slots do not stop the search for an existing channel. A slot holding the `#wardriving` key under another name is reused without renaming or deleting it on disconnect. 8. **GPS Init**: Acquire GPS lock 9. **Connected State**: Ready for wardriving — Unified RX Handler starts processing ALL incoming packets, noise floor polling begins (5s interval) @@ -333,12 +486,12 @@ Parse PacketMetadata (ONCE) TX Track RX Log (echoes) (passive) ↓ ↓ -7s window Buffer by repeater +5s window Buffer by repeater ↓ ↓ Update UI Flush to API queue ``` -**TX Tracking** (during 7-second window after ping): +**TX Tracking** (during 5-second window after ping): - Validates: GROUP_TEXT header, RSSI < -30dBm, channel hash match, decrypted message match, path length > 0 - Deduplicates by first hop (repeater ID), keeps best SNR - Updates UI with repeater counts @@ -357,7 +510,7 @@ Discovery pings use the MeshCore control data protocol to directly query nearby **Response**: ControlData packets (0x8E) with `DISCOVER_RESP` flag (0x90), containing node type, remote SNR, and full 32-byte public key. -**Tracking**: `DiscTracker` manages a 7-second listening window (like `TxTracker`), validates responses, deduplicates by public key, and applies carpeater filtering (RSSI too strong = too close). +**Tracking**: `DiscTracker` manages a 7-second listening window (`TxTracker`'s is 5 seconds), validates responses, deduplicates by public key, and applies carpeater filtering (RSSI too strong = too close). **API Payload**: Type `"DISC"` with fields: `lat`, `lon`, `repeater_id`, `node_type`, `local_snr`, `local_rssi`, `remote_snr`, `public_key`, `timestamp`, `external_antenna`, `noisefloor`. @@ -365,7 +518,7 @@ Discovery pings use the MeshCore control data protocol to directly query nearby Four auto-ping modes are available after connecting: -- **Active Mode**: Sends TX pings at user-configured interval (15s, 30s, or 60s). Each ping broadcasts a group channel message containing GPS location and radio power to `#wardriving`, then listens 7s for repeater echoes via `TxTracker`. +- **Active Mode**: Sends TX pings at user-configured interval (15s, 30s, or 60s). Each ping broadcasts a group channel message containing GPS location and radio power to `#wardriving`, then listens 5s for repeater echoes via `TxTracker`. - **Passive Mode**: Sends discovery requests every 30s. No TX pings, only discovery request-response. Responses tracked via `DiscTracker`. - **Hybrid Mode**: Alternates between discovery and TX pings at the user-configured interval. Discovery, TX, Discovery, TX... - **Trace Mode**: Sends zero-hop trace path (CMD_SEND_TRACE_PATH, 0x24) to a specific repeater by ID at user-configured interval. Listens 7s for trace response (PUSH_CODE_TRACE_DATA, 0x89) via `TraceTracker`. Only successful traces are posted to API; failures are logged locally and shown as red markers on noise floor graph. @@ -404,18 +557,42 @@ landed in the queue. The discovery countdown is the one timer the user stop path and the hot switch stops, because a discovery window still open belongs to the session being torn down. +Scope discovery (see below) rides Passive and Hybrid's own discovery results and never changes +either mode's own schedule: no ping is ever skipped or rescheduled because of it, and the timer +that decides when the next TX or discovery is due keeps running untouched. What CAN happen is a +delay at the write itself: a TX, discovery, trace send, or a banked-ping release that is written +while the short radio lease (see below) is held waits at the lease's own write gate until it +releases, normally a few hundred milliseconds and at most about 4 seconds. It has nothing to do +with Active or Trace mode in practice, since only Passive and Hybrid ever hold that lease. + ### GPS & Zone Validation - Uses `geolocator` package with high accuracy and continuous tracking +- **Stream cadence**: a 10 m distance filter on every platform, and on Android a 1 s interval for both location providers (`gpsStreamSettings` in `lib/services/gps_service.dart`). Left unset, the Android plugin asks every 5 s, and pings while driving reused the previous fix. - **Zone Validation**: Server-side — client sends GPS coordinates to the API, server returns zone status (in-zone, nearest zone, or error) - **Min Distance Filter**: 25m between pings prevents spam -- **Airborne block** (`GpsService.positionLooksAirborne`): a fix counts as in the air when its altitude, less its own vertical accuracy, is above 6,000 m (higher than any road on Earth, below airliner cruise) OR its ground speed is above 250 km/h (catches take-off, approach and most small aircraft; a high-speed train trips it too, by design). Three consecutive airborne fixes set `GpsService.isAirborne`, three consecutive ground fixes clear it, and one fix of the other kind restarts the count. The latch records which test fired (`airborneGate`) and BOTH readings of the fix that set it (`airborneAltitude`, `airborneSpeed`, each null when unknown; `speedOrNull` mirrors `altitudeOrNull`), and reports every flip once through `onAirborneChanged`. Unknown altitude and speed arrive from geolocator as 0.0 and never qualify (fail open). Every accepted fix feeds the latch (`trackAirborne`): the position stream, the simulator and `getFreshPosition()`, which TX, discovery and trace sends all take. A fix handed over twice (stream plus fresh read, same platform timestamp) counts once, so the streak really is three distinct fixes. The latch resets whenever the fix source restarts (`startWatching`, `enableSimulator`), because the stream only fires on movement and a phone left on a desk after a simulated flight would otherwise stay locked out. `GpsService.altitudeOrNull` is the shared "does this fix know its altitude" test (only the 0.0/0.0 pair means unknown; Android omits the accuracy on fixes that do carry an altitude). +- **Airborne block** (`GpsService.positionLooksAirborne`): a fix counts as in the air when its altitude, less its own vertical accuracy, is above 6,000 m (higher than any road on Earth, below airliner cruise) OR its ground speed is above 250 km/h (catches take-off, approach and most small aircraft; a high-speed train trips it too, by design). The altitude test only counts when the same fix's speed is unknown (`speedOrNull`) or at least 150 km/h (`airborneAltitudeMinSpeedMetersPerSecond`): nothing above 6,000 m flies slower, so a known slow speed marks the altitude as the bad reading (an iOS fix once read 18,490 m in a car at 8 km/h). One helper decides it for both the test and the recorded `airborneGate`; a fast car with a bogus altitude would still latch. Three consecutive airborne fixes set `GpsService.isAirborne`, three consecutive ground fixes clear it, and one fix of the other kind restarts the count. The latch records which test fired (`airborneGate`) and BOTH readings of the fix that set it (`airborneAltitude`, `airborneSpeed`, each null when unknown; `speedOrNull` mirrors `altitudeOrNull`), and reports every flip once through `onAirborneChanged`. Unknown altitude and speed arrive from geolocator as 0.0 and never qualify (fail open). Every accepted fix feeds the latch (`trackAirborne`): the position stream, the simulator and `getFreshPosition()`, which TX, discovery and trace sends all take. A fix handed over twice (stream plus fresh read, same platform timestamp) counts once, so the streak really is three distinct fixes. The latch resets whenever the fix source restarts (`startWatching`, `enableSimulator`), because the stream only fires on movement and a phone left on a desk after a simulated flight would otherwise stay locked out. `GpsService.altitudeOrNull` is the shared "does this fix know its altitude" test (only the 0.0/0.0 pair means unknown; Android omits the accuracy on fixes that do carry an altitude). - **What the block does**: `AppStateProvider._checkAirborne()` is level-triggered from the position listener and from the auto-ping scheduling hook (on iOS the position stream is quiet in the background, so the fresh fix each ping takes is the only sample then). With a live session it calls `_endSessionForAirborne()`: disconnect alert, error-log entry with the altitude or speed in the user's units, then `disconnect(closeApp: false, releaseExtras: ...)`, the normal user-disconnect path (auto-ping off, RX logging off, queue cleared, offline session kept in Offline Mode, API session released, no auto-reconnect). It defers while a zone transfer is in progress, since that flow re-acquires a session after its awaits with no cancellation check. The listener returns early on that tick so it cannot run a zone check on the way out, and the 100 m zone recheck while disconnected is skipped while airborne (a flight would otherwise POST once a second for hours). The four connect entry points refuse via `_refuseConnectIfAirborne()` (which sets no `connectionError`: the Connection screen's Airborne panel outranks the error card, and a message set there would survive the landing until the next attempt), the Connection screen disables Connect and shows "Airborne" with the reading that set the latch (`airborneCause`, "Your altitude is 10000m." or "You are moving at 300 km/h."), the map's GPS chip shows the fix's altitude when known, `PingValidation.airborne` blocks all three validators, the discovery and trace send lanes read the latch again after their own fresh fix and bow out without transmitting (a TX is already covered by `canPing()`, which re-reads it after the same suspension; on iOS in the background that fresh fix is the sample that sets the latch, so without the re-read each of those lanes put one more packet on the air after the block engaged, and neither reschedules, since the provider's handler is ending the session), Siri and the watch get `ExternalCommandReasonCode.airborne`, and auto-reconnect abandons instead of retrying into a flight (same alert, error-log entry and release telemetry, preserved queue dropped; the check sits below the reconnect prep so the foreground service and RX-side objects are torn down first). The check skips while `_isConnecting`, because the step flips to connected before `_postConnectionSetup` finishes and a disconnect inside that window would null objects the setup still uses; the next fix catches it. The release call carries `disconnect_cause: airborne`, `airborne_gate` (the test that fired) and `airborne_value` (its reading, raw meters or km/h), plus `airborne_alt_m` and `airborne_speed_kmh`, BOTH readings of the fix that set the latch (each omitted when the platform did not know it, metric ints regardless of the unit setting), so a speed-gate fire can be told apart from a high-speed train; built by the pure `airborneReleaseInfo` in `lib/services/airborne_release.dart` and logged by the server. In Offline Mode the offline recording is paused for as long as the latch is set (`ApiQueueService.setOfflineRecordingPaused`, driven by `GpsService.onAirborneChanged`, logged once on pause and once on resume), so the RX flush at disconnect and any straggler row cannot land in the offline file; the server owner chose the app as the only control on that path. Known gaps: a small aircraft below both limits passes. Thresholds are compiled in (server-delivered limits and a server-side guard were considered and left out). Logged under `[GPS]`, `[APP]`, `[CONN]`. +### Precise Location at Connect + +With iOS "Precise Location" off, or Android 12+ granting only approximate location, fixes are off by hundreds of metres to kilometres, and the server refuses every fix worse than 50 m (`gps_inaccurate`), so such a session maps nothing. The four connect front doors (`connectToDevice`, `connectViaTcp`, `connectViaUsb`, `connectWithTransport`) therefore run `_refuseConnectIfImprecise()` right after the airborne refusal. That covers the Connection screen's BLE, TCP and USB buttons, the remembered-companion button, the anonymous-mode reconnect and the Siri/App Intent "connect last companion" path (it goes through `reconnectToRememberedDevice`). It is checked only at Connect, never at launch or in onboarding. + +- **Decision**: the pure `decidePreciseLocationStep` in `lib/services/precise_location_gate.dart`, run by `PreciseLocationGate.allowsConnect`. Web and the GPS simulator skip (the same cases `_gpsPolicyApplies` leaves out); no location permission skips too, leaving the existing denied path unchanged; `Geolocator.getLocationAccuracy()` precise, or an unreadable answer (fail open), connects; reduced asks once, then blocks. +- **iOS ask**: `Geolocator.requestTemporaryFullAccuracy(purposeKey: 'CoverageMapping')`, the key in `NSLocationTemporaryUsageDescriptionDictionary` (`ios/Runner/Info.plist`). Allowed continues the connect. A prompt that throws counts as declined. +- **Android ask**: `AppStateProvider.preciseLocationUpgradeRequester`, registered by `MainScaffold` on Android only. It shows the usual location disclosure (Google Play wants it before every system location prompt; there is no new disclosure), then `Permission.locationWhenInUse.request()`, which Android 12+ answers with its "precise" upgrade dialog while only COARSE is granted. Skipped when the permission is permanently denied. permission_handler reports this group `denied` while FINE is missing, so the plain request reaches the system. +- **Prompts only on screen**: with the app not resumed (a background Siri run) or no requester registered, reduced blocks without asking. +- **Block**: no connect, no `connectionError` (as with airborne); `preciseLocationPromptDue` makes `MainScaffold` show "Precise Location needed" with Cancel and Open settings (`Geolocator.openAppSettings()`), after the onboarding lane like its sibling prompts. Siri answers `preciseLocationVoiceMessage`. +- **Auto-reconnect** does not prompt: `_attemptReconnect` re-reads the accuracy before each attempt (`canPrompt: false`) and, if it is now reduced, ends through `_abandonAutoReconnectForImpreciseLocation()` (alert, error-log entry, same dialog), instead of mapping rough fixes. +- **GPS**: the check never starts GPS or sends a location, so the 1.4.2 background-location policy is untouched. The one GPS call is after an Android upgrade with a stream already running: `restartGpsAfterPermission(keepTracking: true)`, because a running Android request keeps the permission level it was registered with. +- A tap during the check is ignored as a duplicate (`_preciseLocationCheckInFlight`). Logged under `[GPS]`. + ### Smart Pinging -Auto mode defers TX pings and discovery requests in a grid square that already has a recent -bidir (green) or disc (cyan) result. A deferred ping is held rather than dropped: it waits in a +Auto mode defers pings in a grid square that already has a recent bidir (green) or disc (cyan) +result. By default ("Delay only flood pings", `smartPingFloodOnly`) only a green square holds a +TX ping and a discovery request is never held; with it off, a green or cyan square holds both. +A deferred ping is held rather than dropped: it waits in a one-slot bank and goes out at the first fix in a square with no recent coverage. RX logging is never deferred (it is free). Manual pings, Trace mode and the auto-mode start check are untouched. On by default with a 14 day window. @@ -424,7 +601,10 @@ untouched. On by default with a 14 day window. (any whole number of days from 1 to 365, typed into a number field; default 14; bounds in `SmartPingDays`). A stored value outside the range falls back to 14. The window tile is hidden while the switch is off. An (i) button beside the switch opens `_showSmartPingInfo`, - a dialog explaining the deferral in user-facing words. + a dialog explaining the deferral in user-facing words. A second switch, `smartPingFloodOnly` + ("Delay only flood pings", default true), sits under the window tile while Smart Pinging is + on. It is locked in auto mode, like the main switch, so it never changes mid-session, and + locked (amber "Set by Regional Admin.") while the region enforces Smart Pinging. - **Map trail**: a deferral adds a hollow yellow marker (`PingColors.deferred`, with color-vision palette variants) whenever the phone has moved the configured minimum ping distance since the last deferred marker, the same rule a real ping answers to, so a drive @@ -456,16 +636,21 @@ untouched. On by default with a 14 day window. clear its patch; patch bodies belong to a region/grid/radio/window context, and an in-flight fetch from an old context is discarded. This changes the coverage squares, not the session's ping markers or the Smart Pinging send rules. -- **Enforcement**: `/auth` carries `smart_ping` (bool) and `smart_ping_days` (int). When - `smart_ping` is true the switch is locked on and the window is the server's; otherwise the - user's own values apply. The preference is never overwritten: `AppStateProvider` - exposes effective getters (`smartPingEnabled`, `smartPingDays`, `enforceSmartPing`), the - `discDropEnabled` pattern. A missing or invalid field means not enforced, 14 days - (`ApiService.enforceSmartPing`, `apiSmartPingDays`). +- **Enforcement**: `/auth` carries `smart_ping` (bool) and `smart_ping_days` (int) and + `smart_ping_flood_only` (bool). When `smart_ping` is true the switch is locked on and the + window and the flood only setting are the server's; otherwise the user's own values apply. The preference is never overwritten: `AppStateProvider` + exposes effective getters (`smartPingEnabled`, `smartPingDays`, `smartPingFloodOnly`, + `enforceSmartPing`), the `discDropEnabled` pattern. A missing or invalid field means not + enforced, 14 days, flood only on (`ApiService.enforceSmartPing`, `apiSmartPingDays`, + `apiSmartPingFloodOnly`: only `false` or `0` reads off). - **Data source**: `vector_tile.php?z=13&gsize=&f_days=&f_types=green,cyan` - (`ApiService.fetchRecentCoverageTile`), decoded by `decodeCoverageCells`. The square is the - cell of the user's Coverage Grid setting (300 m or 100 m), so what is deferred matches what - is painted, including the Detailed 3 by 3 smear. The tap API (`app_coverage.php`) is not used. + (`ApiService.fetchRecentCoverageTile`, read from the coverage host: the group's own site when + the zone is grouped, see Multi-region groups), decoded by `decodeCoverageCells`. The square + is the cell of the user's Coverage Grid setting (300 m or 100 m), so what is deferred matches + what is painted, including the Detailed 3 by 3 smear. The tap API (`app_coverage.php`) is not + used. + The tile keeps each cell's colour: its `st` is read as green (1) or cyan (2), and the filter + stays `f_types=green,cyan` so one tile serves both settings. The fetch also carries the radio preset filter (`f_freq`, `f_bw`, `f_sf`, see Coverage Overlay), and `RecentCoverageService.configure(radioKey:)` drops every loaded tile when the preset changes, since a tile fetched under the old preset answers for the wrong layer. @@ -478,29 +663,46 @@ untouched. On by default with a 14 day window. back carrying any cell other than green or cyan is treated as unfiltered (a region server without the `f_*` filter support) and ignored, so the lookup stays `unknown` there. Cells this session covered itself (a heard TX, an answered discovery) are marked covered at once - (`markCovered`). `isCovered` is synchronous and returns `covered`, `clear` or `unknown`. + (`markCovered(lat, lon, CoverageColor)`: a heard TX echo is `CoverageColor.green`, an answered + discovery `CoverageColor.cyan`, and green wins, so a later cyan never downgrades a green + mark). `isCovered(lat, lon, {required forTx})` is synchronous and returns `covered`, `clear` + or `unknown`. With `floodOnly` (set through `configure(..., floodOnly:)`) a discovery + (`forTx` false) always reads `clear` and only a green cell holds a TX; with it off either + colour holds both. Tiles keep both colours, so flipping `floodOnly` keeps them and only + changes how they are read. - **Fail open**: `unknown` (no tile yet), a fetch failure, Offline Mode, no zone, or the feature off all let the ping go out. -- **The deferral**: `PingService.checkRecentCoverage` (wired to `isCovered`) is consulted by - `canPing()` before the distance check (covered wins: a fix that is both reads Deferred, not +- **The deferral**: `PingService.checkRecentCoverage(lat, lon, BankedPingType kind)` (wired to + `isCovered(forTx: kind == tx)`) asks per ping kind. It is consulted by `canPing()` (as `tx`) before the distance check (covered wins: a fix that is both reads Deferred, not Skipped, so parked on already mapped ground is held rather than rate limited, and both Hybrid - legs agree) and by the auto discovery path alongside its distance check. It yields + legs agree) and by the auto discovery path (as `discovery`) alongside its distance check. It yields `PingValidation.recentlyCovered` and the skip reason `'recently covered'` (`PingService.skipReasonRecentlyCovered`), which rides the existing `onAutoPingScheduled` hook, and it banks the ping instead of dropping it. The interval timer is untouched: the next attempt is still scheduled at the normal interval, so the timer stays - the backstop for a phone that never reaches a clear square. + the backstop for a phone that never reaches a clear square. In Hybrid the discovery leg also + asks about TX: a square that is clear for discovery but still covered for TX (flood only, + green square) sends the discovery and keeps the banked TX waiting, instead of handing the leg + to the TX. - **The bank**: one slot. `PingService._bankedPing` holds a `BankedPingType`, either `tx` (Active or Hybrid) or `discovery` (Passive or Hybrid), readable through `bankedPing`. A - later deferral overwrites an earlier one, so what eventually goes out is whichever type was - most recently due. `maybeSendBankedPing(position)` releases it and returns true when it + later deferral overwrites an earlier one, except that in Hybrid a held TX ping is never + replaced by a discovery: a deferred discovery leaves the TX held (and its DEFER names the + TX), and a discovery leg whose fresh fix is not covered (`clear` or `unknown`) and passes + the TX distance rule sends the held TX in its place (when the square is still covered for TX + the discovery goes out and the TX stays banked). That leg clears the bank and the + in-progress latch, sets `_nextPingIsDiscovery` back to true and dispatches the TX from the + attempt's `finally`, so the next leg is a discovery and the TX re-arms the lane itself. The + release check alone cannot cover this: it is refused while the discovery holds the latch + across its fresh fix, that fix bypasses the position stream, and it only releases on + `clear`. `maybeSendBankedPing(position)` releases it and returns true when it dispatched one. Dispatched rather than delivered: both send paths take their own fresh fix and re-validate, so a released ping can still be stopped inside the send. The GPS position listener in `AppStateProvider` calls it on every fix, placed after the airborne early return, and on a true it also clears the countdown's skip reason so the label does not keep reading "Deferred" while the released ping is going out. -- **What lets a banked ping go**: the fix must answer `RecentCoverage.clear` (`unknown` is not - enough, and the interval tick already fails open there) and must satisfy the same 25 m +- **What lets a banked ping go**: the fix must answer `RecentCoverage.clear` when asked with the + banked kind (`unknown` is not enough, and the interval tick already fails open there) and must satisfy the same 25 m minimum-distance rule the send path enforces, measured against the last TX or the last discovery to match the banked type. The release is refused while auto mode is off, in targeted (Trace) mode, with a disable pending, with a ping already in progress, with the @@ -510,7 +712,8 @@ untouched. On by default with a 14 day window. airborne check of its own the way a TX send does through `canPing()`). On release it cancels the pending auto and discovery timers and sets `_nextPingIsDiscovery` explicitly rather than toggling it, so Hybrid's alternation stays correct however many deferrals came first. -- **Clearing the bank**: a ping that proceeds to send clears it, and so do auto-mode start, +- **Clearing the bank**: a ping that proceeds to send clears it (a discovery leg with a TX + held sends that TX instead, see above), and so do auto-mode start, stop, mode switch and `dispose()`. `clearBankedPing()` clears it from `_syncRecentCoverage` when the lookup goes inactive, because with the lookup off `isCovered` answers `clear` for every fix and would otherwise release the hold on the next GPS tick. Every other skip of a @@ -520,7 +723,7 @@ untouched. On by default with a 14 day window. not re-banked, so that one deferral is lost (pre-branch behaviour, and not worth the extra state to recover). - **"Deferred", not "Skipped"**: the word applies only to this hold. The countdown labels pick - it from the skip reason (`_pausedWord` in `lib/widgets/ping_controls.dart`), so the 25 m + it from the skip reason (`lib/services/status/ping_control_labels.dart`), so the 25 m distance skip still reads "Skipped". The shared phase title is the bare word `Deferred` with the detail "Waiting for a square with no recent mapping", carried by `LiveActivityPhase.deferred` (wire value `deferred`) and labelled natively in @@ -554,7 +757,8 @@ untouched. On by default with a 14 day window. row heard with no mode running, absent only when no getter is wired, which the server reads as unknown, and never on a `DEFER`, which the factory cannot stamp). (3) One `DEFER` item per fixed 300 m square per API session, `{type, lat, lon, timestamp, held}` with `held` - `tx` or `disc` and nothing else (no antenna, noise floor, power or altitude: the server pays + `tx` or `disc` and nothing else (`disc` only appears with Delay only flood pings off, since a + discovery is never held otherwise) (no antenna, noise floor, power or altitude: the server pays for the square, not the reading). `PingService.onPingDeferred` fires at the two deferral sites (the TX auto branch and the discovery send) with the validated fix; the provider dedupes it through `RecentCoverageService.markDeferred` (always the 300 m grid, whatever the @@ -578,13 +782,394 @@ untouched. On by default with a 14 day window. `DEFER` enqueue) and `[PING]` / `[DISC]` (deferrals, releases and drops). The batch and heartbeat request summaries under `[API]` / `[HEARTBEAT]` show `auto_mode`. +### Scope Discovery + +After a discovery sweep finds repeaters, the app can ask up to 3 of the strongest ones which +scopes (the channels or contacts a repeater passes) they carry, and upload each answer as its +own `SCOPES` item. It never runs on its own: it only follows a discovery that a Passive or +Hybrid session already made, and it never changes when a TX or discovery ping is due, or +replaces one. A ping, trace send or banked-ping release that is written while the short radio +lease is held does wait for it to release first, normally a few hundred milliseconds and at +most about 4 seconds (see the short radio lease below); the schedule itself is never touched. +Off by default until a region turns it on. + +- **The gate**: `/auth` carries `scope_discovery` (bool) and `scope_refresh_days` (int) on every + live and offline-mode auth. **Server first is built into the gate itself**: an old server + that never adds the key is read as key absent, and the app then never asks and never uploads + a `SCOPES` item, whatever the user's own switch says, with no separate version check needed + anywhere else. Key present with `true` (or `1`) locks the user's switch on and enforces the + server's own interval regardless of the user's own setting: `scope_refresh_days` missing or + non-numeric reads as 14 days, and any numeric value below 7 reads as 7 (floored at 7, no + ceiling otherwise). Key present with anything else leaves the user's own switch and interval + in force (default off, 14 days, minimum 7, clamped rather than falling back to the default the + way Smart Ping's interval does). `AppStateProvider.scopeDiscoveryActive` + (`scopeDiscoveryGateOpen` in `lib/services/scope_discovery/scope_lifecycle.dart`) is the one + predicate every send site reads: offered, (enforced OR the user switch), never in Offline + Mode, and the connected companion's firmware at or above the floor below. Settings (Settings + -> Wardriving -> Auto-Ping, beneath Smart Pinging): a `Scope Discovery` switch, an (i) button + explaining it in plain words, an amber "Set by Regional Admin" subtitle, and a locked switch + and interval tile while enforced. + +- **Firmware floor**: companion firmware code 13 (`kScopeDiscoveryFirmwareFloor`, shipped as + v1.16.0) or newer. Below it `scopeDiscoveryActive` reads false no matter what the switch + says, and the switch's subtitle shows `ScopeDiscoveryFirmwareNote`, "Your radio needs + firmware v1.16.0 or newer for this." The setting still saves: nothing is asked and nothing + extra goes on the air until the radio is updated, so a user does not lose their own choice by + upgrading later. + +- **The due rule and the phone cache** (`lib/services/scope_discovery/scope_discovery_rules.dart`, + `isScopeQueryDue`): a repeater is due only when it is not currently held (below), and BOTH the + server's own `scopes_checked_at` for it (missing, or older than the interval in force, counts + as due) AND the phone's own cached answer for it (the same rule) call for a fresh ask, and no + earlier answer for it is still being written (`pendingPersist`). The phone cache + (`ScopeQueryCache`) only ever remembers an ANSWER as a durable stamp: a flood, an unreadable + reply or a radio error is logged and leaves no entry behind, so that repeater reads as due + again at the very next discovery on those outcomes. It is JSON in `user_preferences` + (`scope_query_cache`), pruned at load to the interval in force and capped at 20,000 entries + (oldest evicted first past the cap), so a stamp written just before a crash still suppresses + the ask afterward. + +- **The no-answer hold**: a repeater that got no answer at all (`ScopeNoAnswer`) is different + from the other non-answer outcomes above, because the repeater firmware answers at most 4 + anonymous scope requests per 3 minutes, shared across every phone asking it, not just this + one. Re-asking a silent repeater on the very next sweep keeps it silent and starves every + other phone's turn at the same budget, so this one outcome starts a per-phone hold instead of + leaving the repeater due again at once. Consecutive misses (no answer landing in between) + hold it for 1, 5, 10 and 20 minutes (`ScopeQueryCache.noAnswerHoldSteps`), then 30 minutes + each (`ScopeQueryCache.noAnswerHoldMax`). The first step is short because a first miss is + usually a car at the edge of the repeater's range, and a longer hold (it used to start at 15 + minutes and double to 2 hours) meant the car had left that range for good before the retry. + Once a hold runs out the retry also needs a stronger signal: until 30 minutes after the miss, + the repeater must be heard by the sweep's own discovery at least 1 dB above the RSSI it had at + the miss (`strongerSignalMarginDb`, `ScopeQueryCache.awaitingStrongerSignal`), since asking + again at the same signal would most likely go unanswered and spend the shared budget for + nothing. A parked phone therefore waits the full 30 minutes, and a car closing on the + repeater gets another try within about a minute. An answer that PARSES clears its hold and its miss count + at once (`ScopeQueryCache.clearHold`, called the moment `parseRegionsReply` succeeds), whatever + happens to it afterward: a failed hourly-budget reservation write or a refused enqueue still + proved the repeater reachable right then, so neither may leave the miss count in place for the + next ask to step up from. The durable answer stamp (`recordAnswer`, which clears the hold too, + redundant by that point) still waits on a successful persist, since that stamp feeds the OTHER + cache rule (the due rule above), not this one. Only `ScopeNoAnswer` starts or extends a hold: a + flood, a radio error, an unreadable reply (never parsed, so never cleared either), a local + failure, an abort or a cancel never does, so those outcomes keep re-asking on the very next + sweep as before. The hold is memory only, exactly like + `pendingPersist`: never written to `toJson`, never read back by `fromJson`, so it does not + survive a relaunch, only this phone's own no-server-coordination choice for the run it is in. + `isScopeQueryDue` takes the hold as a plain `heldUntil`/`nowSec` pair so the rule itself stays + pure; the runner reads it off the cache before choosing candidates and logs one `[SCOPES]` line + when a hold starts or extends, and the sweep summary line reports how many candidates were + held and how many were waiting on a stronger signal (`weak`). + +- **The repeater list refresh cadence**: the due rule reads the server's own `scopes_checked_at` + off the repeater list (`AppStateProvider._repeaters`), which the app itself must keep fetching + or another phone's answers never reach this one. Three triggers share the same refresh + (`AppStateProvider._refreshRepeatersForScopes`, `ScopeLifecycle.resultIfStillCurrent`'s discard + when the zone or radio preset moved while it was in flight, and `scopeRefreshChangesMap`'s "did + this change anything the map draws" check, all unchanged): at connect, a list missing or older + than 1 hour (`kScopeRepeaterListMaxAge`); when Passive or Hybrid mode starts, a list older than + 5 minutes (`scopeListRefreshOnStartAge`), refreshed at once rather than waiting on the other + two triggers; and, for as long as Passive or Hybrid keeps running, every 15 minutes + (`scopeListRefreshPeriod`), unconditionally, since a phone driving for an hour needs more than + the connect-time refresh caught at the start of the drive. All three are gated on + `scopeDiscoveryActive` (offered, the effective switch on, not Offline Mode, firmware at or + above the floor) and a known zone, so a user without scope discovery, or before a zone check + has landed, sees no change in traffic; `scopeModeStartRefreshPlan` + (`lib/services/scope_discovery/scope_provider_support.dart`) is the pure decision for the + mode-start trigger (whether to refresh at once, and whether to arm the periodic timer at all), + kept separate from the network call so it is unit-testable with a fake clock. Only one refresh + runs at a time across all three triggers (`AppStateProvider._scopeRepeaterRefreshInFlight`); a + trigger that lands while one is already in flight is a no-op, not a queued retry, since the + next connect, mode-start or periodic tick asks again anyway. + The periodic timer (`ScopeLifecycle.startRepeaterRefreshTimer`/`stopRepeaterRefreshTimer`) is + a dumb repeating scheduler with no memory of the gate itself; every tick re-checks + `scopePeriodicRefreshShouldRun` (scope discovery active, Passive or Hybrid still the mode + running, a known zone), the same three facts the mode-start check reads, so a tick that lands + after some OTHER path changed one of them without going through the timer's own stop still + does nothing rather than refresh for a mode or a gate state that no longer holds. + + It stops on whichever ends first: the mode itself stopping (`AppStateProvider._finishAutoPingStop`, + the mode-switch teardown inside `toggleAutoPing`'s start branch since switching between two + running modes never passes through `_finishAutoPingStop`, and `_startZoneGracePeriod`'s own + ad hoc disable, which bypasses the normal stop the same way), or any `ScopeLifecycle` stop + event (disconnect in both flows, an Offline Mode switch in either direction, a zone transfer, + the gate closing under a live session, and dispose), all of which stop the timer inside + `ScopeLifecycle.onEvent` itself; `onGateChanged` stops it even with no scope request currently + running (a gate closing between sweeps must not leave the timer ticking on into a session that + can no longer ask anything). + + **Reopening the gate re-arms it.** A gate that closes and reopens while Passive or Hybrid never + stopped (a live `/auth` answer withdrawing and then restoring `scope_discovery`, or the user + flipping their own switch back on) must not leave the refresh stopped for the rest of the + session: `onGateChanged` takes `passiveOrHybridRunning` and a `startRepeaterRefresh` callback + (`AppStateProvider._startScopeRepeaterRefreshForRunningMode`, the exact mode-start sequence, + 5-minute stale check included) and calls it when the gate is open again, the mode is still + running, and nothing is already scheduled; already running, or the mode not running at all, is + a no-op, so an unrelated preference change does not keep rescheduling it. The three paths that + RESTORE a stopped mode (auto-reconnect success, zone-grace re-entry, a completed zone transfer) + all resume it through `toggleAutoPing`, so they already re-arm through the ordinary mode-start + hook and need no separate wiring here. The Offline Mode hot switch back to online is the one + path that does not resume any auto-ping mode at all today, by design (the user restarts it), + so there is nothing for this gate to re-arm on that path. + +- **Why requests run one at a time, and why pings may run alongside them**: the companion keeps + one pending request outstanding, the same reason Repeater Administrators' own commands never + overlap, so the runner asks its chosen repeaters strictly in sequence, one lease per repeater, + never in parallel. A TX or discovery ping is a different matter: while the short-lived radio + lease actually holds the radio (below), another write simply waits its turn at the same gate + a sign write parks other writers behind, so nothing is lost, only delayed by at most the + lease's own hold. A TX that waits there arms its echo tracking, creates its log record and + takes its send time only once its frame is past the gate, just before the transport write + (`MeshCoreConnection.sendPing`'s `onWire`), so the wait never eats into its listening window + and an echo is still never missed. Once the lease releases and the runner is only listening for the tagged + answer, a ping can go out and come back without touching that listen at all, since only a + frame carrying the answer's own tag ends it early: nothing else in flight ever clears it. + +- **The short radio lease** (`lib/services/meshcore/scope_lease.dart`, `ScopeLease`): exists so + a scope ask can never indefinitely delay a ping or a repeater-admin command, or the reverse. + **Admission** is granted only in one synchronous step, with nothing else already holding the + radio: no sign in progress or waiting, no admin session open, the contact stream idle, and + the connection's reply ledger completely clear, meaning every reply an earlier command owes + has come back. Most commands owe exactly one reply frame. `getContacts` owes its initial + reply (`CONTACTS_START`, or an ERR) like any other command and then opens a stream tracked on + its own, which must also have ended. A self telemetry request owes one reply too, but that + reply is the telemetry push 0x8B rather than a frame below 0x80. A reboot, factory reset or + CLI reboot owes none, since the radio goes away. So a lease is never granted while anything + is still owed an answer. An owed reply that expires unanswered (10 seconds after its write, + `kReplyOwedExpiry`) may still arrive later, and from then on nothing tells which reply answers + which command: a stale `ERR_NOT_FOUND` or `CONTACT` could be taken as a new lookup's answer + and skip the zero-hop borrow. So the first expiry suspends scope discovery for the rest of + that connection (logged once under `[SCOPES]`), exactly as a contact stream silent for 60 + seconds does; wardriving is untouched, and a reconnect (a new connection object) clears it. **The write gate**: exactly as a `CMD_SIGN_DATA` + write queues every other write behind `_signGate` (see MyMeshMapper Account), a granted lease + opens its own gate the same way: every OTHER write queues behind it and goes out once the + lease releases, while the lease's own commands skip that queue and go straight to the + transport. **The hold cap**: at most 4 seconds from grant (`kScopeLeaseHold`), long enough for + a lookup, a route borrow, the send and the restore, never longer; a new command (or a queued + restore) is only written with the ledger clear and at least 500 ms left on the clock. + Reaching the cap while a send has already gone out still lets that request's own answer wait + continue outside the lease; reaching it before the send goes out ends the request at once + (`hold_cap`) rather than wait for a reply that may never come. **Manage waits for it**: + `MeshCoreConnection.isScopeRadioBusy` is true while a lease is held or a reply to a command + a lease wrote is still owed (`hasScopeReplyDebt` counts only those entries, so the pollers' + and other ordinary replies never hold Manage). The connection fires `onScopeRadioBusyChanged` + only when that flag actually flips (grant, release, the last scope reply retiring, expiring + or being cleared), and the provider answers with a plain `notifyListeners()`, never a + `mapRevision` bump; the Trace row's Selector record carries the flag, so Manage re-enables the + moment the radio frees up instead of waiting for an unrelated control change. + +- **The zero-hop route borrow and its byte-exact restore**: a repeater already known as a + multi-hop contact would otherwise route a scope request the long way and answer late, so the + lease rewrites its route to zero-hop (`out_path_len 0`) for the one send, using the contact + record exactly as read (`ContactRecord.withOutPathLen(0)`), then writes the SAME record back + byte for byte afterward, its raw 32-byte name field and whatever `lastmod` it carried + included, so nothing about the contact changes except the trip this one request takes. A + restore that cannot be written before the lease's own deadline is kept (`unrestored`) and + held (`ScopeLifecycle.restoresFor`) across runner sweeps on the same connection until it + succeeds, ahead of anything else that connection's next lease writes; a repeater that is not + yet a contact skips the borrow entirely, since firmware sends the request direct with + nothing to restore. + + **An accepted residual**: the lookup and the send are not atomic. Firmware can auto-add or + refresh a contact from an advert that happens to arrive in the gap between them, and when it + does the send goes out as a flood instead of direct. `SENT`'s own flood byte catches this + after the fact (`ScopeFlooded`, logged and moved past), but nothing on the app side can + prevent it; documented here rather than chased as a bug. + +- **The full contact table (a companion firmware bug)**: companion firmware v1.16.0 needs a + contact-table slot to ask a repeater that is not already a saved contact (the send auto-adds + one for the one request), and when the user's own contact table is already full the radio + refuses with `ERR_CODE_TABLE_FULL` (3) instead of sending. MeshCore fixed this in v1.17.0 with + 8 reserved transient slots, but both versions report the same firmware code (13), so the app + cannot tell them apart from `DEVICE_INFO` alone. + + **ERR 3 is ambiguous, and the app confirms it before believing it.** The same error code also + answers a transient, unrelated failure: `BaseChatMesh::sendAnonReq` returns `MSG_SEND_FAILED`, + which the companion also writes as `ERR_CODE_TABLE_FULL`, whenever its own packet allocation + fails (an empty packet pool), whatever the recipient was, contact table full or not. So an ERR + 3 on a non-contact's send does not by itself prove the table is full: the anon contact may have + been allocated fine and the send itself failed for an unrelated, transient reason. Before + latching anything, `ScopeLease` asks once more, inside the same lease + (`_confirmContactNotAllocated`, `CMD_GET_CONTACT_BY_KEY` for the same key, obeying the lease's + own deadline and reply-ledger rules): `CMD_GET_CONTACT_BY_KEY` reads the very table `addContact` + just inserted into, so finding the contact now means the slot exists and the failure was the + packet pool, not the table (verified against both `companion-v1.16.0` and current `dev`: both + read `lookupContactByPubKey` off the same table `addContact` writes, so a transient anon contact + is found by a follow-up lookup in either firmware). Only a re-lookup that answers + `ERR_CODE_NOT_FOUND` (the contact really could not be allocated) latches the flag; a re-lookup + that finds the contact, answers anything else, or has no time left in the lease to even run, + does not latch, and the ask is logged as an ordinary radio error instead. + + Once latched, `MeshCoreConnection.scopeCannotAskNonContacts` stays true for the rest of that + connection (a saved contact's own ERR 3 never reaches the confirmation step at all, so it never + sets it, and a reconnect builds a new connection object and clears it). From then on the runner + remembers every key its own lookup already proved is not a contact (`ScopeRunner`'s + per-connection `knownNonContacts`, held the same way as `pendingRestores`) and filters those keys + out before choosing the sweep's top 3, not after: a known non-contact stealing a top-3 slot only + to be skipped there would starve a weaker, askable repeater (a saved contact, or one not yet + proven a non-contact) out of every sweep for the rest of the connection. A repeater of unknown + status is still looked up (a local BLE read, no airtime) and, if the lookup says not-a-contact, + the lease ends right there without writing the send (`ScopeNonContactRefused`, a debug log line + only, never a log tab entry). A saved contact is asked exactly as before, flag or no flag. The + log tab shows the ERR 3 that sets the flag as "Radio contact list full" + (`ScopeLogOutcome.radioContactsFull`) rather than the generic "Radio error", and the first time a + connection sees the flag set, `AppStateProvider` drops a warning into the Errors list naming the + fix (companion firmware v1.17 or newer, or removing some contacts) instead of the generic error, + since users rarely reopen Settings mid-drive to see a note there. Fired only on the transition + through `MeshCoreConnection.onScopeCannotAskNonContactsChanged`, latched to once per connection, + and logged with `severity: ErrorSeverity.warning, autoSwitch: false` so it never pulls the user to + the Errors tab on its own (a plain `notifyListeners()` still follows, never a `mapRevision` bump, + per Rule 9). + +- **Choosing repeaters and the distance gate**: strongest local RSSI first, local SNR to break + a tie, then the repeater's key for a stable order past that; at most 3 per sweep + (`ScopeRunner.maxAsksPerSweep`). The gate measures how far the PHONE has moved (straight + line, against its latest fix) from the discovery position, never the distance to the + repeater itself: the app has no other fix on where a repeater actually is, only where the + phone stood when it heard it. Moving more than 300 m from that point ends the rest of the + sweep outright (`scope_runner.dart`, `_mayAsk`), not just a skip of the one repeater over the + line, since a car that has moved on should not spend airtime on any of what it left behind. A + phone with no current fix skips the check rather than block on it. A stationary phone can + therefore still ask a repeater that is, in reality, well over 300 m away: the gate only ever + measures how far the phone itself has travelled. + +- **The answer wait**: each repeater's own measured discovery reply time (`DiscTracker`'s + `discoveryReplyAfter` for THIS sweep's own tag, never a foreign one) plus a 2 second margin + (`discoveryReplyMargin`), capped at 7 seconds total (`kScopeAnswerWaitCap`); a repeater with + no measured reply time (its discovery answered before the runner started, or under a foreign + tag) gets the full 7 second cap reserved instead, since the radio's own timing estimate is + only known after `SENT`. The margin exists because the discovery reply time only measures how + long a much shorter frame took to come back over that route; the scope answer is a longer + push over the same path, so a fixed pad is added rather than assuming an identical round + trip. Every ask is checked against the next scheduled discovery twice: before it starts + (admission wait, the lease's own hold and the answer wait must all still fit before the next + discovery is due) and again right after the lease is granted (just the hold and the wait, + since the admission time is already spent); either check failing stops the whole runner + rather than let an ask begin that cannot finish. + +- **The hard stop and cancellation**: a runner never outlives 30 seconds (`maxRunnerLifetime`) + or the next scheduled discovery send, whichever comes first, and a Timer enforces it even + mid-ask. Cancellation reaches the same runner from many places: the next discovery send + (about to reuse the radio), a newer sweep superseding an older one, Stop (parked behind an + in-flight TX, or immediate), force disable, the airborne block, an Offline Mode switch in + either direction, a zone transfer, user disconnect, the full disconnect cleanup, + auto-reconnect, provider disposal, and the gate closing while a request runs (a live `/auth` + answer, a session recovery's included, that drops or disables `scope_discovery`, applied + before anything in that answer's handling is awaited, the stale wire-tag queue cleanup of a + new session id included, or the user switching the feature off; `ApiService.onScopeDiscoveryChanged` and + `ScopeLifecycle.onGateChanged`) (`ScopeStopEvent` in + `lib/services/scope_discovery/scope_lifecycle.dart`). Every one of these cancels the + runner's token at once (no further frame goes out for it), releases a held lease + synchronously, and clears the badge. An Offline Mode switch also blocks new runners for as long as it + runs (`ScopeLifecycle.beginModeSwitch` on its first line, before anything is awaited, and + `endModeSwitch` when it ends, success or not), because the gate still reads open until + Offline Mode is set at the end of the switch and a discovery window closing during its waits + would otherwise start a fresh runner. A connection actually going away also drops its list of + routes still owed a restore (the per-connection `pendingRestores`), and nothing restores them + on reconnect. **An accepted residual**: a disconnect between the borrow and its restore can + leave the borrowed zero-hop route on the radio until firmware relearns a path to that + repeater. + +- **The "Scopes" badge**: a small pill on the Passive and Hybrid ping buttons only (never + Active or Trace, neither of which runs a discovery) while a request is out + (`AppStateProvider.isScopeRequestActive`, a plain `notifyListeners()`, never a `mapRevision` + bump, per Rule 9). It never changes a button's label or its countdown text, only adds the + pill, and it never blocks a tap. + +- **The Scopes log entry**: only a request that actually reached a repeater and got an answer + or a refusal is logged (`ScopeLogEntry` / `ScopeLogOutcome` in + `lib/models/scope_log_entry.dart`): answered (with the scope names exactly as received, case + kept), no response, flooded, unreadable answer, radio error, radio contact list full, or + withheld by the hourly cap. A + local failure, an abort, a cancel or the distance gate never reached a repeater and stay + debug log lines only. Entries live in their own `ScopeLogStore` (newest first, capped at 500, + cleared by both Clear Pings and Clear All Logs), merge into the unified log tab under an + `SCP` filter, and export to CSV with the same `SCOPES,` prefix in both the filtered and the + full export. + +- **Accepted non-atomic risks, besides the lookup-versus-send one above**: persisting an + accepted answer is three separate steps run one after another, an hourly-budget reservation, + the queue enqueue, then the cache stamp, each independently loggable. A crash between the + first two loses the answer with its hour slot already spent; a crash between the last two + leaves the answer queued (it still uploads) but not yet remembered as answered, so the same + repeater can be asked again before its own earlier answer has even left the phone. Both are + rare and self-correcting (the repeater is simply asked again), so neither is treated as a bug + to chase. Separately, a lease reply that arrives after the lease has already released (a slow + restore `OK`, past the 4 second hold) can be claimed by an unrelated pending TX or discovery + reply instead of being ignored, the same limitation an unrelated poll error already had + before this feature existed; not fixed here. + +- **The 60 per device-hour budget** (`ScopeHourlyBudget`, same file as the due rule): at most 60 + `SCOPES` uploads per connected device (its radio public key, or the session id with no key) + per hour of the ANSWER's own timestamp, mirroring the server's own cap exactly. The runner + checks the budget before every ask and stops the WHOLE sweep, not just that one repeater, + once the hour is full, since asking further would only produce more answers the budget + cannot accept. + +- **DISC before SCOPES, every upload, and the cross-zone residual**: the server only accepts a + `SCOPES` item for a device that also uploaded a DISC for the same repeater with a timestamp + within 1800 seconds, in the same batch or an earlier one. `orderDiscBeforeScopes` (a stable + partition) enforces this ordering everywhere pings leave the phone: the normal batch queue, + the pre-disconnect snapshot, and the offline-session export; `selectBatchWithScopesDependency` + additionally keeps a `SCOPES` out of a batch entirely while its DISC is still queued anywhere + (Hive or memory, regardless of retry backoff), so a DISC still waiting out a retry holds its + own SCOPES back rather than let it upload alone. **A residual the server accepts**: DISC-heard + is stored against the zone that processed that batch. A zone transfer clears the online queue + and bumps its own generation, and the transfer's own selection keeps a `SCOPES` with its DISC + while that DISC is still queued, but a `SCOPES` that reaches the server in a different zone's + batch than its own DISC is still dropped there, since the two were processed by different + zones. Documented as accepted, not fixed on the app side + (`MeshMapper_Server/docs/APP_API.md`). + +- **The upload-door strip, and Offline Mode never asking**: a `SCOPES` item is dropped, never + uploaded and never forwarded to the custom third-party endpoint, the moment the live + `scope_discovery` key goes missing from a later `/auth` (the region turned the feature off, + or the app reconnected to a region that never had it), whether or not the item survives the + drop attempt in Hive. Offline Mode strips every `SCOPES` row from a stored offline session + before it uploads when that session's own auth answer carries no `scope_discovery` key at + all (key absence, not the value `false`, is the strip's own gate), rewriting the stored file + before any chunk goes out so a partial upload's retained rows are exactly the ones never + sent. Offline Mode itself never asks in the first place: the app's own asking gate excludes + Offline Mode outright, so no `SCOPES` item is ever created while offline; the strip exists + only for a session recorded before a switch was flipped, or a stray file from an older build. + +- **The SCOPES item** (`ApiQueueItem.fromScopes`, Hive field 21 `scopes`): `{type: "SCOPES", + public_key, scopes, timestamp, lat, lon}` plus `radio_freq` when the radio reported one. + `public_key` is the answering repeater's full key, normalized to 64 upper-case hex (a key + that will not normalize throws rather than queuing a broken item; `enqueueScopes` validates + first and never reaches that throw). `scopes` is the names exactly as the repeater sent them, + case kept, `*` kept, at most 33, empty valid. `lat`/`lon` are where the DISCOVERY that found + the repeater was made, not where the answer arrived; `timestamp` is when the answer arrived. + Never `external_antenna`, `noisefloor`, `altitude` or `power`, and never stamped with the + running auto mode, the same shape as `DEFER`. Logged under `[SCOPES]`. + +- **The status bar's Scopes chip**: `PingStats.scopeCount` counts the repeaters that answered a + scope request this session (log outcomes `answered` and `withheldHourlyCap`, one per answer, + the same rows the Log tab lists under SCP minus the ones nobody answered). It is counted by + `PingService.recordScopeAnswer`, called from `AppStateProvider._addScopeLogEntry`, so it + resets with TX/DISC/Trace (`resetStats`, a new `PingService` at connect) and is not cut by + Clear logs or the log's 500-entry cap. Trace and Scope share one chip + (`statusBarSharedSlot` in `lib/widgets/status_bar.dart`): Trace while `autoMode` is + `targeted`, else Scope while `scopeDiscoveryActive` or once `scopeCount > 0`, else no chip. + +### Top Status Bar + +`lib/widgets/status_bar.dart`: region chip, then TX, RX, DISC, the shared Trace/Scope slot +(above) and Uploaded. Counts from 1000 are shortened by `formatCompactCount` +(`lib/utils/compact_count.dart`: "1.4k", "12k", "1.2M", truncated, never rounded up). The +stats group sits in an `Expanded` + `FittedBox(scaleDown)`, so with large Accessibility text it +shrinks instead of overflowing. `test/widgets/status_bar_fit_test.dart` renders the real bar +with the SDK's Roboto and Material Icons fonts at 320/375/393 px and requires 4-digit counts to +fit a 375 pt phone at normal text without any shrinking; it skips the width cases when +`$FLUTTER_ROOT/bin/cache/artifacts/material_fonts` is missing. + ### API Queue System Three data flows (TX pings, RX observations, Discovery results) merge into unified API batch queue: - **Storage**: Hive-based persistent queue survives app restarts -- **Batch Size**: Max 50 messages, auto-flush at 10 items or 30 seconds -- **Payload Format**: `[{type:"TX"|"RX"|"DISC"|"TRACE", ...}]`. TX/RX include `heard_repeats`; DISC includes `repeater_id`, `node_type`, `local_snr`, `local_rssi`, `remote_snr`, `public_key`; TRACE includes `repeater_id`, `local_snr`, `local_rssi`, `remote_snr`. Every type also carries `altitude` (whole meters, omitted when the phone did not know it; iOS reports height above mean sea level; Android usually reports height above the WGS84 ellipsoid, but Android 14+ substitutes mean sea level when the fix carries it, so one device can report either. The two references differ by the local geoid separation, up to ~100 m) +- **Batch Size**: Max 50 messages per batch. A periodic batch timer uploads every 15 seconds (60 seconds on a constrained link), and a ping flush runs 5 seconds after a ping is enqueued (60 seconds constrained) +- **Payload Format**: `[{type:"TX"|"RX"|"DISC"|"TRACE"|"SCOPES", ...}]`. TX/RX include `heard_repeats`; DISC includes `repeater_id`, `node_type`, `local_snr`, `local_rssi`, `remote_snr`, `public_key`; TRACE includes `repeater_id`, `local_snr`, `local_rssi`, `remote_snr`; SCOPES carries only `public_key` and `scopes` (see Scope Discovery), none of `external_antenna`, `noisefloor`, `altitude` or `power`. Every other type also carries `altitude` (whole meters) together with `altitude_ref` (`msl` above mean sea level, or `ellipsoid` above the WGS84 ellipsoid) and `altitude_acc` (vertical accuracy in whole meters, about one sigma, omitted when unknown). The altitude and its reference travel together or not at all, and the accuracy only beside them: an altitude whose reference the app cannot prove is never uploaded, and an offline session saved by an older build has its bare altitudes stripped at upload (`withoutUnlabelledAltitude`). iOS is always `msl`. Android below 14 is always `ellipsoid` (the app never enables the plugin's NMEA sea level option). On Android 14 and later the plugin swaps in a sea level value whenever the fix object carries one, so `GpsService` asks a native handler (`MeshMapperAltitudeService.kt`, channel `meshmapper/altitude`) to describe the provider's last fix and `resolveFixAltitude` (`lib/services/fix_altitude.dart`) proves identity by exact timestamp, coordinates and altitude value before labelling; nearness is never accepted. The GPS simulator and mocked fixes resolve unknown. Resolution runs in the background per fix (`FixAltitudeResolver`, keyed by exact fix plus a source generation, 128 entries) so no send path waits; it never notifies or bumps `mapRevision`. Logged under `[GPS]`, one line on first resolution, a once-a-minute warning when an Android fix cannot be proved, and one summary line per 50 Android resolutions (`AltitudeResolutionStats`). Contract: `MeshMapper_Server/docs/APP_API.md`) - **Radio preset stamp**: every item (TX, RX, DISC, TRACE and DEFER) carries `radio_freq`, the radio's configuration tag `freqMHz,bwKHz,SF,CR` as reported at connect (`ApiQueueItem` Hive field 20, read at enqueue time through `ApiQueueService.radioConfigGetter`, wired to the live @@ -595,8 +1180,17 @@ Three data flows (TX pings, RX observations, Discovery results) merge into unifi `MeshMapper_Server/docs/APP_API.md`. - **Authentication**: API key in JSON body (NOT query string) - **Retry Logic**: Exponential backoff on failures. A 429 storm-brake answer holds the whole queue for the server's `Retry-After` without spending a retry (see Session Heartbeat) +- **Scheduled uploads can be paused**: `ApiQueueService.pauseScheduledUploads()` cancels the periodic batch timer and the post-enqueue ping flush without touching the queue, remembering which of the two was running (or asked for while the pause held), and `resumeScheduledUploads()` puts back exactly that, plus a flush when anything was enqueued meanwhile. Explicit uploads (`forceUploadWithHoldWait`, `flushQueue`) still run while paused, which is how a group handoff drains the queue under a session it is about to release without a timer starting a batch that would land after the close and answer `bad_session`. `clearOnDisconnect` drops the pause with the timers, so a resume from a handoff that a disconnect superseded restarts nothing. `waitForUploadToFinish()` awaits an upload already on the wire (a `Completer` claimed with `_isUploading`) for at most 15 s: true when idle or once it lands, false at the bound. Both calls are idempotent; logged under `[API QUEUE]`. See Multi-region groups. - **Closed keep-alive sockets are replayed once**: every request `ApiService` makes goes through `_send`, which sends it again when the first attempt comes back `ClientException: Connection closed before full header was received`. The server closes an idle connection after 5 seconds while Dart's HttpClient keeps it pooled for 15, so a request made in that gap goes out on a socket that is already gone; a backgrounded app widens the gap further, because a frozen event loop cannot notice the close. Such a request never reaches the server (no access-log entry there), so replaying it changes nothing about what the server did. One replay only, and the per-attempt timeout stays at the call site so the replay gets a full allowance. Without it a single dead socket failed the whole connect on `/auth` and the user had to press Connect again. +### Update Required Panel + +The app never checks its own version: it sends `APP-` (store) or `APP-` (TestFlight) and the server refuses an old build at `/auth` with reason `outofdate`, comparing against the zone's `min_version` or `min_dev_version`. When that happens the Connection screen shows `UpdateRequiredPanel` (`lib/widgets/update_required_panel.dart`) instead of the error card: "Update MeshMapper to continue", one line of copy, the installed and required versions in small grey ("Your build: N" for TestFlight builds, which the server compares by build number; the required version is parsed from the server's "Required: v1.4.0" message and left off when it names none), an update button and Back. + +- **The button follows how the app was installed** (`StoreLinks.resolve` in `lib/utils/store_links.dart`, one unit test per row): iOS `com.apple.testflight` opens TestFlight (`itms-beta://`), any other iOS value the App Store listing; Android `com.android.vending` or `com.google.android.feedback` opens the Play listing (which also serves closed-test members), anything else (a sideloaded APK) opens MeshMapper_Project on GitHub: a store build (`APP-x.y.z`) its `/releases/latest`, and a beta build (`APP-`, `AppConstants.isDevelopmentBuild`) the releases page, where the newest pre-release is listed first. GitHub has no address for the newest pre-release, and `/releases/latest` skips them, which sent beta testers to the older stable build. +- **`installerStore`** comes from `package_info_plus`, read only when the server refuses the build (`AppStateProvider.installerStoreReader`, replaceable in tests because the real plugin call hangs under flutter_test), with a 2 s timeout; any failure falls back to the store listing. +- **`appUpdateRequirement`** is tied to the connection error text, so every path that clears or replaces the error drops the panel too. Logged under `[APP]` and `[UI]`. + ### Offline Mode `OfflineSessionService` enables wardriving when the API is unavailable (no network, maintenance mode, etc.). Data accumulates locally and can be uploaded later. @@ -604,30 +1198,39 @@ Three data flows (TX pings, RX observations, Discovery results) merge into unifi - **Storage**: SharedPreferences with key `offline_sessions` — JSON-encoded list of session objects - **Session Format**: Each session has a filename (`YYYY-MM-DD.json`), creation timestamp, ping count, device info, and the wardrive data payload - **Upload**: Sessions can be uploaded from Settings → Data when connectivity is restored +- **Export**: each session's download button writes its data payload as pretty JSON (`offlineSessionJson`, `lib/services/offline_session_export.dart`) to a temp file named after the session and opens the share sheet (`shareOfflineSession`); web downloads it instead. **Export all**, the last row of the Offline Sessions card (hidden when there are none), shares every session in one sheet, a file each with the same name and JSON (`shareAllOfflineSessions` through the pure `writeOfflineSessionExports`, which encodes off the UI isolate and suffixes a repeated name ` (2)` rather than overwrite it); web downloads each. The row shows a spinner and is disabled while the files are built and the sheet is open. Both pass the tapped row's rect as `sharePositionOrigin` (iPad). Exporting only reads: no session is deleted or marked uploaded, a dismissed sheet is not an error, and a failure shows `Error exporting: ...`. Logged under `[OFFLINE]`. - **Non-persistent**: Offline mode is never persisted — always off on app restart. Users must re-enable if needed. +- **When pings are written**: pings collect in memory (`ApiQueueService` offline buffer, cleared on every app launch) and reach the session file at these points: a 60 s auto-save that runs for as long as Offline Mode is on (it stops only when Offline Mode is turned off or the switch back to online succeeds, never on a save), a snapshot whenever the app is backgrounded, and a final save on mode stop, mode switch, user disconnect and the BLE-drop cleanup after a reconnect gives up. The noise floor session is stored on those same teardowns, so a teardown that skipped the final save left a drive in Session History with no offline file. The final save finalizes the file, so the next connect starts a new one. - **Maintenance integration**: When maintenance mode is detected while disconnected, the UI suggests using Offline Mode - **Airborne pause**: while the airborne latch is set, no fix is appended to the offline recording (`ApiQueueService.setOfflineRecordingPaused`); the session itself ends through the normal airborne block. See GPS & Zone Validation. - **File**: `lib/services/offline_session_service.dart` ### Background Service -Keeps BLE and GPS active when the app is backgrounded during auto-ping. +Keeps BLE and GPS active while the app is in the background: for the whole radio session on Android, per mode on iOS. -- **Android**: Foreground service via `flutter_background_service` with persistent low-importance notification (no sound/vibration). Notification shows live stats: `TX: N | RX: M | Queue: P` (Active/Hybrid) or `RX: M | Queue: P` (Passive). Foreground types: `location + connectedDevice`. -- **iOS**: Uses declared background modes (`bluetooth-central`, `location`). Users can enable "Background Location" in Settings to upgrade to "Always" location permission, which prevents iOS throttling during extended sessions. This must be manually enabled — a disclosure dialog explains the feature, then the system permission prompt appears. +- **Android**: the app's own `MeshMapperSessionService` (`android/app/src/main/kotlin/net/meshmapper/app/`, in `MainActivity`'s package), a foreground service of types `location + connectedDevice`. `BackgroundServiceManager` drives it over the `meshmapper/session_service` channel (`start`, `update`, `stop`, `status`; the handler is `SessionServiceChannel`, in the same Kotlin file). The `flutter_background_service` plugin's Android service and receivers are removed from the manifest, so the plugin never runs there. Because the service keeps the app's GPS stream running in the background, Android needs only "While in use" location: the manifest removes `ACCESS_BACKGROUND_LOCATION`, and the Background Location setting is iOS-only. + - **Runs for the whole radio session, not per mode.** It starts on screen at the Connect tap (`AppStateProvider._syncConnectionService`, on the notify that follows the tap's state change, with no `await` between them) and keeps running through reconnects, zone grace periods and mode switches. Its low-importance notification (no sound/vibration) reads `MeshMapper - Connected` between modes, the mode's stats while one runs (`TX: N | RX: M | Queue: P` for Active/Hybrid, `Trace: N | RX: M | Queue: P` for Trace, `RX: M | Queue: P` for Passive), `MeshMapper - Reconnecting`, or `MeshMapper - Outside zone` (`_serviceNotificationNow`, `lib/services/status/android_notification.dart`). On Android 13+ with notifications denied, Android drops the post. + - **A start needs the app on screen.** Android grants a foreground service while-in-use location only if the app is on screen when it starts, so `shouldStartConnectionService` (`lib/services/background_location_policy.dart`) requires the lifecycle to be resumed, a live session that is not disconnecting, and location permission granted with the disclosure agreed. `mayStart` is asked again right before the channel call. A start the service refuses (`startForeground` throws) is logged under `[BACKGROUND]` and not retried until the app is back on screen, where `healAfterResume` also reconciles the service with the session. `_checkStartStatus` asks the service 1.5 s after a start whether it came up, because the channel answers the start before the service tries `startForeground`. + - **It holds a wake lock only while a mode runs** (a partial lock, `MeshMapper:session`), including a reconnect or a zone grace period that has paused one that will resume (`_keepServiceAwake`), so their own timers (the reconnect's 30 s give-up, the grace period's 5 s polling) do not drift with the screen off. Between modes the service stays up without a wake lock. + - **It stops when the radio session is over**: at the end of the disconnect cleanup, after the queue upload and the session release, so the backgrounded process cannot freeze halfway through them (`shouldStopServiceAtCleanupEnd`; a cleanup followed by a reconnect or a connect re-run leaves it up). Also on a failed connect that nothing carries on, on swipe-away (`android:stopWithTask`), when `MainActivity` is destroyed (not for a configuration change), on Exit app, and at a cold start (`cleanupOrphanedService`). `_syncConnectionService` itself never stops it. There is no boot start, no watchdog and no restart: `onStartCommand` answers `START_NOT_STICKY`. + - **A stop sent before the service has promoted itself is deferred natively.** The channel answers `start` before `onStartCommand` runs, and stopping a service started with `startForegroundService` before it has called `startForeground` crashes the app. While a start is pending, `stop` only sets a flag, and the service stops itself right after `startForeground`. A `start` that arrives while one is pending clears the flag, and a `start` while the service is running only takes the new content. +- **iOS**: per mode, through the plugin, unchanged. `startService()` runs when a mode starts and `stopService()` when it stops, switches or the radio disconnects. Uses declared background modes (`bluetooth-central`, `location`). Users can enable "Background Location" in Settings to upgrade to "Always" location permission, which prevents iOS throttling during extended sessions. This must be manually enabled — a disclosure dialog explains the feature, then the system permission prompt appears. - **Web**: No-op (Web Bluetooth requires active tab) -- **Lifecycle**: Lazy-initialized on first `startService()` call (triggered by auto-ping start), stopped on disconnect or auto-ping stop -- **It MUST outlive the auto-reconnect window.** On Android the foreground service is the only thing holding the process alive, so `_startAutoReconnect` only re-titles it ("Reconnecting") and never stops it. Stopping it there froze the app within about three seconds and every Dart timer stalled with it, the 30 second reconnect timeout included: one user's reconnect gave up 18 to 21 minutes late, when they picked the phone back up, which is why the disconnect alert beeped on their return to the car instead of when the radio went out of range (the GPS stream, the 15 second batch timer and the reconnect timeout all resumed in the same millisecond). The service is stopped on the abandon path through `_fullDisconnectCleanup`, and by `_onReconnectSuccess` when there is no auto-ping to restore. A success that does restore auto-ping re-uses the running service, since `startService` folds into `updateNotification` when it is already up. +- **Lifecycle**: Android: as above; `initialize()` returns at once there, and the plugin's `configure()` never runs. iOS: lazy-initialized on the first `startService()` call (a mode starting), stopped on mode stop, mode switch and disconnect. +- **It MUST outlive the auto-reconnect window.** On Android the foreground service is the only thing holding the process alive, so `_startAutoReconnect` only re-titles it ("Reconnecting", with the wake lock kept if a mode was running) and never stops it. Stopping it there froze the app within about three seconds and every Dart timer stalled with it, the 30 second reconnect timeout included: one user's reconnect gave up 18 to 21 minutes late, when they picked the phone back up, which is why the disconnect alert beeped on their return to the car instead of when the radio went out of range (the GPS stream, the 15 second batch timer and the reconnect timeout all resumed in the same millisecond). The service is stopped on the abandon path through `_fullDisconnectCleanup`. `_onReconnectSuccess` leaves it running on Android, and the notification goes back to Connected or to the restored mode's stats. On iOS, where `_startAutoReconnect` also leaves the per-mode service running, `_onReconnectSuccess` stops it when there is no auto-ping to restore, and a success that does restore auto-ping re-uses it, since `startService` folds into `updateNotification` when it is already up. - **The disconnect alert is dated to its cause, not to when it plays.** `AppStateProvider._playDisconnectAlert(occurredAt)` refuses to beep once the event is older than `maxDisconnectAlertAge` (`lib/services/disconnect_alert_decision.dart`, 2 minutes) and writes an error-log entry naming the real delay instead. The reconnect abandon passes `_reconnectStartedAt` (the BLE drop); every other caller is event-driven and passes the current moment. This is the backstop for phones that freeze anyway, not the fix. `_logStuckTimers` also reports a reconnect window still open past twice its budget, under `[CONN]`. -- **Orphan cleanup**: `cleanupOrphanedService()` detects and stops stale foreground services from previous sessions -- **File**: `lib/services/background_service.dart` +- **A stop must not be overtaken by a start, or the reverse.** Android: every `stopService()` bumps a stop generation, even with nothing counted as running, and always sends the channel `stop`, since a start may still be on its way. A start that finds the generation moved when the channel answers does not count the service as running, because its stop is already queued natively (see the deferred stop above). If `_checkStartStatus` finds the service gone while the session still wants it, the provider marks the start failed and does not retry until the app is back on screen. iOS: `'stop'` is fire-and-forget (the plugin's isolate answers it with `stopSelf()` a few milliseconds later), so `initialize()`, finding a service left running after `configure()`, sends it and polls `isRunning()` every 100 ms, for at most 2 s, until it is gone (`waitUntilStopped`, logged under `[BACKGROUND]` with how long it took, a warning at the bound), so that late stop cannot take down the start that follows. A start waiting on `initialize()` abandons itself when a `stopService()` came in meanwhile. +- **Orphan cleanup**: `cleanupOrphanedService()` runs from a cold `main()`. Android stops the session service, since the notification of a foreground service can only be stopped, not cancelled, and one can outlive the engine that started it. iOS cancels the old notification (id 888) after initializing the local-notifications plugin, because `cancel()` is a silent no-op before that. +- **Files**: `lib/services/background_service.dart`, `android/app/src/main/kotlin/net/meshmapper/app/MeshMapperSessionService.kt` ### Noise Floor Measurement Continuous RSSI measurement of the idle channel, providing ambient noise data for coverage analysis. -- **Polling**: 5-second interval via `MeshCoreConnection.getNoiseFloor()` (MeshCore stats request for radio stats, parses int16LE). Retries up to 3 consecutive failures before stopping. +- **Polling**: 5-second interval via `MeshCoreConnection.getNoiseFloor()` (MeshCore stats request for radio stats, parses int16LE). After 3 consecutive failures it backs off to a 30-second interval instead of stopping, and returns to 5 seconds on the next success. On Android a write refused with `ERROR_GATT_WRITE_REQUEST_BUSY` (usually a second app talking to the same radio) is retried up to 3 times, 50 to 150 ms apart, in its place in the write queue (`writeRetryingGattBusy` in `lib/services/bluetooth/mobile_bluetooth.dart`). - **Sessions**: `NoiseFloorSession` (HiveType 13) records samples + ping event markers over time. Each sample has a timestamp and noise floor value (dBm). +- **Storage** (`lib/services/noise_floor_session_store.dart`, box `noise_floor_sessions`): History keeps the last 10 ended sessions. The running session is checkpointed into the same box under its own id every 3 minutes and when the app is paused (`NoiseFloorCheckpoint`; a write with no new sample or marker is skipped, since each write rewrites the whole session). A launch closes any session left without an `endTime` by a kill, at its last sample or marker (`loadStoredNoiseFloorSessions`), then trims to 10. The normal end overwrites the checkpoint, so a session is never counted twice. - **Event Markers**: `PingEventMarker` records ping events overlaid on the noise floor graph: - `txSuccess` (Green) — TX heard by repeater - `txFail` (Red) — TX not heard @@ -660,7 +1263,16 @@ Two-service system for capturing debug logs and submitting bug reports. - Writes timestamped log files (`meshmapper-debug-{unix_timestamp}.txt`) to app documents directory - Auto-rotation: max 10 files, max 4.5 MB per chunk (0.5 MB safety margin under 5 MB server limit) - 5-second flush timer (critical for iOS background suspension) -- Non-persistent: always starts disabled on app launch +- On by default. The stored preference (`user_preferences` box, `debug_logs_enabled`) is + read in `main.dart` before the first file is created; startup lines are held in memory + (`DebugFileLogger.beginCapture`, capped at 500) until then and land under the header, or + are dropped when the preference reads off. The provider's `_initDebugLogs` reconciles the + logger's real state with the preference rather than mirroring it, and deletes the stub + files an older build left behind (one per launch with logging off, matched by the exact + line that build wrote before closing). The file list is shown whether or not logging is on. +- A log is rotated exactly once per upload, at submit (`prepareDebugLogsForUpload`), never on + opening the Upload sheet or the Submit Feedback dialog (`listDebugLogFiles`); the current + file is listed and labelled, and a cancel leaves nothing behind. - Log format: `[ISO8601_timestamp] LEVEL: message` - Every file opens with a two-line header: the start time, then the app build, OS version and hardware model (`=== App APP-1.4.0 | iOS 18.5 | iPhone 15 Pro @@ -674,9 +1286,9 @@ Two-service system for capturing debug logs and submitting bug reports. **DebugSubmitService** — 4-step bug report workflow: 1. **Create Ticket** (0-20%): POST to `/debug/submitdebug.php/create-ticket` → returns `issue_number`, `issue_url` -2. **Request Upload** (per file, 20-90%): POST `/request-upload` → returns `upload_url`, `session_id` -3. **Upload File**: POST multipart to `upload_url` — splits large files at newline boundaries, uploads chunks sequentially with retry (3 attempts, exponential backoff) -4. **Complete Upload** (90-100%): POST `/upload-complete` with issue reference +2. **Request Upload** (per file, 20-90%): POST `/request-upload` → returns `upload_url`, `session_id`. A dropped connection or timeout is retried twice (1 s, 2 s backoff); a server refusal is not. +3. **Upload File**: POST multipart to `upload_url`. Splits large files at newline boundaries, uploads chunks sequentially with retry (3 attempts, exponential backoff). An HTTP 400 `Session Closed` after an earlier attempt lost its answer means the file most likely landed, so the upload goes on to step 4 and lets the server's hash check decide; if upload-complete then does not confirm, the upload is reported as failed. A `Session Closed` with no earlier lost answer fails at once, without the retries, since the closed session takes no more uploads. +4. **Complete Upload** (90-100%): POST `/upload-complete` with issue reference or user notes - **Accessible via**: Settings → About & Support - **Files**: `lib/services/debug_file_logger.dart`, `lib/services/debug_submit_service.dart` @@ -701,7 +1313,10 @@ Prevents session timeout during long wardriving sessions by periodically refresh - **Storm brake (429)**: a `rate_limited` answer from `/wardrive` carries `Retry-After` (75s by default) and keeps the session valid (server contract: `docs/APP_API.md` Appendix C item 9, "a 429 is not a sign-out"). `ApiService` parses it into one per-session hold, `wardriveBackoff`, that every sender on that door respects: `uploadBatch` returns `UploadResult.held` (no retry spent), `checkSessionValid` skips the post and reports the last known verdict so the ping itself proceeds, and the keepalive reschedules after the hold instead of going quiet. The brake re-arms its penalty on every blocked hit, so one lane knocking through it would keep all of them locked out. Without the keepalive reschedule, a braked session lapsed while the car was stopped (no ping or upload restarted the lane), the next post got a 401 and the app re-minted a fresh session id, which is exactly what the brake must not cause (VLC-20260903-0002). A new session id drops the hold. The hold honours `Retry-After` in full, up to the one hour ceiling `maxWardriveRetryAfter`: the server derives the value from its penalty and re-arms the lockout on every blocked hit, so a client that retries before the penalty has run is braked for the rest of the session, which is why the app never shortens it. The 429 path on the server answers before any session work and does not refresh `expires_at`, so a hold that outlasts the 300 s session TTL lets the session lapse, and the TX pings queued behind wire tags minted under it are dropped when the next `/auth` returns a new session id. The app cannot close that gap without knocking into the open window; it is a server matter (refresh the expiry on a 429, or keep the penalty under the TTL). In practice the brake only trips above 300 posts per 60 s from one session, so a healthy app never sees it. Tests: `test/services/api_service_rate_limit_test.dart`. - **Mechanism**: POST to `/wardrive-api.php/wardrive` with `heartbeat: true` flag and optional GPS coordinates - **Response**: Returns updated `expires_at`, which schedules the next heartbeat -- **Expiry recovery**: A live online companion treats only `session_expired` as recoverable. It serializes one replacement `/auth`, preserves the BLE connection and current auto mode, refreshes the region channels, validator, flood scope, capacity, Smart Pinging settings and path widths, then lets the recovered heartbeat lane own its next schedule. A recovered path policy applies the enforced regional width when present and otherwise restores the device firmware width, while retaining the user's trace-width preference. A recovery captures the exact connection and lifecycle generation, blocks new TX, and waits for an on-air TX window to finish its queued old wire tag before cleanup and session swap. Disconnect, zone transfer, Offline Mode, reconnect and disposal invalidate that ownership and wait for the recovery before releasing the current session. A superseded request is distinct from a failed recovery: stale preflights stop without a disconnect, stale heartbeats end quietly, and stale uploads stay held. If replacement configuration cannot be applied, the replacement session is explicitly released before the ordinary fatal path. Stale wire-tagged TX rows are removed before the new session ID is installed; untagged passive observations stay queued. Recovery is refused during disconnect, zone transfer, connection setup and Offline Mode. Other session and auth errors still follow the normal fatal-session path. +- **Expiry recovery**: A live online companion treats only `session_expired` as recoverable. It serializes one replacement `/auth` (a second caller joins the in-flight attempt; while a group handoff holds that slot every caller is instead answered `superseded` at once, `resolveSessionRecoveryJoin`, see Multi-region groups), preserves the BLE connection and current auto mode, and through `_mintAndApplyReplacementSession` (the back half a group handoff shares with it; a success + answer with no usable session id while ownership held is a failure, not a superseded request) + for `_sessionZoneCode`, the zone the session belongs to (else the current zone, so a recovery + that ran while a handoff was deferred behind it never mints in a member the session is not in) refreshes the region channels, validator, flood scope, capacity, Smart Pinging settings and path widths, then lets the recovered heartbeat lane own its next schedule. A recovered path policy applies the enforced regional width when present and otherwise restores the device firmware width, while retaining the user's trace-width preference. A recovery captures the exact connection and lifecycle generation, blocks new TX, and waits for an on-air TX window to finish its queued old wire tag before cleanup and session swap. Disconnect, zone transfer, Offline Mode, reconnect and disposal invalidate that ownership and wait for the recovery before releasing the current session. A superseded request is distinct from a failed recovery: stale preflights stop without a disconnect, stale heartbeats end quietly, and stale uploads stay held. If replacement configuration cannot be applied, the replacement session is explicitly released before the ordinary fatal path. Stale wire-tagged TX rows are removed before the new session ID is installed; untagged passive observations stay queued. Recovery is refused during disconnect, zone transfer, connection setup and Offline Mode. Other session and auth errors still follow the normal fatal-session path. A scheduled keepalive that comes back `session_expired` while the app is idle does NOT recover: no auto mode running, starting or stopping, no ping in flight, no Manage session open and nothing queued for upload (`sessionIsIdle` in `lib/services/idle_session.dart`, wired as `ApiService.isSessionIdle`). It stops the keepalive timers, leaves the lapsed session in place and logs under `[HEARTBEAT]`. This is the Android case where a stopped mode lets the backgrounded process freeze, the keepalive never fires, and the overdue one comes back expired on resume; recovering there minted a session that never saw a ping (empty sessions on the admin dashboard). The next Start or manual ping recovers it through `checkSessionValid`, which always posts its own heartbeat rather than trusting the stored expiry, and the heartbeat's enabled flag is kept so the recovered session reschedules its keepalive. The Manage sheet's `/repeater` actions (claim, unclaim, neighbour upload) run the same check first, since that door reports an expired session but never recovers one. A keepalive answer is only acted on while its session is still the current one: a failed answer for a session a manual action has since replaced is ignored, so it cannot cancel or retry the replacement's keepalive. The idle disconnect timer is untouched. Upload and preflight recovery are not gated, and a busy app recovers exactly as before. - **Bounding the recovery wait**: ownership is one predicate, `_ownsSessionRecovery(generation, connection, publicKey)`, re-read after every await: not disposed, still the current generation, not in Offline Mode, not connecting, reconnecting or transferring, still at `ConnectionStep.connected`, the same `MeshCoreConnection` instance and the same device public key. The teardown paths bump that generation (`_invalidateLiveSessionRecovery`) and then wait, but only for `sessionRecoveryWaitTimeout` (15 s, through `awaitSessionRecoveryBounded`), after which they carry on and log under `[SESSION]`. Giving up is safe precisely because of the ownership re-read: the recovery finishes on its own and finds it has been superseded. A recovery is two network legs (an `/auth` POST, then the channel and validator work it applies), and an unbounded wait held `disconnect()` and `_startAutoReconnect()` for as long as it liked with the UI already reading Disconnecting and the radio still up. `disconnect()` releases the sign gate and the repeater-admin slot (`abortPendingSign()`, `abortPendingAdmin()`) BEFORE that wait, not after it: a live sign holding the gate through all 15 seconds is exactly what aborting first exists to prevent. A superseded recovery releases the replacement session it already minted through `_releaseRecoveredSession` without being awaited, because that release is a second `/auth` POST that can sit for 30 s, nothing on this path depends on its answer, and the caller that superseded it is blocked on this recovery settling. A recovery that fails for its own reasons still awaits its release before returning `failed`. - **Flow**: Auth response sets initial `expires_at` → each wardrive POST or heartbeat updates it → timer reschedules automatically @@ -715,6 +1330,16 @@ Two-flag system ensuring users explicitly declare their antenna configuration be - **API integration**: `external_antenna` field included in every TX/RX/DISC API payload - **Persistence**: Stored per-device, restored on reconnect with same device, reset on reconnect failure +### Persistent Power Override + +User-selected TX power overrides are saved per device and restored automatically on reconnect. + +- **Storage**: Hive box key `device_power_overrides`, mapping a device name to `{powerLevel, txPower}` +- **Restore**: On reconnect, a saved override for the device replaces the power values from the device catalog +- **Reset**: "Reset to Auto" clears the saved override and restores the catalog values for the device model +- **Visual indicator**: `powerRestoredFromDevice` shows when power was restored from a saved override +- **Important**: This only changes what the app *reports* to the API. The app never sends TX power commands to the radio. + ### Wake Lock Service Keeps the screen on during auto-ping to prevent device sleep during wardriving sessions. @@ -830,10 +1455,11 @@ a connection.** Mobile only (`!kIsWeb`). Server contract: of its own 30s..8m ladder and the server's value. A 429 is never a sign-out: 401 + `token_invalid` stays the only signed-out signal. - **Account page overview**: `me` also answers `overview: {points, weekly, grid, - awards:[{name, description}]}`, the portal Overview tab's numbers, summed - server-side over each companion's primary so a grouped radio counts once. The - app never adds up the per-companion points itself. The block is absent on a - server that predates it; the app reads that as unknown (`PortalOverview` + awards:[{name, description}]}`, the portal Overview tab's numbers. Each + linked radio keeps its own points (`pubkeys[].points`); the overview is the + server's sum of them plus any credit tied to no radio, and grid squares are a + union, not a sum. The app never adds up the per-companion points itself. The + block is absent on a server that predates it; the app reads that as unknown (`PortalOverview` null) and hides the Overview card rather than show zeros. The Account page lists every linked companion from `portalCompanions` (name, else label, else "Companion"; the key; a points pill above zero), runs the throttled `refreshMe` @@ -885,7 +1511,10 @@ the app shows as "This region does not support claiming yet." once per BLE connection and cached on the `MeshCoreConnection`, and every later `getContacts` sends the firmware's `since` filter (the newest `lastmod` from the END_OF_CONTACTS frame) and merges what changed, so the 52 KB stream happens once, not per - login; a learned route bumps `lastmod` so it syncs, `resetPath` does not so the cached + login; the read times out on 5 s of silence (120 s overall), never a fixed total, because + a 350-contact list takes about 21 s and a fixed 20 s timeout cut it off on every try, and that + timeout reads "Your radio didn't finish sending its contact list", never the password + sentence; a learned route bumps `lastmod` so it syncs, `resetPath` does not so the cached record is patched, `addContact` inserts its record, and the cache dies with the connection object (auto-reconnect builds a new one); `ERR 3` there is "Your radio's contact list is full."). Step 2 logs in (`login`, `CMD_SEND_LOGIN` with the raw UTF-8 @@ -1033,6 +1662,18 @@ the app shows as "This region does not support claiming yet." `mains`, and `displayPreset` renders the tag as `910.525 MHz · 62.5 kHz · SF7`, falling back to the raw string when it is not three numeric slots. Covered by `test/models/repeater_site_details_test.dart`. +- **Scopes** (`Repeater.scopes`, `RepeaterScope` in `lib/models/repeater_scope.dart`): the + list's `scopes` array, one entry per scope name with when each source last confirmed it + (seen forwarding, reported to an observer, uploaded by a wardriver's app), plus the four + `default_scope*` fields read together. All optional: an older server sends none and the + row is left out. The detail sheet's Scopes row (`RepeaterScopeChips`, + `lib/widgets/repeater_scope_chips.dart`) shows one chip per scope, ordered by the pure + `repeaterScopeChips` (the default first with a gold star, then more sources, then name), + folded after 4 behind "+N more"; tapping a chip says where it came from. `*` means no + scope set and reads "Not set", never "all". A default state of `unknown` shows a starred + `?`. Ported from the web popup's chip strip so both answer alike. The web's "never + replied" row is left out: the list carries no probe counts. Display only, no + `mapRevision` bump. Covered by `test/models/repeater_scopes_test.dart`. - **The detail sheet's facts card scrolls inside a cap** (`_repeaterCardMaxHeightFraction`, 32% of screen height) so a fully populated repeater cannot grow the sheet past its normal opening height and scroll the close button away. Its ID chip is drawn by the map's own @@ -1057,8 +1698,8 @@ sat on. The constant body is dE 25.7 from the nearest coverage colour. (`<= 2` chars: 24, else `10 + len * 7`, plus 8 for the bar), and the label is centred in the space RIGHT of the bar, not in the whole box. A newly discovered repeater is taller (28 vs 24), with a larger label and a wider - glow. Corner radius still encodes hop-byte width (4 / 6 / 8), which is this - app's own signal and has no web counterpart. + glow. Corners use one radius for every id length and state + (`RepeaterMarkerStyle.chipCornerRadius`, 8 px; see Uniform Repeater Corners). - **Group marker**: a `#22303A` disc of radius 19 with the count across it, a 2.5 px ring at radius 17.75 in the DOMINANT state's colour, a 1 px hairline at 19.5, and one uniform 2.6 px dot per state PRESENT, pitch 4.2, centred at @@ -1184,8 +1825,10 @@ sat on. The constant body is dE 25.7 from the nearest coverage colour. ### Coverage Overlay (vector tiles) -The MeshMapper coverage layer is rendered from the region server's vector tiles -(`vector_tile.php`, z7–14, overzoom beyond) as a MapLibre source+layer pair. The app is +The MeshMapper coverage layer is rendered from the coverage host's vector tiles +(`vector_tile.php`, z2–14, overzoom beyond) as a MapLibre source+layer pair. The host is +`AppStateProvider.coverageHostCode`: the zone's own site, or the group's site when the zone +belongs to a multi-region group (see Multi-region groups). The app is vector-only — every region server must serve `vector_tile.php` (the legacy raster `tiles.php` overlay was removed from the app 2026-06). Contract reference: `MeshMapper_Server/docs/VECTOR_TILES.md`. @@ -1193,6 +1836,18 @@ vector-only — every region server must serve `vector_tile.php` (the legacy ras - **Styling is client-side**: each cell carries an integer status category `st`; colours come from `match` expressions built by `lib/utils/coverage_tile_palette.dart` (kept in sync with the server's `dev/cvd_palettes.php`, including all colour-vision palettes). +- **Tile format 2 (`cf=2`)**: every tile request (overlay, fresh refetch, Smart Pinging) + sends `cf=2` (`kCoverageTileFormat` in `lib/utils/mvt_cells.dart`), a promise that the app + handles a feature carrying `k` at any zoom. Such a feature is a BLOCK of k by k 300 m cells, + whatever gsize was asked for: its rectangle is the 300 m steps times k, and its i/j are block + indices (`CoverageCell.bounds`, never the raw grid steps). The server serves blocks at z2 to + z6 to every client and, to a `cf=2` client, at z7 to z9 too (Detailed's 100 m cells start at + z10). The app never assumes the zoom-to-k table; it reads `k` off each feature. The fill + paints from `st` alone, so blocks colour like cells. The session patch filter is + `coveragePatchBaseFilter`, "show if it has `k` OR its `i_j` is not patched", so a block whose + index happens to equal a patched cell's is never hidden. The patch extraction and Smart + Pinging skip blocks (their i/j are not cells of the fine grid; Smart Pinging fails open). + Only send a newer `cf` once every reader handles that format. - **Coverage Grid preference (`prefs.coverageGridSize`)**: Simplified (300 m, default) or Detailed (100 m + blob), mirroring the web's Grid Mode; baked into the tile URL. The grid is locked to the chosen preset at every zoom — cells never resize. @@ -1233,6 +1888,214 @@ vector-only — every region server must serve `vector_tile.php` (the legacy ras `lib/services/api_service.dart` (`freshenVectorTile`), `lib/utils/coverage_tile_palette.dart`, `lib/utils/mvt_cells.dart`. +### Multi-region groups + +A zone can belong to a multi-region group (Ottawa, Montreal and Quebec City as `ONQC`). The +`/status` in-zone answer carries `zone.group = {code, name, members}` for a grouped zone and no +key at all for a standalone one; `/auth` carries the same object, which the app does not need. +Contract: `MeshMapper_Server/docs/APP_API.md` (sections 2 and 3.1). The app parses it in exactly +one place, `parseZoneGroup` in `lib/utils/zone_group.dart`: a missing, null or non-map `group`, a +non-string code, or a code that is not `[A-Z0-9]+` after trim and upper-case all mean "no group", +so a server that never sends the key (production before the server change, and Offline Mode's +own auth) leaves the app behaving exactly as before. The name is trimmed (blank to null) and the +members trimmed and upper-cased. There is no setting: it is on whenever the server says the zone +is grouped. `AppStateProvider.zoneGroup` parses `_currentZone` on each read, and +`_noteZoneGroupChange` logs `[APP] Zone group: CODE (N members)` (or `none`) once per change, +after both `_currentZone = newZone` assignments in the `/status` handler. + +- **What follows the group.** Labels: `displayZoneCode` is the group code when there is one, + else the zone code, and `shortZoneCode` cuts it for the short labels (`shortZoneLabel`, + `kShortZoneLabelMax` = 4: anything longer becomes the first 4 characters and an ellipsis, so + `FINLAND` reads `FINL…`). The status bar, the map's GPS chip, the Connection screen chip, the + Live Activity, the watch snapshot and Siri's session snapshot all read `shortZoneCode` where + they read `zoneCode` before, the two external-surface preflight keys included (they dedupe the + displayed payload, so a group arriving on an unchanged member zone must still flush). + `displayZoneName` is the group's name when the server sent one, else the zone's. The compact + Regional Settings card adds a `Region` row with the full group code beside the member code + (`RegionalConfigCard.groupCode`), hidden in Offline Mode. Labels never bump `mapRevision` + (Rule 9). Coverage: `coverageHostCode` (group code, else zone code) is the subdomain the + coverage overlay's tile template, the post-wardrive `fresh=1` refetch (`_pendingFreshZone`), + both coverage taps (`fetchCellCoverage`, `fetchRepeaterCoveragePoints`; `app_coverage.php` is + never sent a `zone` in its body) and Smart Pinging's tiles (`_syncRecentCoverage` configures + `RecentCoverageService` with it) are read from, because the group's own site + (`.meshmapper.net`) merges every member. `MapWidget` keys the overlay on it + (`_lastOverlayHostCode`), so a move between two members of one group changes nothing on the + map, and leaving the group is an ordinary host change (session patch dropped, overlay rebuilt) + through the existing zone watcher. Repeaters are still FETCHED from the member's site + (`fetchRepeaters(iata)`; the member already answers for the whole group) and the borders from + the central `/border` endpoint, keyed on the phone's position (`_fetchBorderPolygons`), but + both are KEYED on `_repeaterContextKey`, which is `coverageHostCode`: + `_repeatersLoadedForIata`, `BorderLoader.loadedKey`, the in-flight fetch dedupe, + `_invalidateRepeatersForContext` and the scope lifecycle's "list still current" check all + compare the key, so a move inside the group neither clears nor refetches either list, and two + members racing a fetch collapse to one request. +- **Border loading** (`lib/services/border_loader.dart`). A group's `/border` answer can be + several MB, so `BorderLoader` gates every request made from the zone check: one at a time + (the guard holds until the request has really ended), one load per context and `border_hash`, + and after a failed, empty or misplaced answer a pause of 5, then 15, then 30 minutes (reset by + a new context, a new hash or a success). `ApiService.fetchBorderPolygons` sends an + `http.AbortableRequest` and aborts each attempt at 60 s, which closes the socket; a plain + Future `.timeout` would leave the body downloading in the background. An abort is never + replayed; the one `_send` replay (a reused connection closed before any header) gets its own + 60 s. `/border` is sent the fix `/status` placed the phone with (`_lastZoneCheckPosition`), + and an answer must contain the zone and, in a group, only members (`bordersFitZone`), else + it is dropped as a failure. A `/border` body carries its own `border_hash` only when every + polygon is real (see `MeshMapper_Server/docs/APP_API.md`); only such an answer is saved, + under that hash, to the `region_borders` lazy Hive box (polygons) plus the small + `region_borders_index` box (hash and save time, kept in memory), four contexts, compacted + after a replace or eviction, JSON work in `compute()`. The `/status` `zone.border_hash` only + decides whether the saved copy is current: a match is served without asking `/border`, also + across a zone transfer and a restart, and a known miss is not read again. An answer with no + body hash (degraded, or an older server) and the HTTP 503 `border_unavailable` are never + saved; the first is shown and loads once per context, the second backs off. Clearing the + borders for another context (or the context moving on mid-request) forgets the loaded + context, so returning to it loads it again. +- **What stays the member.** `zone.code` is still the session's identity everywhere the server + reads it: the `/auth` `iata`, `_sessionZoneCode`, every upload, the wire tags, the custom API + forward (`iataGetter`) and the offline `iataOverride`, `Repeater.iata` and the Siri repeater + entity key, and the host of every `fetchRepeaters` call. Only the labels and the coverage host + change. `_sessionGroupCode` (read-only `sessionGroupCode`) is stored beside `_sessionZoneCode` + at every site that sets it (connect, the switch to online, the visible transfer, the handoff) + and cleared with it. +- **The hidden handoff.** The server never moves a session between zones (below), so the app + still changes session at every border; inside a group the user does not see it. The `/status` + in-zone handler classifies a zone change under a live session with the pure + `classifyZoneMove(sessionZone, sessionGroup, newZone, newGroup)`: `none` (same zone, or no + session), `hiddenHandoff` (another member of the session's own group), `fullTransfer` + (anything else: a different group, or no group on either side). The outer gates are the old + ones (connected, not Offline Mode, not in zone grace, no transfer in progress), and zone-grace + re-entry keeps the visible transfer, grace being a visible state already. A `fullTransfer` + awaits `_handleZoneTransfer` exactly as before. A `hiddenHandoff` fires `_startGroupHandoff` + unawaited, or logs `[ZONE] Group handoff deferred` and returns when a session swap already + holds the recovery slot (a later tick still reads the old session zone, so it lands here again + and must not start a second swap; the running one owns the move). + + `_handOffWithinGroup`, in order: stop a scope runner (`ScopeStopEvent.zoneTransfer`, borrowed + routes kept), hold new TX (`PingService.setSessionRecoveryInProgress`, the recovery hold: a TX that comes + due bows out and re-arms a full interval as the backstop, and once the hold releases the + service pulls that very leg in to `heldTxReleaseDelay`, 1 s, Hybrid's alternation kept since + the TX leg that bowed out is the one that runs), pause the queue's scheduled uploads + (`ApiQueueService.pauseScheduledUploads`, see API Queue System), wait for an on-air TX window + to queue its old wire tag (`waitForTxWindow`), flush the RX buffer, drain the queue under the + old session (at most 5 rounds of `forceUploadWithHoldWait`, each first awaiting + `waitForUploadToFinish` since the queue silently skips a second upload, stopping when a round + does not shrink the queue), wait once more for any upload still on the wire (15 s, a `[ZONE]` + warning when the bound runs out), release the old session with + `disconnect_cause: zone_transfer` and `keepPolicy: true` (the id, wire key, counter, expiry, + storm-brake hold and keepalive timers go; `txAllowed`, `rxAllowed`, the channels and scopes and + the enforce, hop-width, Smart Pinging and scope-discovery terms stay for the mint to overwrite, + so the ping buttons, the status bar and the Smart Pinging lookup, whose `_syncRecentCoverage` + gate reads `hasApiSession || _groupHandoffOwnsRecoverySlot`, never show the two round trips as + "Passive only" with no session; a handoff that ends without a session forgets them in full + through `ApiService.clearSession`, and a release the server did not confirm is a `[ZONE]` + warning, since `requestAuth` answers null rather than throwing), run the session-replaced work + (`_onSessionReplaced`, the one body `onSessionIdChanged` runs: `dropStaleTaggedItems` for the + tagged TX the drain left behind, and `RecentCoverageService.clearDeferred` so the squares + reported under the old session are owed again under the new one, which the server credits per + session id; called explicitly, since the release nulls the held id and the connect that follows + has no previous id to fire the hook against), then `_mintAndApplyReplacementSession` with the + new member's code. The handoff has no Stage 2 register leg: a region group shares all + companions, so a radio registered in one member is registered in every member and + `unknown_device` cannot answer the mint. A Start or a manual ping (the Siri and watch lanes + included, which go through `toggleAutoPing` and `sendPing`) that lands in the release-to-mint + gap waits for the handoff in `_checkSessionBeforeAction` (bounded by + `sessionRecoveryWaitTimeout`; the pure `sessionCheckWaitsForHandoff`) before its session + check, since `checkSessionValid` answers `no_session` there; the handoff never reaches that + check while it holds the slot (the capacity remap runs after the slot clears), so the wait is + never on itself. Only after a successful apply do + `_sessionZoneCode` and `_sessionGroupCode` move, the keepalive is re-armed with + `enableHeartbeat` (the release cancelled its timers and a connect auth never schedules one), + the periodic scope repeater refresh is re-armed when Passive or Hybrid is running and the timer + is not, and `notifyListeners()` runs. The TX hold and the upload pause are released in a + `finally` on every path. Back in `_startGroupHandoff`, a `recovered` handoff into a member + with no TX capacity while Active or Hybrid runs is remapped the way the visible transfer's + restore is (`_remapAutoModeAfterHandoff` through `_resolveAutoModeForZone`, Passive when RX is + allowed, the shared cooldown cleared first), with a `[ZONE]` line and a warning in the error + log: the one case a hidden handoff changes what is on screen. A stop already pending + (`isPendingDisable`, a parked disable or the stop teardown) outranks the remap, which returns + with a `[ZONE]` line and leaves the mode to the stop, since the switch would force-disable the + mode and drop the parked disable (the external lanes' stillStopping rule). It never sets `_isZoneTransferInProgress`, never stops auto-ping, the + RX logger, the zone refresh timer or the idle disconnect timer, never clears the borders or the + repeater list, and never calls `clearOnDisconnect`: auto-ping keeps its schedule through the + swap, so Hybrid does not flip early or late at the border, and the cost is about a second of + TX hold: a TX due during it goes out about a second after the release, not an interval later. + + The handoff rides the expiry recovery's single in-flight slot (`_liveSessionRecoveryInFlight`, + the same `whenComplete` identity clear), so disconnect, auto-reconnect, the Offline Mode hot + switch, zone transfer and dispose already supersede it (the generation bump) and wait for it, + bounded by `sessionRecoveryWaitTimeout`. Ownership is `_ownsSessionRecovery` plus + `!_isInZoneGracePeriod`: zone grace keeps the session and disables the heartbeat without + bumping the generation, and its re-entry runs the visible transfer, so a handoff still running + then bows out. While the handoff holds the slot `_groupHandoffOwnsRecoverySlot` is set and + `_recoverExpiredLiveSession` answers every `session_expired` with `superseded` at once + (`resolveSessionRecoveryJoin` in `lib/services/session_recovery_join.dart`): the drain upload + is itself a lane that can ask, and handing it the handoff's own future made the two wait on + each other for good. The upload comes back held with no retry spent, the keepalive and the + preflight bow out, and the handoff mints the replacement itself. The results are the + recovery's: `recovered`, `superseded` (something else owns the cleanup; a session minted + meanwhile is released unawaited) or `failed`, which never leaves a minted session behind (an + apply failure releases it, awaited). Every exit past the keepPolicy release that ends without a + stored session forgets the kept zone policy (`ApiService.clearSession`), the superseded ones + included, since every superseding owner gates its own release on `hasSession`. On `failed` the + old session is gone and a connected online radio must not sit without one, so + `_startGroupHandoff` acts on the pure `groupHandoffFollowUp` (still connected, not Offline Mode, + not in grace): `transfer`, the visible `_handleZoneTransfer` to the zone the phone is in NOW + (the member the handoff was for, a third member a later tick moved it to, or the old member it + moved back into; the transfer just auths in its target), or `disconnect` when no zone is known, + the way a failed visible transfer ends. A + throw out of the handoff is caught there and treated as `failed`, since nothing awaits the + method. +- **A reconnect in the gap.** The connect workflow's step 6 POSTs `/auth` on every reconnect + (the server reuses a live session, else mints one in the current zone), so an online reconnect + lands with a session even when a handoff it superseded had already released the old one. + `_onReconnectSuccess` keeps a backstop for the one state that must never persist (connected, + online, no session): `_reacquireSessionAfterReconnect` mints through + `_mintAndApplyReplacementSession`, re-arms the session zone, the zone refresh timer and the + keepalive, all before auto-ping is restored; a reconnect that holds its session is unchanged. + How the backstop ends is the pure `reconnectBackstopOutcome` (`lib/utils/zone_group.dart`). + When it cannot get a session with the radio still connected (no zone to re-join, or a failed + mint) it ends through `disconnect()`, the path a failed visible transfer's auth takes: the + channel deleted while BLE is still up (Rule 8), the radio's name and path mode restored, the + transport closed. `_abandonAutoReconnect` assumes a dead link and does none of that, so taken + there it showed Disconnected with the radio still connected and the channel still on it. The + abandon's alert is kept (dated to the drop) and the reason goes to the error log + (`_abandonReconnectOnLiveLink`). After its mint the backstop also re-reads the transport + (`CompanionTransport.connectionStatus`), because the step does not change on a transport drop + and the BLE listener leaves a drop alone while `_isAutoReconnecting` is set, with the reconnect + timers already cancelled: a link lost during that POST hands back to `_startAutoReconnect` + with the auto-ping state captured at the original drop carried over + (`_restartAutoReconnectAfterBackstop`), whatever the mint answered, rather than restoring + auto-ping on a dead link; a session it minted is preserved by the reconnect as usual. A + superseding owner (disconnect, cancel, Offline Mode, dispose) is honoured whatever the link + did. On the API side a release only + forgets the session it released, so a stale release answer landing after a reconnect's connect + auth cannot null the new session. +- **Server side.** `/wardrive` (online only) no longer moves a session between regions. A + batch's zone is its newest item's; when it lands outside the session's own zone the server + stores the WHOLE batch under the session's own zone and answers 200 in three cases: in a zone + of the same enabled group at any distance, in another zone within 50 km of the session's zone, + or in no zone at all within 50 km. Farther away it answers 403 `outside_zone` with the session + kept (the app's zone grace path). `/status` always answers the true zone, so the transfer + trigger is unchanged. What the handoff relies on: the queue is drained under the old session + first (those batches stick to the old zone, which is what makes the drain lossless even though + the newest ping lies in the member just entered), and the old session is released BEFORE the + new `/auth` (a still-live old row would double count the driver against a full group). + `disconnect_cause: zone_transfer` rides every zone-move release, visible or hidden, is + whitelisted server-side and shows as "Zone transfer" under Session Endings. See + `MeshMapper_Server/docs/APP_API.md`: the Border crossings paragraph under the `/wardrive` + errors, the `outside_zone` row, and the `disconnect_cause` row in section 3.3. +- **Accepted residual**: a batch POSTed under the old session that lands at the server after + the release answers `bad_session`, the fatal path, the same window the visible transfer always + had; the paused timers and the awaited drain narrow it to a batch another lane put out during + the release POST itself. +- Logged under `[ZONE]` (the handoff), `[APP]` (the group), `[SESSION]` (the joiner rule), + `[API QUEUE]` (the pause and the in-flight wait) and `[MAP]` (the overlay host). Tests: + `test/utils/zone_group_test.dart` (parsing, the short label, the move classifier, the + follow-up rule), `test/services/session_recovery_join_test.dart`, + `test/services/api_queue_upload_pause_test.dart`, + `test/services/api_service_keep_policy_test.dart`, `test/services/ping_service_held_tx_test.dart`, + `test/widgets/regional_config_card_test.dart`. + ### Coverage Connection Lines (tap-to-inspect) Tapping coverage data draws connection lines from points the tap flow ALREADY @@ -1253,8 +2116,21 @@ fan-out logic (`MeshMapper_Server/dev/index.php`): Reuses the points fetched in `_showRepeaterDetails`. Port of `buildChartFromPoints` (`RepeaterStats.fromCoverageWithPoints`) + `drawRepeaterCoverageFromCache` (`repeaterCoverageCells`). -- **Volume cap**: both cap at the farthest 250 lines/cells (longest reach kept), - logged under `[COVERAGE]` when truncated. +- **Repeater Coverage Lines switch** (Settings > Map > Coverage Overlay, + `preferences.showRepeaterCoverageLines`, default off; the web's "Repeater + Coverage" layer `mm_std_repcov` defaults on): gates only Feature B's lines. + The cells, dim and framing always draw, in status colours (the web's + lines-off highlight blue is not copied). `_drawRepeaterCoverage` keeps the + lines in `_repeaterCoverageLines` (`RepeaterCoverageLines`, cleared with the + cells in `_clearCoverageCells` and on style reload), so a flip redraws or + clears the selected repeater's lines at once (web `mmRedrawSelectedCoverage` + parity). The setter does not bump `mapRevision`: MapWidget applies it from a + direct provider listener (`_onRepeaterCoverageLinesNotify`), which leaves the + shared lines layer alone while a tapped tile's fan-out (Feature A, not + covered by the switch) owns it (`repeaterCoverageLinesAfterSwitch`). +- **Volume cap**: the tile fan-out keeps the farthest 250 lines, a repeater the + farthest 5000 cells (longest reach kept), logged under `[COVERAGE]` when + truncated. - **Layers** (`map_widget.dart`): `coverage-lines-layer` (shared A/B, per-feature `color`) and `coverage-cells-layer` (per-feature fill) — install-once empty, updated via `setGeoJsonSource`, kept separate from the focus-mode lines so the @@ -1267,6 +2143,70 @@ fan-out logic (`MeshMapper_Server/dev/index.php`): `repeaterCoverageCells`, `RepeaterStats.fromCoverageWithPoints`), `lib/utils/coverage_tile_palette.dart` (`colorsForStatus`). +### TX Wire-Tag (Location Privacy) + +By default a TX ping does not broadcast GPS on the air. It sends a short keyed token, and the +coordinates travel only through the API. Anyone holding the community channel key can still +decrypt the channel message, but sees the token, not a location. + +- **On-air body** (the decrypted `#wardriving` message, composed once in `ping_service.dart` and + reused for both the transmit and the `TxTracker.startTracking(payload:)` echo match): + - **Default (privacy):** `MM:<10 base64url>` (for example `MM:YVNPAr5OIw`), the keyed wire tag. + 13 characters, two 16-byte AES blocks. + - **Broadcast My Coordinates** (Settings > Wardriving > Privacy, `preferences.broadcastCoords`, + default off): `MM::lat,lon`. The keyed tag is kept so cross-region spillover can still be + attributed by region, and the plaintext coordinates are appended. Only the on-air body carries + the suffix; the API still receives the bare `MM:` as `wire_tag`. With no session yet the + body is `MM:lat,lon`. + - **Server contract for the combined form:** observers report the full on-air body, so the + server strips the `:lat,lon` suffix (`wireTagBare` in `MeshMapper_Server/wire_tag_codec.php`) + before the coverage observer join and the spillover decode. Coverage gaps for the combined + form are fixed server-side, never by dropping the tag in the app. +- **Codec** (`lib/services/meshcore/wire_tag_codec.dart`): packs region (15 bits, base-26 of the + 3-letter IATA), date (15 bits, `(year-2020)*512 + month*32 + day`), session number (14 bits) and + counter (11 bits) into 55 bits, then runs a 4-round keyed Feistel over two 28-bit halves (round + function: first 4 bytes of `SHA-256(key || round || half)`), base64url without padding. The + date is encoded so `decode` rebuilds the full `region-YYYYMMDD-NNNN` session id and a recycled + daily session number cannot collide across days. 55 bits exceeds the JavaScript exact-integer + range, so the codec only ever works on the two halves with arithmetic (`*`, `~/`, `%`), never + bitwise operators, which dart2js truncates to 32 bits. It must stay byte-identical to PHP + `wireTagEncode`; canonical vectors live in `test/services/wire_tag_codec_test.dart` (key + `TESTKEY`, `PAR-20260611-0013` ping 1 = `MM:YVNPAr5OIw`). +- **Key** (`wire_key`): delivered by `/auth` and held in `ApiService`. With no key the app falls + back to an un-keyed tag (still coordinate-free). Never log the raw key; only its length. +- **Counter**: per session, incremented on each token-mode TX, untouched by the heartbeat. A fresh + `/auth` that reuses the session resumes from the response's `resume_counter`; a brand-new + session starts at 0. Resetting on a reused session would re-mint tags identical to earlier + pings, which the server's dedupe silently drops. The server is the counter's source of truth. + At the 11-bit cap (2047) the app flushes the queue under the still-valid session, then + disconnects through `handleSessionError('session_limit', ...)`. +- **API payload**: token-mode TX items add `ping_counter` and `wire_tag` (`ApiQueueItem` Hive + fields 16 and 17, sent only when set). Coordinate-mode items omit them and take the server's + coordinate path. +- **A tag never outlives the session that minted it, and such a ping is dropped.** The server + recomputes the tag from the session id a batch is posted under and skips a mismatched entry + while still answering success, so the ping would vanish with no error anywhere. Two paths could + carry a tag across a session boundary, and both drop the tagged item: + 1. **Offline preservation.** `extractAllAsJson()` (the pre-disconnect snapshot taken by + `handleSessionError`) leaves tagged TX pings out, because that snapshot is uploaded later + under a new `offline-YYYYMMDD-NNNN` session. Untagged RX, DISC and TRACE rows are kept. + 2. **A new session id under a kept queue.** `ApiService` fires `onSessionIdChanged` when `/auth` + returns a different id, and the provider runs `ApiQueueService.dropStaleTaggedItems()`. This + matters for auto-reconnect, which keeps the queue. Zone grace and zone transfer clear the + queue before re-auth, and a group handoff runs the same drop itself after its release (see + Multi-region groups). + Every item queued when the session changes was minted under the old session, so a blanket drop + is exact and needs no per-item bookkeeping. +- **Why drop rather than re-tag or strip.** Mismatches are rare (about 0.2% of TX pings). + Re-minting under the new session would claim a tag that never went out on the air, breaking the + observer join and spillover attribution. Stripping the tag sends the ping down the coordinate + path, where with no observer row left to join it inserts as DEAD and paints a grey cell for a + ping that was actually heard. A ping that cannot earn credit either way is better lost quietly. +- **`onSessionError` must be awaited.** Its handler snapshots the queue to offline storage while + the `uploadBatch` call site returns `nonRetryable` and discards that same batch. Fired without + `await`, the discard could land first and the preserved pings came back short. Every call site + in `api_service.dart` awaits it. + ### The One Session Status Model "What is the session doing right now?" is worked out in exactly one place, @@ -1357,7 +2297,7 @@ fresh fix there anyway. `canPing()` re-reads the connection step and the airborn that suspension but never the mode, which is why the mode needs its own check. The mode re-read is not enough on its own, because `forceDisableAutoPing` also clears -`_pingInProgress` (it has to: a force disable during a 7 second echo window would otherwise +`_pingInProgress` (it has to: a force disable during a 5 second echo window would otherwise leave the flag latched for the next session) and a zone transfer can re-auth and restart the session inside the old send's fetch. The resumed send then read the mode as on and went out alongside the new session's first ping. So each lane also captures `PingService._sendEpoch` @@ -1570,10 +2510,14 @@ future breaking change makes undecodable still reaches the "update the iPhone app" prompt instead of going silently stale. **One heard list.** The map's Top Heard box (`_topRepeatersOverlay`, the -latest ping's top three by SNR, plus the passive RX slot) is the single source +latest ping's rows by SNR, plus the passive RX slot) is the single source for the watch's heard rows (`ExternalSurfaceGeoBuilder.buildHeard`) and the Live Activity's rows (`buildLiveActivityHeard` in -`lib/services/live_activity/live_activity_heard.dart`). It is replaced only by a +`lib/services/live_activity/live_activity_heard.dart`). The stored list holds up +to `UserPreferences.topHeardRowsMax` (8) rows. The in-app box shows +`topHeardRows` of them (3 to 8, Settings > Map > Top Heard Rows), and the watch +and Live Activity take the first three (`_surfaceTopHeardRows`), which keeps the +watch's `maxHeard` cap from dropping the RX row. It is replaced only by a ping that heard something (direct TX echoes, discovery nodes, a successful trace at its window's close), so a silent ping leaves the last heard set in place on all three; the Live Activity marks rows from before the latest send as last @@ -1593,6 +2537,8 @@ carries the responder's full 64-character public key, and a trace carries its `_overlayIdentityById`, **replaced wholesale per ping and never merged**, because a hash that meant one repeater in a discovery response says nothing about who a later TX echo under the same hash was. +A user's own nickname for the resolved repeater wins over the server name; see +"Repeater Nicknames". TX echoes and passive RX carry only the path byte, so they fall back to prefix matching and keep refusing to guess. That fallback indexes per *distinct* @@ -1664,8 +2610,14 @@ Keep future targets separated by lifecycle: **One deadline, both sides.** `SiriIntentCoordinator` stops waiting after `SiriCommand.responseTimeout` (10 s, or 30 s for Connect) and tells the person -it failed. That same instant travels to Dart as `expiresAtMs`, so giving up is -one decision rather than two, and it is rechecked at three points: +it failed, capped at `SiriCommand.intentBudget` (25 s) from the moment +`perform()` created the command (`responseDeadline`). The cap exists because +iOS ends an App Intent on its own 30 seconds after `perform()` starts and shows +a generic failure ("an unknown error occurred" on iOS 26), discarding whatever +the intent returns afterwards; measured on device, iOS cut a Connect run at +30.01 s while our own 30 s timer, started later, never got to answer. That same +instant travels to Dart as `expiresAtMs`, so giving up is one decision rather +than two, and it is rechecked at three points: 1. Admission refuses an already-expired command outright. 2. `toggleAutoPing`/`sendPing` recheck after the awaited session check, before @@ -1715,7 +2667,7 @@ never be abandoned because a voice request timed out. A surface that sends no `expiresAtMs`, such as the watch, still falls back to the shared 30-second `maximumExternalCommandAge`. -**Connect's 30 seconds is a response deadline, not a cancellation guarantee.** +**Connect's deadline is a response deadline, not a cancellation guarantee.** This is the one mutation where the two differ, and the difference is deliberate. Up to the point of dialling, Connect behaves like the rest: @@ -1735,6 +2687,21 @@ guarantee. Such a reconnect is deliberately left connected: it transmits nothing on the mesh, starts no session, and is what the person asked for; tearing it down would only make them wait out another cold reconnect. +**Connect answers early and lets the dial run.** An unreachable radio runs three +15 second BLE attempts, which no deadline under iOS's 30 seconds can hold. So +`_connectToLastCompanion` waits for the dial only for +`lastCompanionAnswerWindow` (`last_companion_connection.dart`): 12 seconds +(`lastCompanionQuickAnswer`; a reachable radio connects in 4 to 7), shortened to +stay 3 seconds clear of `expiresAtMs` (`lastCompanionAnswerMargin`). A dial that +finishes inside it answers with its real outcome; one that does not answers +"MeshMapper is connecting to X. Check the app in a moment." (admitted, success) +and carries on. `_reconnectForSiri` never throws, because by then nothing may be +awaiting it. Logged under `[SIRI]`: every command's receipt, time left and answer +(`AppIntentBridgeService`), the dial's start, window, finish and whether it +finished after the intent was answered. The native side logs the channel wait, +the send, the answer and any timeout through `os.Logger` (category `Siri`), which +shows in the device syslog but not in the app's debug file. + Because of that, `SiriCommand.Kind.timeoutMessage` is per-kind, and the rule is that only a kind which really is cancelled may say so: @@ -1825,7 +2792,7 @@ when MeshMapper is disconnected. - Channel hash (PSK identifier) used for repeater echo detection and message decryption (AES-ECB via pointycastle) ### Packet Structure -- Custom binary protocol with header byte (0x11 = GROUP_TEXT, 0x21 = ADVERT) +- Custom binary protocol with header byte (0x15 = GROUP_TEXT, 0x11 = ADVERT, 0x26 = TRACE) - Path encoding: `pathLen` byte encodes hash size (top 2 bits) + hop count (bottom 6 bits), followed by `hopCount * hashSize` path bytes - `pathHashSize = (pathLen >> 6) + 1` → 1, 2, 3, or 4 bytes per hop - `pathHashCount = pathLen & 63` → 0-63 hops @@ -1852,14 +2819,13 @@ when MeshMapper is disconnected. ### Android - Requires permissions: Bluetooth, Location (for BLE scanning) - minSdkVersion: 24 (Flutter's `flutter.minSdkVersion` default; MapLibre GL needs 23+) -- Background location permission for continuous tracking - Uses `flutter_blue_plus` package - URL scheme `meshmapper-auth` (host `callback`) registered on MainActivity via a VIEW/DEFAULT/BROWSABLE intent-filter — the portal sign-in return. The bare `meshmapper://` scheme is deliberately NOT registered: it is a paste-only clipboard format (`docs/CUSTOM_API_ENDPOINT.md`). - `android:fullBackupContent` / `android:dataExtractionRules` exclude the `MeshMapperSecure` secure-prefs file from backup ### iOS -- Requires Info.plist entries: NSBluetoothAlwaysUsageDescription, NSLocationWhenInUseUsageDescription -- Deployment target: 13.0 +- Requires Info.plist entries: NSBluetoothAlwaysUsageDescription, NSLocationWhenInUseUsageDescription, NSLocationTemporaryUsageDescriptionDictionary (purpose key `CoverageMapping`, see Precise Location at Connect) +- Deployment target: 15.0 (the minimum Flutter 3.47.5 supports; iOS 13 and 14 devices cannot install the app) - Background modes: bluetooth-central, location - Uses `flutter_blue_plus` package - `CFBundleURLTypes` registers the `meshmapper-auth` scheme (name `net.meshmapper.app.auth`) for the portal sign-in return @@ -1876,7 +2842,6 @@ Key packages used in this project: - `provider`: State management - `http`: API requests - `pointycastle`: Encryption (AES-ECB, SHA-256) -- `usb_serial`: USB Serial communication on Android (USB OTG) - `app_links`: Custom-scheme deep links (`meshmapper-auth://callback`) for the portal sign-in return - `flutter_secure_storage`: Keychain / Android Keystore storage for the portal app token @@ -1974,6 +2939,7 @@ debugError('[API] Failed to post batch: $error'); | `[MODEL]` | Device model identification and power reporting | | `[MAP]` | Map widget operations | | `[DISC]` | Discovery ping operations | +| `[SCOPES]` | Scope discovery: the gate, the radio lease, the runner, the log entry | | `[MAINTENANCE]` | Maintenance mode handling | | `[RX FILTER]` | RX packet validation and carpeater filtering | | `[AUDIO]` | Audio/sound notification operations | @@ -1985,6 +2951,7 @@ debugError('[API] Failed to post batch: $error'); | `[SCAN]` | BLE device scanning | | `[WAKELOCK]` | Wake lock acquisition/release | | `[WATCH]` | WatchConnectivity bridge: availability, snapshot delivery, wrist commands | +| `[ZONE]` | Zone checks, the visible zone transfer and the hidden handoff between members of a region group | | `[LIVE ACTIVITY]` | ActivityKit bridge: sync, end, authorization failures, one line per publish and per held window | | `[ACCOUNT]` | MyMeshMapper portal sign-in and companion device linking | @@ -2107,7 +3074,29 @@ Offline Mode follows the same post-connect decisions without the auth step. - **POST /wardrive-api.php/auth**: Acquire/release session (geo-auth) - **POST /wardrive-api.php/devices**: Refresh supported devices or report an unknown identity (App key) - **POST /wardrive-api.php/wardrive**: Submit wardrive data + heartbeat -- Auth: API key in JSON body (`key` field), NOT query string +- Wardrive auth: API key in JSON body (`key` field), NOT query string +- **GET https://.meshmapper.net/get_repeaters.php**: Region or group repeater list. + Starting with app 1.4.1, every request sends the existing App key in `X-API-Key`, + including the first GPS zone check before connection. No portal login, session, + regional Coverage key or enforcement-switch query is involved. The URL, + `f_freq`/`f_bw`/`f_sf` filters, 15 second timeout and enabled-row parsing remain. + Non-200 and transport/response failures throw `RepeaterFetchException`; + 401/403 explicitly identify authentication failure. Failed reads hold that host + for 60 seconds, or the parsed `Retry-After` on 429 (75 second fallback, one hour + cap), independently of wardrive backoff. There is no anonymous fallback or + scheduled retry; later normal loads/refreshes can try again after the hold. + The provider preserves a loaded list on refresh failure only while its zone + and preset remain current, clears incompatible lists with a map notification, + and drops in-flight results after either context changes. Both loading paths + use the immutable `RepeaterListState` cache decisions, with all replacements + and notifications owned by `AppStateProvider`. Overlapping failed requests + retain the longest per-host backoff. Initial failures use + the existing tagged load-error logging and remain eligible for a later check. + Server header support and App-key quota isolation must be verified before + rollout (MeshMapper/MeshMapper_Server#431). Server support ships with repeater + enforcement OFF, followed by app 1.4.1 and authenticated integration checks. + The operator enables the separate repeater enforcement switch only after the + release and forced update. Other read API enforcement is independent. ### Maintenance Mode Response @@ -2127,18 +3116,18 @@ All API endpoints may return maintenance mode: 1. **Unified RX Handler accepts ALL packets** - No header filtering at entry point. Session log tracking filters headers internally. -2. **GPS freshness** - The client doesn't enforce GPS freshness for pings (25m movement check is sufficient), but zone status checks require GPS < 60s old and < 50m accuracy. The server also enforces fresh GPS on submitted wardrive data. +2. **GPS freshness** - The client doesn't enforce GPS freshness for pings (25m movement check is sufficient), but zone status checks require GPS < 60s old and < 50m accuracy. The app enforces the accuracy half itself: a zone check or connect `/auth` never sends a fix worse than 50 m (`GpsService.isAccurateForZoneCheck`). It uses the newest accurate fix under 60 s old (`bestRecentZoneCheckFix`), or waits briefly for one (4 s on connect), and before the first zone result it shows the Weak GPS Signal state instead of sending. A `gps_inaccurate` answer never overwrites a zone result already known. Fix age is left to the server on purpose, because a stationary phone gets no new fixes from the stream. The server also enforces fresh GPS on submitted wardrive data. 3. **Control locking during ping lifecycle** - `sendPing()` disables all controls until API post completes. Must call unlock in ALL code paths (success/error). 4. **Disconnect cleanup has 3 different flows**: - - **User disconnect**: Full cleanup — stop auto-ping → end noise floor session → stop background service → flush RX logger → clear API queue → release session (`/auth` with `reason: disconnect`) → delete wardriving channel (while BLE still connected) → close BLE → dispose all services → reset state - - **Unexpected BLE disconnect**: Partial cleanup — preserves API session, API queue, and noise floor session for reconnection. Stops timers and background service, disposes BLE-dependent objects, then starts auto-reconnect with exponential backoff (max 30s timeout). On reconnect success, restores auto-ping if it was active. - - **Reconnect failure / abandoned**: Falls back to full disconnect cleanup — flushes and clears API queue, releases session, resets antenna preference (user must re-select) + - **User disconnect**: Full cleanup — stop auto-ping → end noise floor session → stop the iOS per-mode background service → flush RX logger → clear API queue → release session (`/auth` with `reason: disconnect`) → delete wardriving channel (while BLE still connected) → close BLE → dispose all services → reset state; Android's session service stops last, after the queue upload and the session release + - **Unexpected BLE disconnect**: Partial cleanup: preserves API session, API queue, and noise floor session for reconnection. Stops timers, disposes BLE-dependent objects (Android's session service and iOS's per-mode service keep running, so the process stays alive through the reconnect window), then starts auto-reconnect with exponential backoff (max 30s timeout; a connect still in flight when it runs out gets one 15 s grace). On reconnect success, restores auto-ping if it was active. The provider disposes the `PingService` here without a force disable, so `PingService.dispose()` itself bumps the send epoch and clears the modes, and no parked send can re-arm a lane. Three drops in a row each within 30 s of a reconnect success give up (`ReconnectFlapGuard`, error-log entry naming the radio's power and battery). + - **Reconnect failure / abandoned**: Falls back to full disconnect cleanup: flushes and clears API queue, releases session, resets antenna preference (user must re-select). An abandon that catches a connect in flight bumps `_connectGeneration` and cancels the BLE connect, so the stale attempt touches nothing a newer connection owns: a disposed `MeshCoreConnection` writes no frame and leaves the transport alone when its workflow fails. The abandon disposes the stale attempt's connection at once, not at the end of the cleanup's awaits, and that attempt's auth callback answers `superseded` without calling the API (an answer already on its way is not stored as the app's session). A connect the user starts during the cleanup moves the generation, and the cleanup's end then disposes only the connection, ping service and transport it started with, leaving the new ones alone. `connectViaTcp` checks the generation as `connectToDevice` does: a superseded TCP attempt moves no step, shows no error card and closes only the socket it opened. A user Cancel plays no disconnect alert. Critical: Channel deletion MUST happen while BLE is still connected to avoid GATT errors. API queue is cleared on user disconnect (pings won't have valid session) but preserved during auto-reconnect. -5. **Platform-specific Bluetooth imports** - Use conditional exports (bluetooth_service.dart exports platform-specific implementation). Never import platform-specific files directly. +5. **Platform-specific Bluetooth classes** - `lib/main.dart` is the one place that picks `MobileBluetoothService` (`mobile_bluetooth.dart`) or `WebBluetoothService` (`web_bluetooth.dart`) by `kIsWeb`. Everywhere else depend on the abstract `BluetoothService` / `CompanionTransport` and never construct or import a platform class. 6. **Hive model generation required** - After modifying `@HiveType` classes, run `flutter pub run build_runner build --delete-conflicting-outputs`. @@ -2152,8 +3141,17 @@ All API endpoints may return maintenance mode: - `lib/screens/settings/` - Settings folder pages (General, Map, Wardriving, Data, MeshMapper Account, API Endpoints, About & Support, Developer Tools) plus the shared section card and auto-ping lock banner - `lib/services/meshcore/connection.dart` - 9-step connection workflow, MeshCore protocol - `lib/services/meshcore/unified_rx_handler.dart` - Packet routing (TX vs RX) -- `lib/services/meshcore/tx_tracker.dart` - Repeater echo detection (7s window) +- `lib/services/meshcore/tx_tracker.dart` - Repeater echo detection (5s window) - `lib/services/meshcore/disc_tracker.dart` - Discovery response tracking (7s window) +- `lib/services/meshcore/wire_tag_codec.dart` - TX wire-tag codec (keyed Feistel, byte-identical to PHP `wireTagEncode`) +- `lib/services/scope_discovery/scope_regions_codec.dart` - Repeater scope reply codec: builds the regions request, parses the byte-faithful reply, the server's token rule +- `lib/services/meshcore/scope_lease.dart` - The short radio lease a scope request borrows: admission, the write gate, the hold cap, the request/restore frames +- `lib/services/scope_discovery/scope_discovery_rules.dart` - The due rule, the phone-side answer cache (including the no-answer hold), the per-device-hour upload budget +- `lib/services/scope_discovery/scope_runner.dart` - One discovery sweep's scope runner: choosing repeaters, the answer wait, the hard stop, persistence +- `lib/services/scope_discovery/scope_lifecycle.dart` - The scope discovery gate and the provider's lifecycle wiring: stop events, borrowed-route bookkeeping, the repeater refresh discard, the periodic repeater refresh timer +- `lib/services/scope_discovery/scope_provider_support.dart` - Pure helpers behind the provider's scope discovery wiring: server info lookup, refresh staleness at connect/mode-start, the mode-start refresh plan +- `lib/models/scope_log_entry.dart` - `ScopeLogEntry` / `ScopeLogOutcome` and the scope log's own capped list store +- `lib/widgets/scope_discovery_firmware_note.dart` - The firmware-floor note shown under the Scope Discovery switch - `lib/services/meshcore/rx_logger.dart` - Passive observation logging - `lib/services/transport/companion_transport.dart` - Transport-agnostic interface for companion connections - `lib/services/transport/stream_frame_codec.dart` - TCP/USB Serial framing codec @@ -2168,9 +3166,13 @@ All API endpoints may return maintenance mode: - `lib/services/status/ping_control_labels.dart` - The in-app button labels and countdowns, read from the model's lanes - `lib/services/status/android_notification.dart` - Pure title/body for the Android foreground notification - `lib/services/gps_service.dart` - GPS tracking and geofencing +- `lib/services/fix_altitude.dart` - The rule that labels a fix's altitude with its reference (msl or ellipsoid) and accuracy, or unknown +- `lib/services/fix_altitude_resolver.dart` - Per-fix store of resolved altitude references, background Android read, source generation +- `lib/services/android_altitude_channel.dart` - Dart side of the `meshmapper/altitude` channel that describes the last Android fix - `lib/services/recent_coverage_service.dart` - Smart Pinging lookup: recently covered cells from filtered z13 tiles - `lib/services/airborne_release.dart` - Pure builder for the airborne session-end text and release telemetry - `lib/services/disconnect_alert_decision.dart` - Pure staleness rule for the disconnect alert, so a beep delayed by a suspended process is never played +- `lib/services/session_recovery_join.dart` - Pure rule for what a `session_expired` does while a recovery, or a group handoff, already holds the recovery slot - `lib/services/api_queue_service.dart` - Persistent upload queue - `lib/services/device_model_service.dart` - Device catalog cache, launch and connect-time refresh, unknown-device outbox - `lib/services/device_model_matcher.dart` - Shared identity sanitization, normalization and exact catalog match @@ -2212,9 +3214,16 @@ All API endpoints may return maintenance mode: - `lib/screens/watch_diagnostics_screen.dart` - Watch transport diagnostics (Settings) - `lib/services/meshcore/packet_validator.dart` - Packet validation and carpeater filtering - `lib/services/meshcore/regional_carpeater_filter.dart` - The region's shared CARpeater list: own-key exclusion, hop-prefix and full-key matching +- `lib/models/repeater_scope.dart` - A repeater's confirmed scopes and default from the repeater list, and the detail sheet's chip order +- `lib/widgets/repeater_scope_chips.dart` - The repeater detail sheet's Scopes chip row - `lib/utils/public_key.dart` - Full public key normalization (upper-case 64 hex) +- `lib/utils/zone_group.dart` - The zone's multi-region group: `parseZoneGroup`, the short label, the zone-move classifier and the handoff fallback rule - `lib/utils/repeater_marker_style.dart` - Repeater marker geometry, the five-state colour registry, and the cluster dominant/presence expressions - `lib/utils/cluster_spread.dart` - The zoom that pulls a repeater cluster apart, deciding zoom-vs-spread on tap - `lib/utils/repeater_marker_painter.dart` - Draws the repeater chip, the cluster badge disc and its presence dots +- `lib/utils/repeater_nicknames.dart` - Personal repeater nicknames: `RepeaterNicknames.sanitize`, the 8-character cap, and resolution of a heard row to its nickname +- `lib/widgets/repeater_nickname_dialog.dart` - The dialog that sets or removes a nickname, shared by the map sheet and Settings +- `lib/widgets/repeater_nickname_widgets.dart` - `RepeaterHexBadge`, `RepeaterNicknameTag` and `RepeaterNicknameButton`, the pieces the nickname UI is drawn from +- `lib/screens/settings/repeater_nicknames_page.dart` - Settings > Map > Repeater Nicknames: the list with add, edit, remove and Undo - `lib/models/noise_floor_session.dart` - Noise floor session data models - `lib/widgets/noise_floor_chart.dart` - Noise floor graph visualization diff --git a/analysis_options.yaml b/analysis_options.yaml index 3d54c641..11c51449 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -22,3 +22,7 @@ analyzer: # Vendored, patched copy of maplibre_gl (see pubspec.yaml dependency_overrides). # Analyze it under its own options, not ours. - third_party/** + - build/** + - android/** + - ios/** + - web/** diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 0d80a81f..0b1f4923 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -78,4 +78,14 @@ dependencies { // OfflineManager for the tile cache MethodChannel handlers. Version must // match maplibre_gl-0.27.1's OpenGL transitive dependency. implementation("org.maplibre.gl:android-sdk-opengl:13.5.0") + + // Fused location client, already pulled transitively by geolocator_android + // 4.6.2, but declared so MeshMapperAltitudeService.kt compiles against it. + // Version must match geolocator_android's transitive dependency. + implementation("com.google.android.gms:play-services-location:21.2.0") + + // AndroidX core, already pulled transitively (maplibre_gl's core-ktx), but + // declared so MeshMapperSessionService.kt compiles against ServiceCompat + // and NotificationCompat. Version must match the one Gradle resolves. + implementation("androidx.core:core:1.18.0") } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 8e0d5898..9b63dcb8 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -9,7 +9,10 @@ - + + @@ -21,6 +24,13 @@ + + @@ -29,8 +39,10 @@ - + + - + + + + + tools:node="remove" /> + + + + + + diff --git a/asc_store.py b/asc_store.py new file mode 100755 index 00000000..90a791b3 --- /dev/null +++ b/asc_store.py @@ -0,0 +1,1108 @@ +#!/usr/bin/env python3 +"""MeshMapper App Store Connect release manager. + +Gets an iOS release from an uploaded build to "Waiting for Review" through the +App Store Connect API, for MeshMapper (bundle id net.meshmapper.app): + + status read-only overview: versions, builds, What's New, screenshots + prepare create/reuse the App Store version, attach the build, release + after approval, no phased release, set What's New + screenshots replace the iPhone, iPad and Apple Watch screenshots + submit submit the prepared version for App Review + +Release text never lives in the repo: What's New comes from a notes file you +pass on the command line, screenshots from the folders the capture scripts +write (/ios-iphone-69, /ios-ipad-13, /watch-46). + +Auth: the same credentials upload_ios.sh uses. ASC_KEY_ID and ASC_ISSUER_ID in +the environment or ~/.meshmapper_release.env (environment wins), with the .p8 +at ~/.appstoreconnect/private_keys/AuthKey_.p8 unless ASC_KEY_PATH says +otherwise. ASC_APP_ID overrides the built-in app id. A fresh ES256 token is +minted (via openssl) for every request. + +Every write subcommand is a dry run by default: it prints what it would change +(current -> desired) and sends no writes. Pass --apply to write. Re-running +after an apply shows no changes. + +Usage: + ./asc_store.py status + ./asc_store.py prepare --version 1.4.1 --build 1777777777 --whats-new-file notes.txt + ./asc_store.py prepare --version 1.4.1 --build 1777777777 --whats-new-file notes.txt --apply + ./asc_store.py screenshots --dir shots/ # dry run + ./asc_store.py screenshots --dir shots/ --apply --replace + ./asc_store.py submit --version 1.4.1 # dry run + ./asc_store.py submit --version 1.4.1 --apply + +Python 3 standard library only. ASC_API_BASE overrides the API host (for +exercising the flow against a stub server). +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import os +import re +import struct +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +RELEASE_ENV = os.path.expanduser('~/.meshmapper_release.env') + +API_BASE = os.environ.get('ASC_API_BASE', 'https://api.appstoreconnect.apple.com') +BUNDLE_ID = os.environ.get('ASC_BUNDLE_ID', 'net.meshmapper.app') +DEFAULT_APP_ID = '6758073991' + +# The new version goes live when approved, not on a date or by hand. +RELEASE_TYPE = 'AFTER_APPROVAL' + +LIMITS = { + 'whats_new': 4000, +} + +# Characters App Store text must not carry: emoji and pictographs +# (U+1F000-U+1FAFF), miscellaneous symbols and dingbats (U+2600-U+27BF) and the +# emoji variation selector (U+FE0F). Accented letters are fine. +_FORBIDDEN_TEXT = re.compile('[\U0001F000-\U0001FAFF☀-➿️]') + +BUILD_POLL_SECONDS = 30 + +# Screenshot folders -> App Store Connect ScreenshotDisplayType. +# The API has no APP_IPHONE_69 / APP_IPAD_13 values: the 6.9" iPhone slot is +# APP_IPHONE_67 and the 13" iPad slot is APP_IPAD_PRO_3GEN_129. Accepted sizes +# per Apple's "Screenshot specifications" help page. +SCREENSHOT_SETS = { + 'ios-iphone-69': { + 'displayType': 'APP_IPHONE_67', + 'label': '6.9" iPhone', + 'sizes': {(1320, 2868), (2868, 1320), (1290, 2796), (2796, 1290), + (1260, 2736), (2736, 1260)}, + }, + 'ios-ipad-13': { + 'displayType': 'APP_IPAD_PRO_3GEN_129', + 'label': '13" iPad', + 'sizes': {(2064, 2752), (2752, 2064), (2048, 2732), (2732, 2048)}, + }, + 'watch-46': { + 'displayType': 'APP_WATCH_SERIES_10', + 'label': 'Apple Watch 46mm', + 'sizes': {(416, 496)}, + }, +} +MAX_SCREENSHOTS_PER_SET = 10 + +# App Store version states in which the version can still be edited +EDITABLE_VERSION_STATES = { + 'PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', + 'METADATA_REJECTED', 'INVALID_BINARY', +} +# A version becomes READY_FOR_REVIEW once it is an item of a review submission +# that has not been submitted yet (submit stopped halfway); submit resumes it. +READY_FOR_REVIEW = 'READY_FOR_REVIEW' +# States of a version that has already been sent to App Review (or is past it) +SUBMITTED_STATES = { + 'WAITING_FOR_REVIEW', 'IN_REVIEW', 'PENDING_DEVELOPER_RELEASE', + 'PROCESSING_FOR_DISTRIBUTION', 'READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', +} + + +class Fail(Exception): + """A user-facing error: printed without a traceback.""" + + +# --------------------------------------------------------------------------- +# Config +# --------------------------------------------------------------------------- + +def load_release_env(): + """Parse ~/.meshmapper_release.env (KEY=value, optional quotes, # comments). + Real environment variables take precedence.""" + values = {} + if os.path.isfile(RELEASE_ENV): + with open(RELEASE_ENV, encoding='utf-8') as fh: + for raw in fh: + line = raw.strip() + if not line or line.startswith('#'): + continue + if line.startswith('export '): + line = line[len('export '):].strip() + if '=' not in line: + continue + key, _, value = line.partition('=') + key = key.strip() + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'': + value = value[1:-1] + elif ' #' in value: + value = value.split(' #', 1)[0].rstrip() + values[key] = value + for key in list(values): + if os.environ.get(key): + values[key] = os.environ[key] + for key, value in os.environ.items(): + if key.startswith('ASC_') and value: + values[key] = value + return values + + +ENV = load_release_env() + + +def env(key, default=''): + return ENV.get(key, default) or default + + +def check_store_text(key: str, text: str) -> None: + """Refuse text App Store Connect would reject or that we do not want there: + empty, over the limit for `key`, or carrying emoji / symbol characters.""" + if text is None or not text.strip(): + raise Fail('%s is empty.' % key) + limit = LIMITS[key] + if len(text) > limit: + raise Fail('%s is %d characters; App Store Connect allows %d.' % (key, len(text), limit)) + bad = _FORBIDDEN_TEXT.search(text) + if bad: + raise Fail('%s has a character App Store text must not carry: U+%04X at position %d ' + '(no emoji or symbols; accented letters are fine).' % ( + key, ord(bad.group()), bad.start() + 1)) + + +def check_locales(locales: list[str]) -> None: + """This script only writes English text. Stop at the first other locale + rather than leave it with stale or untranslated text.""" + for locale in locales: + if not locale.startswith('en'): + raise Fail('Localization %s is not English. This script only writes English ' + 'text; handle that locale in App Store Connect first.' % locale) + + +def read_notes(path): + if not os.path.isfile(path): + raise Fail('Notes file not found: %s' % path) + with open(path, encoding='utf-8') as fh: + return fh.read().strip() + + +# --------------------------------------------------------------------------- +# App Store Connect API +# --------------------------------------------------------------------------- + +def _b64(raw): + return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii') + + +def _der_to_raw(der): + """openssl emits ECDSA signatures as DER (SEQUENCE of two INTEGERs); JWS + ES256 wants the raw r||s pair, each padded to 32 bytes.""" + if not der or der[0] != 0x30: + raise Fail('Unexpected signature encoding from openssl.') + idx = 1 + length_byte = der[idx] + idx += 1 + if length_byte & 0x80: + idx += length_byte & 0x7F + parts = [] + for _ in range(2): + if der[idx] != 0x02: + raise Fail('Unexpected signature encoding from openssl.') + idx += 1 + int_len = der[idx] + idx += 1 + parts.append(int.from_bytes(der[idx:idx + int_len], 'big')) + idx += int_len + return parts[0].to_bytes(32, 'big') + parts[1].to_bytes(32, 'big') + + +def mint_jwt(): + """Fresh ES256 token per request (ASC caps token lifetime at 20 minutes).""" + key_id = env('ASC_KEY_ID') + issuer_id = env('ASC_ISSUER_ID') + if not key_id or not issuer_id: + raise Fail('ASC_KEY_ID and ASC_ISSUER_ID must be set (env or %s).' % RELEASE_ENV) + key_path = os.path.expanduser(env('ASC_KEY_PATH') or + '~/.appstoreconnect/private_keys/AuthKey_%s.p8' % key_id) + if not os.path.isfile(key_path): + raise Fail('API key file not found: %s' % key_path) + + def compact(obj): + return json.dumps(obj, separators=(',', ':')).encode('utf-8') + + now = int(time.time()) + header = {'alg': 'ES256', 'kid': key_id, 'typ': 'JWT'} + payload = {'iss': issuer_id, 'iat': now, 'exp': now + 900, 'aud': 'appstoreconnect-v1'} + signing_input = (_b64(compact(header)) + '.' + _b64(compact(payload))).encode('ascii') + result = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', key_path], + input=signing_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if result.returncode != 0: + raise Fail('openssl could not sign with the API key:\n' + + result.stderr.decode('utf-8', 'replace')) + return signing_input.decode('ascii') + '.' + _b64(_der_to_raw(result.stdout)) + + +class APIError(Fail): + def __init__(self, method, path, status, body): + self.status = status + self.body = body + self.errors = [] + if isinstance(body, dict): + self.errors = body.get('errors') or [] + lines = ['%s %s failed (HTTP %s).' % (method, path.split('?')[0], status)] + if self.errors: + for err in self.errors: + line = ' [%s] %s: %s' % (err.get('status', status), err.get('code', ''), + err.get('title', '')) + if err.get('detail'): + line += ' - ' + err['detail'] + pointer = (err.get('source') or {}).get('pointer') + if pointer: + line += ' (%s)' % pointer + lines.append(line) + elif body: + lines.append(' ' + str(body)[:500]) + Fail.__init__(self, '\n'.join(lines)) + + +def api(method, path, body=None, params=None, ok=(200, 201, 204)): + url = path if path.startswith('http') else API_BASE + path + if params: + url += ('&' if '?' in url else '?') + urllib.parse.urlencode(params, safe='[],') + data = json.dumps(body).encode('utf-8') if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header('Authorization', 'Bearer ' + mint_jwt()) + if data is not None: + req.add_header('Content-Type', 'application/json') + try: + with urllib.request.urlopen(req, timeout=60) as resp: + status = resp.status + raw = resp.read() + except urllib.error.HTTPError as exc: + status = exc.code + raw = exc.read() + except urllib.error.URLError as exc: + raise Fail('Could not reach App Store Connect: %s' % exc.reason) + parsed = None + if raw: + try: + parsed = json.loads(raw.decode('utf-8')) + except ValueError: + parsed = raw.decode('utf-8', 'replace') + if status not in ok: + raise APIError(method, path, status, parsed) + return parsed + + +def get(path, params=None): + return api('GET', path, params=params) + + +def get_optional(path, params=None): + """GET a to-one relationship; None when ASC answers 404 or data: null.""" + try: + res = get(path, params) + except APIError as exc: + if exc.status == 404: + return None + raise + return (res or {}).get('data') + + +def get_all(path, params=None): + params = dict(params or {}) + params.setdefault('limit', '200') + res = get(path, params) + items = list(res.get('data') or []) + included = list(res.get('included') or []) + nxt = (res.get('links') or {}).get('next') + while nxt: + res = get(nxt) + items.extend(res.get('data') or []) + included.extend(res.get('included') or []) + nxt = (res.get('links') or {}).get('next') + return items, included + + +def patch(type_, id_, attributes=None, relationships=None): + data = {'type': type_, 'id': id_} + if attributes: + data['attributes'] = attributes + if relationships: + data['relationships'] = relationships + return api('PATCH', '/v1/%s/%s' % (type_, id_), {'data': data}) + + +def create(type_, attributes=None, relationships=None): + data = {'type': type_} + if attributes: + data['attributes'] = attributes + if relationships: + data['relationships'] = relationships + return api('POST', '/v1/' + type_, {'data': data})['data'] + + +def rel(type_, id_): + return {'data': {'type': type_, 'id': id_}} + + +# --------------------------------------------------------------------------- +# Lookups +# --------------------------------------------------------------------------- + +def app_id(): + return env('ASC_APP_ID', DEFAULT_APP_ID) + + +def version_state(version): + attrs = version['attributes'] + return attrs.get('appVersionState') or attrs.get('appStoreState') or 'UNKNOWN' + + +def state_label(version): + """The version state, plus the older appStoreState name when it differs + (READY_FOR_DISTRIBUTION is READY_FOR_SALE there).""" + attrs = version['attributes'] + old = attrs.get('appStoreState') + state = version_state(version) + return state if not old or old == state else '%s / %s' % (state, old) + + +def ios_versions(app): + versions, _ = get_all('/v1/apps/%s/appStoreVersions' % app, {'filter[platform]': 'IOS'}) + return versions + + +def editable_version(versions): + for version in versions: + attrs = version['attributes'] + if (attrs.get('appVersionState') in EDITABLE_VERSION_STATES or + attrs.get('appStoreState') in EDITABLE_VERSION_STATES): + return version + return None + + +def newest_version(versions): + return max(versions, key=lambda v: v['attributes'].get('createdDate') or '', default=None) + + +def choose_version(versions: list[dict], version_string: str) -> tuple[str, dict | None]: + """('create', None) when no version is editable, ('reuse', v) when the + editable one already carries version_string. Another editable version is an + error: App Store Connect allows only one, so it needs a decision first.""" + editable = editable_version(versions) + if editable is None: + return 'create', None + have = editable['attributes'].get('versionString') + if have == version_string: + return 'reuse', editable + raise Fail('The editable App Store version is %s (%s), not %s. Edit or delete it in App ' + 'Store Connect, or pass --version %s.' % (have, version_state(editable), + version_string, have)) + + +def already_submitted(version: dict) -> bool: + attrs = version['attributes'] + return (attrs.get('appVersionState') in SUBMITTED_STATES or + attrs.get('appStoreState') in SUBMITTED_STATES) + + +def in_unsubmitted_submission(version: dict) -> bool: + attrs = version['attributes'] + return READY_FOR_REVIEW in (attrs.get('appVersionState'), attrs.get('appStoreState')) + + +def version_localizations(version): + locs, _ = get_all('/v1/appStoreVersions/%s/appStoreVersionLocalizations' % version['id']) + return locs + + +def locale_of(loc): + return loc['attributes'].get('locale') or '?' + + +class BuildNotFound(Fail): + pass + + +def find_build(app, number): + res = get('/v1/builds', {'filter[app]': app, 'filter[version]': str(number), + 'sort': '-uploadedDate', 'limit': '1'}) + if not res.get('data'): + raise BuildNotFound('Build %s not found in App Store Connect.' % number) + return res['data'][0] + + +def wait_for_build(app, number, wait): + """Poll until the build is VALID. Right after an upload ASC does not list the + build at all for a while, then shows it PROCESSING.""" + deadline = time.time() + wait + while True: + try: + build = find_build(app, number) + state = build['attributes'].get('processingState') or 'UNKNOWN' + except BuildNotFound: + build, state = None, 'NOT_LISTED_YET' + if build and state == 'VALID': + if build['attributes'].get('expired'): + raise Fail('Build %s has expired.' % number) + return build + if state in ('FAILED', 'INVALID'): + raise Fail('Build %s is %s; App Store Connect will not accept it.' % (number, state)) + if time.time() + BUILD_POLL_SECONDS > deadline: + raise Fail('Build %s is still %s after waiting %d s. Re-run later or raise --wait.' + % (number, state, wait)) + print(' build %s is %s; checking again in %d s' % (number, state, BUILD_POLL_SECONDS)) + time.sleep(BUILD_POLL_SECONDS) + + +# --------------------------------------------------------------------------- +# Diff plumbing +# --------------------------------------------------------------------------- + +def show(value): + if value is None or value == '': + return '(empty)' + if isinstance(value, bool): + return 'true' if value else 'false' + if not isinstance(value, str): + return json.dumps(value) + flat = value.replace('\n', '\\n') + if len(flat) > 70: + return "'%s...' (%d chars)" % (flat[:67], len(value)) + return "'%s'" % flat + + +class Plan(object): + """Collects pending writes. In dry-run they are only printed.""" + + def __init__(self, apply): + self.apply = apply + self.count = 0 + + def section(self, title): + print('') + print('== ' + title) + + def same(self, label, value): + print(' = %-28s %s' % (label, show(value))) + + def change(self, label, current, desired): + self.count += 1 + print(' ~ %-28s %s -> %s' % (label, show(current), show(desired))) + + def info(self, text): + print(' ' + text) + + def note(self, text): + print(' ! ' + text) + + def diff_attrs(self, current_attrs, desired, labels=None): + """Print each desired attribute; return the subset that differs.""" + changed = {} + for key, value in desired.items(): + if value is None: + continue + cur = (current_attrs or {}).get(key) + label = (labels or {}).get(key, key) + if cur == value: + self.same(label, cur) + else: + self.change(label, cur, value) + changed[key] = value + return changed + + def finish(self): + print('') + if self.count == 0: + print('No changes.') + elif self.apply: + print('%d change(s) applied.' % self.count) + else: + print('%d change(s) pending. DRY RUN - nothing was sent. Re-run with --apply to write.' + % self.count) + + +# --------------------------------------------------------------------------- +# status +# --------------------------------------------------------------------------- + +def field_line(label, value, limit=None): + if value is None or value == '': + print(' %-26s EMPTY' % label) + else: + extra = '' + if isinstance(value, str) and limit: + extra = ' [%d/%d]' % (len(value), limit) + print(' %-26s %s%s' % (label, show(value), extra)) + + +def screenshot_sets(loc): + sets, _ = get_all('/v1/appStoreVersionLocalizations/%s/appScreenshotSets' % loc['id']) + return sets + + +def shot_state(shot): + return ((shot['attributes'].get('assetDeliveryState') or {}).get('state')) or 'UNKNOWN' + + +def cmd_status(args): + app = app_id() + a = get('/v1/apps/%s' % app)['data']['attributes'] + print('') + print('== App %s' % app) + print(' %-26s %s' % ('name', a.get('name'))) + print(' %-26s %s' % ('bundleId', a.get('bundleId'))) + print(' %-26s %s' % ('primaryLocale', a.get('primaryLocale'))) + + versions = ios_versions(app) + print('') + print('== App Store versions (iOS)') + if not versions: + print(' none') + for v in versions: + print(' %s %-10s %s' % (v['id'], v['attributes'].get('versionString'), state_label(v))) + + version = editable_version(versions) + print('') + if version: + print('== Editable version %s (%s)' % (version['attributes'].get('versionString'), + state_label(version))) + else: + version = newest_version(versions) + print('No editable App Store version (./asc_store.py prepare creates the next one).') + if version: + print('== Newest version %s (%s), read-only' % (version['attributes'].get('versionString'), + state_label(version))) + if version: + va = version['attributes'] + field_line('releaseType', va.get('releaseType')) + build = get_optional('/v1/appStoreVersions/%s/build' % version['id']) + field_line('build', build and build['attributes'].get('version')) + phased = get_optional('/v1/appStoreVersions/%s/appStoreVersionPhasedRelease' % version['id']) + print(' %-26s %s' % ('phased release', phased['attributes'].get('phasedReleaseState') + if phased else 'none')) + locs = version_localizations(version) + print(' localizations: %s' % (', '.join(sorted(locale_of(l) for l in locs)) or 'none')) + for loc in locs: + field_line(locale_of(loc) + ' whatsNew', loc['attributes'].get('whatsNew'), + LIMITS['whats_new']) + sets = screenshot_sets(loc) + print(' %s screenshot sets:' % locale_of(loc)) + for s in sets: + shots, _ = get_all('/v1/appScreenshotSets/%s/appScreenshots' % s['id']) + states = {} + for shot in shots: + states[shot_state(shot)] = states.get(shot_state(shot), 0) + 1 + print(' %-24s %d screenshot(s) %s' % ( + s['attributes'].get('screenshotDisplayType'), len(shots), + ' '.join('%s=%d' % kv for kv in sorted(states.items())))) + for folder, spec in SCREENSHOT_SETS.items(): + if not any(s['attributes'].get('screenshotDisplayType') == spec['displayType'] + for s in sets): + print(' %-24s MISSING (%s, from %s/)' % ( + spec['displayType'], spec['label'], folder)) + detail = get_optional('/v1/appStoreVersions/%s/appStoreReviewDetail' % version['id']) + print(' App Review detail:') + da = detail['attributes'] if detail else {} + for key in ('contactFirstName', 'contactLastName', 'contactEmail', 'contactPhone', + 'demoAccountRequired'): + field_line(' ' + key, da.get(key)) + + builds, included = get_all('/v1/builds', { + 'filter[app]': app, 'sort': '-uploadedDate', 'limit': '5', + 'include': 'preReleaseVersion'}) + builds = builds[:5] + prv = {i['id']: i for i in included if i['type'] == 'preReleaseVersions'} + print('') + print('== Latest builds') + for b in builds: + ba = b['attributes'] + rel_p = ((b.get('relationships') or {}).get('preReleaseVersion') or {}).get('data') or {} + pv = prv.get(rel_p.get('id'), {}).get('attributes', {}) + print(' %s (%s) uploaded %s processing=%s encryption=%s%s' % ( + ba.get('version'), pv.get('version', '?'), (ba.get('uploadedDate') or '')[:10], + ba.get('processingState'), show(ba.get('usesNonExemptEncryption')), + ' EXPIRED' if ba.get('expired') else '')) + + subs, _ = get_all('/v1/reviewSubmissions', {'filter[app]': app, 'filter[platform]': 'IOS'}) + subs.sort(key=lambda s: s['attributes'].get('submittedDate') or '9999', reverse=True) + print('') + print('== Review submissions (iOS, newest first)') + if not subs: + print(' none') + for s in subs[:5]: + print(' %s %-18s submitted %s' % ( + s['id'], s['attributes'].get('state'), + (s['attributes'].get('submittedDate') or 'never')[:10])) + + print('') + print('Not managed here (App Store Connect web UI): listing text, App Privacy "nutrition') + print('labels" (no public API), pricing and availability.') + + +# --------------------------------------------------------------------------- +# prepare +# --------------------------------------------------------------------------- + +def cmd_prepare(args): + # Read and validate everything first; the writes below then run in order. + text = read_notes(args.whats_new_file) + check_store_text('whats_new', text) + plan = Plan(args.apply) + app = app_id() + versions = ios_versions(app) + + action, version = choose_version(versions, args.version) + if action == 'create': + clash = [v for v in versions if v['attributes'].get('versionString') == args.version] + if clash: + raise Fail('Version %s already exists (%s) and cannot be edited.' % ( + args.version, version_state(clash[0]))) + # A new version starts with the previous version's localizations. + previous = newest_version(versions) + if previous: + check_locales([locale_of(l) for l in version_localizations(previous)]) + locs = None + else: + locs = version_localizations(version) + check_locales([locale_of(l) for l in locs]) + + plan.section('Build %s' % args.build) + build = wait_for_build(app, args.build, args.wait) + ba = build['attributes'] + plan.info('processingState=%s uploaded=%s' % (ba.get('processingState'), + (ba.get('uploadedDate') or '')[:19])) + + # 1. the version + plan.section('App Store version %s' % args.version) + if action == 'create': + plan.change('app store version', None, 'create %s' % args.version) + plan.info('releaseType %s is set when it is created' % RELEASE_TYPE) + if plan.apply: + version = create('appStoreVersions', + {'platform': 'IOS', 'versionString': args.version, + 'releaseType': RELEASE_TYPE}, + {'app': rel('apps', app)}) + locs = version_localizations(version) + check_locales([locale_of(l) for l in locs]) + if not locs: + raise Fail('The new version has no localizations; add one in App Store Connect.') + else: + plan.same('app store version', '%s (%s)' % (args.version, version_state(version))) + vid = version['id'] if version else None + + # 2. the build + plan.section('Build on the version') + attached = get_optional('/v1/appStoreVersions/%s/build' % vid) if vid else None + if attached and attached['id'] == build['id']: + plan.same('build', ba.get('version')) + else: + plan.change('build', attached and (attached.get('attributes') or {}).get('version'), + ba.get('version')) + if plan.apply: + api('PATCH', '/v1/appStoreVersions/%s/relationships/build' % vid, + {'data': {'type': 'builds', 'id': build['id']}}) + + # 3. release after approval + if version is not None: + cur = version['attributes'].get('releaseType') + if cur == RELEASE_TYPE: + plan.same('releaseType', cur) + else: + plan.change('releaseType', cur, RELEASE_TYPE) + if plan.apply: + patch('appStoreVersions', vid, {'releaseType': RELEASE_TYPE}) + + # 4. no phased release + phased = get_optional('/v1/appStoreVersions/%s/appStoreVersionPhasedRelease' % vid) if vid else None + if phased: + plan.change('phased release', phased['id'], 'removed') + if plan.apply: + api('DELETE', '/v1/appStoreVersionPhasedReleases/%s' % phased['id']) + else: + plan.same('phased release', 'none') + + # 5. What's New on every localization + plan.section("What's New") + if locs is None: + plan.change('whatsNew', None, text) + plan.info('(applied to every localization once the version exists)') + for loc in locs or []: + changed = plan.diff_attrs(loc['attributes'], {'whatsNew': text}, + {'whatsNew': locale_of(loc) + ' whatsNew'}) + if changed and plan.apply: + patch('appStoreVersionLocalizations', loc['id'], changed) + + # 6. export compliance + if ba.get('usesNonExemptEncryption') is None: + plan.note('Build %s has no export compliance answer (usesNonExemptEncryption is ' + 'null); App Review will not accept it until it is set.' % ba.get('version')) + + plan.finish() + + +# --------------------------------------------------------------------------- +# screenshots +# --------------------------------------------------------------------------- + +def png_size(path): + with open(path, 'rb') as fh: + head = fh.read(24) + if len(head) < 24 or head[:8] != b'\x89PNG\r\n\x1a\n' or head[12:16] != b'IHDR': + raise Fail('%s is not a PNG.' % path) + return struct.unpack('>II', head[16:24]) + + +def md5_file(path): + h = hashlib.md5() + with open(path, 'rb') as fh: + for chunk in iter(lambda: fh.read(1 << 20), b''): + h.update(chunk) + return h.hexdigest() + + +def upload_screenshot(set_id, path, checksum): + size = os.path.getsize(path) + name = os.path.basename(path) + shot = create('appScreenshots', {'fileName': name, 'fileSize': size}, + {'appScreenshotSet': rel('appScreenshotSets', set_id)}) + ops = shot['attributes'].get('uploadOperations') or [] + with open(path, 'rb') as fh: + blob = fh.read() + for op in ops: + chunk = blob[op['offset']:op['offset'] + op['length']] + req = urllib.request.Request(op['url'], data=chunk, method=op.get('method', 'PUT')) + for header in op.get('requestHeaders') or []: + req.add_header(header['name'], header['value']) + try: + with urllib.request.urlopen(req, timeout=120) as resp: + resp.read() + except urllib.error.HTTPError as exc: + raise Fail('Uploading %s chunk at offset %s failed (HTTP %s): %s' % ( + name, op['offset'], exc.code, exc.read()[:300])) + except urllib.error.URLError as exc: + raise Fail('Uploading %s failed: %s' % (name, exc.reason)) + patch('appScreenshots', shot['id'], {'uploaded': True, 'sourceFileChecksum': checksum}) + deadline = time.time() + 300 + while True: + try: + cur = get('/v1/appScreenshots/%s' % shot['id'])['data'] + except APIError as exc: + # Apple sometimes answers 5xx for a screenshot it has only just + # received, then recovers within seconds. Keep waiting until the + # deadline; a 4xx or a 5xx past the deadline still stops here. + if exc.status < 500 or time.time() > deadline: + raise + print(' %s: App Store Connect answered HTTP %s, checking again...' % ( + name, exc.status)) + time.sleep(5) + continue + state = shot_state(cur) + if state == 'COMPLETE': + return cur + if state == 'FAILED': + errs = (cur['attributes'].get('assetDeliveryState') or {}).get('errors') or [] + raise Fail('ASC failed to process %s: %s' % (name, '; '.join( + '%s %s' % (e.get('code', ''), e.get('description', '')) for e in errs) or 'no detail')) + if time.time() > deadline: + print(' %s still %s after 5 min; continuing (check again with status).' % (name, state)) + return cur + time.sleep(3) + + +def cmd_screenshots(args): + plan = Plan(args.apply) + root = os.path.abspath(args.dir) + if not os.path.isdir(root): + raise Fail('Screenshot directory not found: %s' % root) + + # Validate local files first, before any network call + local = {} + for folder, spec in SCREENSHOT_SETS.items(): + path = os.path.join(root, folder) + if not os.path.isdir(path): + continue + files = sorted(f for f in os.listdir(path) if f.lower().endswith('.png')) + if not files: + continue + if len(files) > MAX_SCREENSHOTS_PER_SET: + raise Fail('%s has %d PNGs; App Store Connect allows %d per set.' % ( + folder, len(files), MAX_SCREENSHOTS_PER_SET)) + entries = [] + for name in files: + full = os.path.join(path, name) + w, h = png_size(full) + if (w, h) not in spec['sizes']: + raise Fail('%s/%s is %dx%d; %s accepts %s.' % ( + folder, name, w, h, spec['label'], + ', '.join('%dx%d' % s for s in sorted(spec['sizes'])))) + entries.append({'name': name, 'path': full, 'md5': md5_file(full), 'size': (w, h)}) + local[folder] = entries + if not local: + raise Fail('No PNGs found under %s/{%s}.' % (root, ','.join(SCREENSHOT_SETS))) + + app = app_id() + versions = ios_versions(app) + version = editable_version(versions) + if not version: + if args.apply: + raise Fail('No editable App Store version. Create one first: ' + './asc_store.py prepare --version X.Y.Z --build N --whats-new-file F --apply') + # Dry run before prepare: compare with the newest version for a preview. + version = newest_version(versions) + if not version: + raise Fail('The app has no iOS App Store version.') + plan.note('No editable version yet; previewing against %s (%s), read-only. A new version ' + 'normally starts with the previous version\'s screenshots.' % ( + version['attributes'].get('versionString'), version_state(version))) + locs = version_localizations(version) + locales = [locale_of(l) for l in locs] + check_locales(locales) + if len(locales) != 1: + raise Fail('Screenshots go to exactly one localization; version %s has %d (%s).' % ( + version['attributes'].get('versionString'), len(locales), ', '.join(locales) or 'none')) + loc = locs[0] + sets = screenshot_sets(loc) + + for folder, entries in local.items(): + spec = SCREENSHOT_SETS[folder] + dtype = spec['displayType'] + plan.section('%s -> %s (%s)' % (folder, dtype, spec['label'])) + sset = next((s for s in sets if s['attributes'].get('screenshotDisplayType') == dtype), None) + existing = [] + if sset: + existing, _ = get_all('/v1/appScreenshotSets/%s/appScreenshots' % sset['id']) + order = get('/v1/appScreenshotSets/%s/relationships/appScreenshots' % sset['id'], + {'limit': '50'}).get('data') or [] + pos = {o['id']: i for i, o in enumerate(order)} + existing.sort(key=lambda s: pos.get(s['id'], 999)) + else: + plan.change('screenshot set', None, 'create ' + dtype) + if plan.apply: + sset = create('appScreenshotSets', {'screenshotDisplayType': dtype}, + {'appStoreVersionLocalization': rel('appStoreVersionLocalizations', loc['id'])}) + + # Screenshots to delete: everything on --replace, plus failed uploads + to_delete = [] + keep = [] + for shot in existing: + if args.replace or shot_state(shot) == 'FAILED': + to_delete.append(shot) + else: + keep.append(shot) + for shot in to_delete: + plan.change('delete', '%s [%s]' % (shot['attributes'].get('fileName'), shot_state(shot)), None) + + by_md5 = {} + for shot in keep: + by_md5.setdefault(shot['attributes'].get('sourceFileChecksum'), []).append(shot) + matched = [] # (entry, existing shot or None) + for entry in entries: + hit = by_md5.get(entry['md5']) + if hit: + shot = hit.pop(0) + plan.same(entry['name'], 'already uploaded (%s)' % shot_state(shot)) + matched.append((entry, shot)) + else: + plan.change(entry['name'], None, 'upload %dx%d' % entry['size']) + matched.append((entry, None)) + extras = [s for lst in by_md5.values() for s in lst] + for shot in extras: + plan.info('kept, not in %s/: %s (pass --replace to remove)' % ( + folder, shot['attributes'].get('fileName'))) + total = len(entries) + len(extras) + if total > MAX_SCREENSHOTS_PER_SET: + raise Fail('%s would hold %d screenshots (max %d). Use --replace.' % ( + dtype, total, MAX_SCREENSHOTS_PER_SET)) + + current_order = [s['id'] for s in keep] + desired_known = [s['id'] for _, s in matched if s] + [s['id'] for s in extras] + needs_upload = any(s is None for _, s in matched) + if not needs_upload and not to_delete and current_order != desired_known: + plan.change('order', ', '.join(s['attributes'].get('fileName') or '?' for s in keep), + ', '.join(e['name'] for e in entries)) + + if not plan.apply: + continue + for shot in to_delete: + api('DELETE', '/v1/appScreenshots/%s' % shot['id']) + final = [] + for entry, shot in matched: + if shot is None: + print(' uploading %s...' % entry['name']) + shot = upload_screenshot(sset['id'], entry['path'], entry['md5']) + final.append(shot['id']) + final += [s['id'] for s in extras] + order = get('/v1/appScreenshotSets/%s/relationships/appScreenshots' % sset['id'], + {'limit': '50'}).get('data') or [] + if [o['id'] for o in order] != final: + api('PATCH', '/v1/appScreenshotSets/%s/relationships/appScreenshots' % sset['id'], + {'data': [{'type': 'appScreenshots', 'id': i} for i in final]}) + print(' reordered to match file order') + + for folder in SCREENSHOT_SETS: + if folder not in local: + print('') + print('(%s/ not found or empty - %s set left unchanged)' % (folder, SCREENSHOT_SETS[folder]['displayType'])) + plan.finish() + + +# --------------------------------------------------------------------------- +# submit +# --------------------------------------------------------------------------- + +def check_ready_to_submit(version): + """Everything App Review needs that this script manages. Raises Fail on the + first thing missing; reads only.""" + build = get_optional('/v1/appStoreVersions/%s/build' % version['id']) + if not build: + raise Fail('Version %s has no build attached. Run ./asc_store.py prepare first.' + % version['attributes'].get('versionString')) + locs = version_localizations(version) + if not locs: + raise Fail('Version %s has no localizations.' % version['attributes'].get('versionString')) + no_notes = [locale_of(l) for l in locs if not (l['attributes'].get('whatsNew') or '').strip()] + if no_notes: + raise Fail("No What's New for: %s. Run ./asc_store.py prepare first." % ', '.join(no_notes)) + wanted = [spec['displayType'] for spec in SCREENSHOT_SETS.values()] + for loc in locs: + sets = {s['attributes'].get('screenshotDisplayType'): s for s in screenshot_sets(loc)} + missing = [] + for dtype in wanted: + shots = [] + if dtype in sets: + shots, _ = get_all('/v1/appScreenshotSets/%s/appScreenshots' % sets[dtype]['id']) + if not [s for s in shots if shot_state(s) != 'FAILED']: + missing.append(dtype) + if missing: + raise Fail('The %s localization has no screenshots for: %s. Run ' + './asc_store.py screenshots --dir DIR --apply.' % ( + locale_of(loc), ', '.join(missing))) + return build + + +def submission_has_version(submission_id, version_id): + items, included = get_all('/v1/reviewSubmissions/%s/items' % submission_id, + {'include': 'appStoreVersion'}) + for item in items: + linked = ((item.get('relationships') or {}).get('appStoreVersion') or {}).get('data') or {} + if linked.get('id') == version_id: + return True + return any(i.get('type') == 'appStoreVersions' and i.get('id') == version_id + for i in included) + + +def cmd_submit(args): + plan = Plan(args.apply) + app = app_id() + versions = ios_versions(app) + version = next((v for v in versions + if v['attributes'].get('versionString') == args.version), None) + if not version: + raise Fail('No iOS App Store version %s. Run ./asc_store.py prepare first.' % args.version) + if already_submitted(version): + print('already submitted (%s)' % version_state(version)) + return + resuming = in_unsubmitted_submission(version) + if editable_version([version]) is None and not resuming: + raise Fail('Version %s is %s and cannot be submitted.' % (args.version, version_state(version))) + + plan.section('Ready for review?') + if resuming: + plan.info('The version is already an item of a submission that was not submitted; ' + 'resuming it.') + build = check_ready_to_submit(version) + plan.same('build', (build.get('attributes') or {}).get('version') or build['id']) + plan.same("What's New", 'set on every localization') + plan.same('screenshots', ', '.join(spec['displayType'] for spec in SCREENSHOT_SETS.values())) + + # The review-submissions API: a submission (one open per app and platform), + # an item that points at the App Store version, then submitted=true. + plan.section('App Review submission') + open_subs, _ = get_all('/v1/reviewSubmissions', { + 'filter[app]': app, 'filter[platform]': 'IOS', 'filter[state]': READY_FOR_REVIEW}) + sub = open_subs[0] if open_subs else None + if sub: + plan.same('review submission', 'reuse open %s' % sub['id']) + else: + plan.change('review submission', None, 'create (IOS)') + plan.change('submission item', None, 'App Store version %s' % args.version) + plan.change('submitted', False, True) + + if plan.apply: + if sub is None: + sub = create('reviewSubmissions', {'platform': 'IOS'}, {'app': rel('apps', app)}) + try: + create('reviewSubmissionItems', None, { + 'reviewSubmission': rel('reviewSubmissions', sub['id']), + 'appStoreVersion': rel('appStoreVersions', version['id'])}) + except APIError as exc: + # ASC answers 409 for most state and validation errors, not only for + # a duplicate: carry on only when the version really is in the submission. + if exc.status != 409 or not submission_has_version(sub['id'], version['id']): + raise + print(' the version is already an item of this submission') + res = patch('reviewSubmissions', sub['id'], {'submitted': True}) + state = (((res or {}).get('data') or {}).get('attributes') or {}).get('state') + print(' submission %s is now %s' % (sub['id'], state or 'submitted')) + + plan.finish() + + +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description='Prepare, screenshot and submit MeshMapper iOS releases through ' + 'App Store Connect.') + sub = parser.add_subparsers(dest='command') + sub.required = True + + sub.add_parser('status', help='read-only overview of versions, builds and screenshots') + + p = sub.add_parser('prepare', help='version, build, release type, What\'s New ' + '(dry run unless --apply)') + p.add_argument('--version', required=True, metavar='X.Y.Z', help='App Store version string') + p.add_argument('--build', required=True, metavar='EPOCH', + help='build number (the epoch Build.sh printed)') + p.add_argument('--whats-new-file', required=True, metavar='FILE', + help='text file with the What\'s New text') + p.add_argument('--wait', type=int, default=1800, metavar='SECONDS', + help='how long to wait for the build to finish processing (default 1800)') + p.add_argument('--apply', action='store_true', help='perform the writes') + + p = sub.add_parser('screenshots', help='upload screenshots (dry run unless --apply)') + p.add_argument('--dir', required=True, + help='folder holding ios-iphone-69/, ios-ipad-13/ and watch-46/') + p.add_argument('--apply', action='store_true', help='perform the writes') + p.add_argument('--replace', action='store_true', + help='delete existing screenshots in those sets first') + + p = sub.add_parser('submit', help='submit the prepared version for App Review ' + '(dry run unless --apply)') + p.add_argument('--version', required=True, metavar='X.Y.Z', help='App Store version string') + p.add_argument('--apply', action='store_true', help='submit for real') + + args = parser.parse_args() + handlers = {'status': cmd_status, 'prepare': cmd_prepare, + 'screenshots': cmd_screenshots, 'submit': cmd_submit} + print('App Store Connect: %s (app %s)%s' % ( + BUNDLE_ID, app_id(), + '' if getattr(args, 'apply', False) or args.command == 'status' else ' [DRY RUN]')) + try: + handlers[args.command](args) + except Fail as exc: + print('') + print('Error: %s' % exc, file=sys.stderr) + sys.exit(1) + except KeyboardInterrupt: + print('\nInterrupted.', file=sys.stderr) + sys.exit(130) + + +if __name__ == '__main__': + main() diff --git a/docs/CUSTOM_API_ENDPOINT.md b/docs/CUSTOM_API_ENDPOINT.md index 44c41028..c1227b84 100644 --- a/docs/CUSTOM_API_ENDPOINT.md +++ b/docs/CUSTOM_API_ENDPOINT.md @@ -1,6 +1,6 @@ # Custom API Endpoint - Third-Party Developer Guide -This document describes the API contract for receiving forwarded wardrive data from MeshMapper. When a user enables "Custom API Endpoint" in MeshMapper settings, every successful wardrive batch upload is also forwarded to your endpoint. +This document describes the API contract for receiving forwarded wardrive data from MeshMapper. When a user enables "Custom API Endpoint" in MeshMapper settings, every successful wardrive batch upload is also forwarded to your endpoint. This includes offline sessions the user uploads later: each 50-row chunk that uploads is forwarded as its own request. ## Request Format @@ -22,7 +22,7 @@ This document describes the API contract for receiving forwarded wardrive data f } ``` -The `data` array contains 1-50 ping objects per batch. Batches arrive approximately every 15-30 seconds during an active wardriving session. +The `data` array contains 1-50 ping objects per batch. During a live session the app uploads about 5 seconds after each TX, DISC, TRACE, DEFER or SCOPES item is queued, and on a 15-second timer otherwise (both stretch to 60 seconds on a constrained link such as satellite). Each successful upload is forwarded once. ## Ping Object Schema @@ -32,17 +32,21 @@ Every ping object contains a `type` field that determines which additional field | Field | Type | Description | |-------|------|-------------| -| `type` | `string` | Ping type: `"TX"`, `"RX"`, `"DISC"`, `"TRACE"`, or `"DEFER"`. A `DEFER` carries only the common `lat`, `lon`, `timestamp`, `contact`, `iata` and `radio_freq` fields plus `held` (see below); it has no `external_antenna`, `noisefloor`, `altitude` or `power`. | +| `type` | `string` | Ping type: `"TX"`, `"RX"`, `"DISC"`, `"TRACE"`, `"DEFER"`, or `"SCOPES"`. A `DEFER` carries only the common `lat`, `lon`, `timestamp`, `contact`, `iata` and `radio_freq` fields plus `held` (see below); it has no `external_antenna`, `noisefloor`, `altitude`, `altitude_ref`, `altitude_acc` or `power`. A `SCOPES` carries only the common `timestamp`, `lat`, `lon`, `contact`, `iata` and `radio_freq` fields plus `public_key` and `scopes` (see below); it has no `external_antenna`, `noisefloor`, `altitude`, `altitude_ref`, `altitude_acc` or `power` either. | | `lat` | `number` | Latitude (WGS84, decimal degrees) | | `lon` | `number` | Longitude (WGS84, decimal degrees) | | `timestamp` | `integer` | Unix timestamp in seconds | | `external_antenna` | `boolean` | Whether an external antenna is connected to the device | | `noisefloor` | `integer\|null` | Ambient noise floor in dBm (e.g., -103). Null if unavailable. | -| `altitude` | `integer\|absent` | Altitude of the fix in whole meters (e.g., `123`). Absent when the phone did not know its altitude. iOS reports height above mean sea level. Android usually reports height above the WGS84 ellipsoid, but Android 14 and later substitutes mean sea level when the fix carries it, so one device can report either. The two references can differ by up to about 100 m. | +| `altitude` | `integer\|absent` | Altitude of the fix in whole meters (e.g., `123`). Present only together with `altitude_ref`: an altitude whose reference the app could not prove is not sent at all. Absent on `DEFER` and `SCOPES`. | +| `altitude_ref` | `string\|absent` | The reference `altitude` is measured from: `"msl"` (above mean sea level) or `"ellipsoid"` (above the WGS84 ellipsoid). The two differ by the local geoid separation, tens of meters in most places. iPhones always send `msl`; Android phones send `ellipsoid` below Android 14 and either on Android 14 and later, whichever the fix carried. Always present beside `altitude`. | +| `altitude_acc` | `integer\|absent` | Vertical accuracy of the fix in whole meters, about one standard deviation. Present only beside `altitude` and only when the phone knew it. | | `radio_freq` | `string\|absent` | The radio configuration the item was recorded under, as `freqMHz,bwKHz,SF,CR` (e.g. `"910.525,62.5,7,5"`). Absent when the radio did not report its parameters. Present on every type, `DEFER` included. | | `power` | `string\|null` | Radio TX power formatted as `"X.Xw"` (e.g., `"0.3w"`, `"1.0w"`, `"2.0w"`). Null if unavailable. | | `contact` | `string\|absent` | First 8 hex chars of the wardriver's MeshCore device public key (e.g., `"D873B1F2"`). Only present when the user enables "Include Contact Key" in settings. Useful for cross-referencing with MQTT observer data. | -| `iata` | `string\|absent` | MeshMapper zone code (e.g., `"RDU"`, `"MSP"`, `"YOW"`). Present when the wardriver is in a zone. | +| `iata` | `string\|absent` | MeshMapper zone code (e.g., `"RDU"`, `"MSP"`, `"YOW"`). The wardriver's current zone, or the last zone the app saved when there is no current one. On an offline session upload, it is the zone the upload was made from, for the whole chunk, not where each ping was recorded. | + +Earlier builds forwarded an `altitude` with no reference; those bare altitudes are no longer forwarded. ### TX Ping (type: "TX") @@ -50,7 +54,11 @@ A transmitted ping broadcast on the wardriving channel, with repeater echo resul | Field | Type | Description | |-------|------|-------------| -| `heard_repeats` | `string` | Comma-separated repeater echoes: `"id(snr),id(snr)"` or `"None"` if no repeaters heard. IDs are hex strings (1-6 chars). SNR is in dB. | +| `heard_repeats` | `string` | Comma-separated repeater echoes: `"id(snr),id(snr)"` or `"None"` if no repeaters heard. IDs are upper-case hex: 2, 4 or 6 characters depending on the path's bytes per hop (8 is possible). SNR is in dB with two decimals, or `null` when the echo came through the user's own CARpeater (for example `"4E(null)"`). | +| `wire_tag` | `string\|absent` | The encrypted tag the ping carried on air instead of its coordinates (e.g., `"MM:Ab3dEf9hIj"`). Only MeshMapper holds the key that decrypts it. Decrypted, it names the session and the ping that sent it, which is how MeshMapper matches a ping heard by an observer in another region back to its session (cross-region spillover). Can be absent: a TX that carried no tag, for example from an offline session saved by an older app version, has none. | +| `ping_counter` | `integer\|absent` | The ping's number within the user's MeshMapper session. Sent only together with `wire_tag`. | + +Echoes that reached the user through more than one repeater are not in `heard_repeats`. They arrive as separate `RX` items at the TX ping's location. **Example:** @@ -61,11 +69,15 @@ A transmitted ping broadcast on the wardriving channel, with repeater echo resul "lon": -75.77746, "noisefloor": -103, "altitude": 84, + "altitude_ref": "msl", + "altitude_acc": 6, "radio_freq": "910.525,62.5,7,5", - "heard_repeats": "4e(12.25),77(8.50)", + "heard_repeats": "4E(12.25),77(8.50)", "timestamp": 1768762843, "external_antenna": false, "power": "0.3w", + "ping_counter": 42, + "wire_tag": "MM:Ab3dEf9hIj", "contact": "D873B1F2", "iata": "YOW" } @@ -80,11 +92,15 @@ A transmitted ping broadcast on the wardriving channel, with repeater echo resul "lon": -75.77802, "noisefloor": -101, "altitude": 86, + "altitude_ref": "msl", + "altitude_acc": 6, "radio_freq": "910.525,62.5,7,5", "heard_repeats": "None", "timestamp": 1768762873, "external_antenna": false, "power": "0.3w", + "ping_counter": 43, + "wire_tag": "MM:Kl2mNo4pQr", "contact": "D873B1F2", "iata": "YOW" } @@ -92,11 +108,11 @@ A transmitted ping broadcast on the wardriving channel, with repeater echo resul ### RX Ping (type: "RX") -A passively observed mesh packet from a nearby repeater. +A passively observed mesh packet from a nearby repeater, or a TX echo that reached the user through more than one repeater. | Field | Type | Description | |-------|------|-------------| -| `heard_repeats` | `string` | Single repeater with SNR: `"id(snr)"` (e.g., `"4e(12.0)"`). | +| `heard_repeats` | `string` | Single repeater with SNR: `"id(snr)"` (e.g., `"4E(12.00)"`). Same ID and SNR format as TX, so the SNR can be `null` (`"4E(null)"`). | **Example:** @@ -106,7 +122,7 @@ A passively observed mesh packet from a nearby repeater. "lat": 45.26950, "lon": -75.77700, "noisefloor": -105, - "heard_repeats": "4e(12.00)", + "heard_repeats": "4E(12.00)", "timestamp": 1768762900, "external_antenna": false, "power": "0.3w", @@ -121,12 +137,14 @@ A response from a discovered repeater or room node. | Field | Type | Description | |-------|------|-------------| -| `repeater_id` | `string` | Hex ID of the discovered node (e.g., `"a3b2c1"`), or `"None"` for failed discovery. | +| `repeater_id` | `string` | Upper-case hex ID of the discovered node: the first 2, 4 or 6 characters of its public key, following the user's path bytes setting (e.g., `"A3B2C1"`). `"None"` for a failed discovery. | | `node_type` | `string` | Node type: `"REPEATER"` or `"ROOM"`. Absent on failed discovery. | -| `local_snr` | `number` | SNR measured locally (dB). | -| `local_rssi` | `integer` | RSSI measured locally (dBm, negative). | -| `remote_snr` | `number` | SNR reported by the remote node (dB). | -| `public_key` | `string` | Full 32-byte public key of the node (64 hex chars). | +| `local_snr` | `number` | SNR measured locally (dB). `0` if the stored value could not be read. | +| `local_rssi` | `integer` | RSSI measured locally (dBm, negative). `0` if the stored value could not be read. | +| `remote_snr` | `number` | SNR reported by the remote node (dB). `0` if the stored value could not be read. | +| `public_key` | `string` | Full 32-byte public key of the node (64 upper-case hex chars). | + +A failed discovery (no node answered) is only sent when the user or region has **Discovery Drop** on. It carries none of `node_type`, `local_snr`, `local_rssi`, `remote_snr` or `public_key`. **Example (successful discovery):** @@ -136,12 +154,12 @@ A response from a discovered repeater or room node. "lat": 45.26980, "lon": -75.77750, "noisefloor": -102, - "repeater_id": "a3b2c1", + "repeater_id": "A3B2C1", "node_type": "REPEATER", "local_snr": 11.75, "local_rssi": -85, "remote_snr": 9.50, - "public_key": "a3b2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2", + "public_key": "A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2", "timestamp": 1768762950, "external_antenna": true, "power": "1.0w", @@ -174,9 +192,11 @@ A targeted zero-hop trace to a specific repeater. | Field | Type | Description | |-------|------|-------------| | `repeater_id` | `string` | Hex ID of the targeted repeater. | -| `local_snr` | `number` | SNR measured locally (dB). | -| `local_rssi` | `integer` | RSSI measured locally (dBm, negative). | -| `remote_snr` | `number` | SNR reported by the repeater (dB). | +| `local_snr` | `number\|null` | SNR measured locally (dB). | +| `local_rssi` | `integer\|null` | RSSI measured locally (dBm, negative). | +| `remote_snr` | `number\|null` | SNR reported by the repeater (dB). | + +Only traces the repeater answered are sent. **Example:** @@ -200,7 +220,7 @@ A targeted zero-hop trace to a specific repeater. ### DEFER (type: "DEFER") -A square where the app's smart pinging held a TX ping or a discovery request because MeshMapper already had recent coverage there. The app reports it so MeshMapper can credit the square; you receive it because it may help a mapper keeping its own coverage. +A square where the app's smart pinging held a TX ping or a discovery request because MeshMapper already had recent coverage there. The app reports it so MeshMapper can credit the square; you receive it because it may help a mapper keeping its own coverage. Discovery requests are only held when the user (or the region) has turned off Delay only flood pings. **A deferral is unverified.** MeshMapper checks each one against its own coverage data and silently discards any it cannot confirm, but the batch answer does not say which items were kept, and the app forwards the whole batch after the upload succeeds. Treat a `DEFER` as "the app believed this square was covered", not as a confirmed observation. @@ -208,7 +228,7 @@ A square where the app's smart pinging held a TX ping or a discovery request bec |-------|------|-------------| | `held` | `string` | Which kind of ping was held: `"tx"` (a channel ping) or `"disc"` (a discovery request). | -The `external_antenna`, `noisefloor`, `altitude` and `power` fields are not present on a `DEFER`. A `DEFER` carries `lat`, `lon`, `timestamp`, `contact`, `iata`, `held` and `radio_freq`. At most one `DEFER` is sent per 300 m square per MeshMapper session. +The `external_antenna`, `noisefloor`, `altitude`, `altitude_ref`, `altitude_acc` and `power` fields are not present on a `DEFER`. A `DEFER` carries `lat`, `lon`, `timestamp`, `contact`, `iata`, `held` and `radio_freq`. At most one `DEFER` is sent per 300 m square per MeshMapper session. **Example:** @@ -225,9 +245,37 @@ The `external_antenna`, `noisefloor`, `altitude` and `power` fields are not pres } ``` +### SCOPES (type: "SCOPES") + +A repeater's answer to a direct scope discovery question, sent after a discovery finds the repeater. The app asks a discovered repeater which regions (flood scopes) it carries, and the repeater answers with a list of region names. A `SCOPES` item is only sent after the `DISC` item for the discovery that found the repeater. If the server stops offering scope discovery, queued `SCOPES` items are dropped and never forwarded. + +**A SCOPES answer is unverified.** MeshMapper checks each answer against a discovery the same radio reported and discards any it cannot confirm, but the batch answer does not say which were kept, and the app forwards the whole batch after the upload succeeds. A long answer can also be incomplete: the repeater leaves out names that do not fit in its reply. + +| Field | Type | Description | +|-------|------|-------------| +| `public_key` | `string` | Full 32-byte public key of the answering repeater (64 hex chars, upper case). | +| `scopes` | `array of string` | The scope names exactly as the repeater sent them, case-sensitive. Each entry is `"*"` (the repeater passes unscoped traffic) or a name of 1 to 30 bytes that does not start with `#`. May be empty. At most 33 entries. | + +`lat` and `lon` are where the discovery that found the repeater was made, not where the answer arrived. `timestamp` is when the answer arrived. The `external_antenna`, `noisefloor`, `altitude`, `altitude_ref`, `altitude_acc` and `power` fields are not present on a `SCOPES` item. + +**Example:** + +```json +{ + "type": "SCOPES", + "public_key": "A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2", + "scopes": ["ROOM1", "*"], + "timestamp": 1768763050, + "lat": 45.26980, + "lon": -75.77750, + "contact": "D873B1F2", + "iata": "YOW" +} +``` + ## Batch Examples -A batch is whatever the app uploaded to MeshMapper in that round, so one request can mix every type above. `DEFER` items only appear from app version 1.4.0 onward, and only while the user has Smart Pinging on (the default) in Active, Passive or Hybrid mode, so your endpoint must accept batches both with and without them. Dispatch on `type` and ignore any value you do not handle rather than rejecting the batch: a `4xx` is shown to the user as an error. +A batch is whatever the app uploaded to MeshMapper in that round, so one request can mix every type above. `DEFER` items only appear while the user has Smart Pinging on (the default) in Active or Hybrid mode, or in Passive mode with Delay only flood pings turned off, so your endpoint must accept batches both with and without them. `SCOPES` items only appear while scope discovery is on, either enforced by the region or switched on by the user, so your endpoint must accept batches with and without them too. Dispatch on `type` and ignore any value you do not handle rather than rejecting the batch: a `4xx` is shown to the user as an error. **Batch without a DEFER** (a TX ping and a passive RX observation): @@ -240,11 +288,15 @@ A batch is whatever the app uploaded to MeshMapper in that round, so one request "lon": -75.77746, "noisefloor": -103, "altitude": 84, + "altitude_ref": "msl", + "altitude_acc": 6, "radio_freq": "910.525,62.5,7,5", - "heard_repeats": "4e(12.25),77(8.50)", + "heard_repeats": "4E(12.25),77(8.50)", "timestamp": 1768762843, "external_antenna": false, "power": "0.3w", + "ping_counter": 42, + "wire_tag": "MM:Ab3dEf9hIj", "contact": "D873B1F2", "iata": "YOW" }, @@ -253,7 +305,7 @@ A batch is whatever the app uploaded to MeshMapper in that round, so one request "lat": 45.26950, "lon": -75.77700, "noisefloor": -105, - "heard_repeats": "4e(12.00)", + "heard_repeats": "4E(12.00)", "timestamp": 1768762900, "external_antenna": false, "power": "0.3w", @@ -295,7 +347,7 @@ A batch is whatever the app uploaded to MeshMapper in that round, so one request } ``` -Note that the `DEFER` has no `noisefloor`, `altitude`, `external_antenna` or `power`, while the `RX` beside it does. +Note that the `DEFER` has no `noisefloor`, `altitude`, `altitude_ref`, `altitude_acc`, `external_antenna` or `power`, while the `RX` beside it does. ## Expected Response @@ -306,14 +358,14 @@ Your endpoint should return any `2xx` HTTP status code on success. The response | `200-299` | Logged as success. No further action. | | `4xx` | Error logged to user's error tab (throttled to once per minute per status code). | | `5xx` | Error logged to user's error tab (throttled to once per minute per status code). | -| Timeout (>10s) | Error logged as timeout. | -| Network error | Error logged as network error. | +| Timeout (>10s) | Error logged as timeout (throttled to once per minute). | +| Network error | Error logged as network error (throttled to once per minute). | MeshMapper does **not** retry failed custom API requests. Each batch is sent exactly once. ## Configuration Link for End Users -As an endpoint operator, you can generate a configuration link that your users paste into their clipboard. In MeshMapper Settings > API Endpoints, they tap **Import from Clipboard** to auto-fill the URL and API key. +As an endpoint operator, you can generate a configuration link that your users copy to their clipboard. In MeshMapper Settings > API Endpoints, they switch on **Custom API Endpoint** (and accept the "Third-Party Data Sharing" notice), then tap **Import from Clipboard**, which only appears once the switch is on, to auto-fill the URL and API key. **Format:** @@ -324,13 +376,15 @@ meshmapper://custom-api?url=your-server.com/api/wardrive&key=your-api-key-here - `url` — Your endpoint host and path, **without** `https://` (MeshMapper prepends it automatically). - `key` — The API key the user should send. This will be set as their `X-API-Key` header value. +The link is read as an ordinary URL query, so percent-encode any `&`, `+`, `#` or `%` inside the `url` or `key` values (for example `&` as `%26`). Left unencoded, they cut the value short or change it. + **Example:** ``` meshmapper://custom-api?url=data.myproject.org/ingest/wardrive&key=sk_live_abc123def456 ``` -The user copies this link, opens MeshMapper Settings > API Endpoints, and taps "Import from Clipboard." Both fields are populated instantly. +The user copies this link, opens MeshMapper Settings > API Endpoints, and taps "Import from Clipboard." Both fields are populated instantly. The endpoint settings can't be changed while an auto mode is running. ## Security Notes @@ -342,7 +396,7 @@ The user copies this link, opens MeshMapper Settings > API Endpoints, and taps " ## Rate and Volume -- **Batch frequency**: Every 15-30 seconds during active wardriving (depends on auto-ping interval and batch timer). +- **Batch frequency**: About 5 seconds after each TX, DISC, TRACE, DEFER or SCOPES item, and every 15 seconds otherwise (60 seconds on a constrained link). Offline session uploads arrive as a burst of up to 50 items per request. - **Batch size**: 1-50 ping objects per request (typically 1-10). - **Session duration**: Wardriving sessions commonly last 30 minutes to several hours. - **Concurrent users**: Plan for multiple users if distributing your endpoint URL. Each user sends independently. diff --git a/docs/LIVE_ACTIVITIES.md b/docs/LIVE_ACTIVITIES.md index 0c928fd3..d470b29c 100644 --- a/docs/LIVE_ACTIVITIES.md +++ b/docs/LIVE_ACTIVITIES.md @@ -6,7 +6,7 @@ MeshMapper starts one read-only Live Activity while an automatic wardriving sess - Current mode and phase (`Sending`, `Listening`, `Next ping`, `Cooldown`, GPS/zone/reconnect states) - System-rendered countdowns based on absolute timer deadlines -- The map's Top Heard rows: the latest ping's top three repeaters by SNR plus the current passive RX slot, the same list the watch shows. Rows heard before the latest send stay on the card dimmed as last heard; a silent ping does not wipe them +- The map's Top Heard rows: the latest ping's top three repeaters by SNR plus the current passive RX slot, the same list the watch shows. It stays three whatever the in-app Top Heard Rows setting is. Rows heard before the latest send stay on the card dimmed as last heard; a silent ping does not wipe them. Repeater names (when "Repeater Names on Live Activity" is on) show the user's own nickname when set in Settings > Map > Repeater Nicknames, otherwise the server name - TX/RX counters, upload queue, zone, connection state, and stale-update warnings - Lock Screen, Dynamic Island, and one iOS 18 small-family layout shared by the paired watch's Smart Stack card and the CarPlay dashboard. CarPlay's canvas overlaps the watch card sizes and nothing names the surface, so the card solves its row count and font from the measured height instead of guessing diff --git a/ios/MeshMapperLiveActivity/MeshMapperLiveActivity.swift b/ios/MeshMapperLiveActivity/MeshMapperLiveActivity.swift index 8d5126ad..2b248754 100644 --- a/ios/MeshMapperLiveActivity/MeshMapperLiveActivity.swift +++ b/ios/MeshMapperLiveActivity/MeshMapperLiveActivity.swift @@ -211,6 +211,12 @@ private struct MeshMapperSmallActivityContent: View { .padding(.vertical, isWide ? 6 : 4) } } + // Opaque on purpose rather than left to `activityBackgroundTint`. When the + // CarPlay dashboard re-lays the card at a new canvas size it can leave the + // previous frame underneath, and it showed through the transparent rows as + // a doubled "Nothing heard" (one copy per width tier). The band was always + // opaque and never ghosted. + .background(MeshMapperPalette.background) .foregroundStyle(.white) } diff --git a/ios/MeshMapperWatch/SampleSnapshot.swift b/ios/MeshMapperWatch/SampleSnapshot.swift index 31c8f482..bc88c7a6 100644 --- a/ios/MeshMapperWatch/SampleSnapshot.swift +++ b/ios/MeshMapperWatch/SampleSnapshot.swift @@ -51,10 +51,10 @@ enum SampleSnapshot { UserDefaults.standard.bool(forKey: "MeshMapperSampleData") } - /// Downtown Seattle, roughly — somewhere with enough spread to see marker + /// Downtown Ottawa, roughly — somewhere with enough spread to see marker /// density and line geometry at a realistic zoom. - private static let originLat = 47.6062 - private static let originLon = -122.3321 + private static let originLat = 45.4205 + private static let originLon = -75.6950 /// Metres travelled per emitted step, matching the phone's movement gate. /// @@ -195,10 +195,10 @@ enum SampleSnapshot { } let repeaters: [WatchRepeater] = [ - ("4E", "Capitol Hill", 0.010, 0.004, pink, true), - ("77", "Queen Anne", -0.006, 0.012, pink, true), - ("A2", "Beacon Hill", -0.012, -0.008, orange, false), - ("B9", "Magnolia", 0.004, -0.015, pink, false), + ("4E", "Centretown", 0.010, 0.004, pink, true), + ("77", "ByWard Market", -0.006, 0.012, pink, true), + ("A2", "The Glebe", -0.012, -0.008, orange, false), + ("B9", "Westboro", 0.004, -0.015, pink, false), ].map { id, name, dLat, dLon, color, heard in WatchRepeater( id: id, @@ -219,10 +219,10 @@ enum SampleSnapshot { // hex characters per row, which is what the box has to survive on 40 mm. let long = UserDefaults.standard.bool(forKey: "MeshMapperLongIds") let heard: [WatchHeardNode] = [ - (long ? "4E5D82" : "4E5D", "Capitol Hill", 8.5, 1420.0, green), + (long ? "4E5D82" : "4E5D", "Centretown", 8.5, 1420.0, green), (long ? "77A1B0" : "77A1", nil, 2.25, 2310.0, teal), (long ? "A2FF31" : "A2", nil, -14.5, nil, green), - (long ? "B914C2" : "B914", "Magnolia", 5.75, 2870.0, purple), + (long ? "B914C2" : "B914", "Westboro", 5.75, 2870.0, purple), ].map { id, name, snr, distance, typeColor in WatchHeardNode( id: id, @@ -251,7 +251,7 @@ enum SampleSnapshot { phaseEndsAtMs: samplePhase.endsAtMs, phaseDurationMs: samplePhase.durationMs, isConnected: true, - zoneCode: "SEA", + zoneCode: "ONQC", txCount: 27, rxCount: 14, discoveryCount: 6, diff --git a/ios/Podfile b/ios/Podfile index 22d33ba4..3c5072af 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -# platform :ios, '13.0' +# platform :ios, '15.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 10431777..505625f7 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -35,12 +35,12 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: disk_space_plus: a36391fb5f732dbdd29628b0bac5a1acbd43aaef - Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 + Flutter: 71a624a5bc0c04062bf19101d501e466baf2fb47 flutter_background_service_ios: 00d31bdff7b4bfe06d32375df358abe0329cf87e flutter_local_notifications: ad39620c743ea4c15127860f4b5641649a988100 flutter_secure_storage: 1ed9476fba7e7a782b22888f956cce43e2c62f13 permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d -PODFILE CHECKSUM: 1b71fceb7f7c8618409f0f855f3558d90a1d2b33 +PODFILE CHECKSUM: c18d393ab851676981e0090eb28cf863c42679ff COCOAPODS: 1.16.2 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index be871f68..95459910 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -917,7 +917,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MESHMAPPER_BUNDLE_PREFIX = net.meshmapper.app; MESHMAPPER_DEVELOPMENT_TEAM = DQC6TNKG5P; MTL_ENABLE_DEBUG_INFO = NO; @@ -1085,7 +1085,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MESHMAPPER_BUNDLE_PREFIX = net.meshmapper.app; MESHMAPPER_DEVELOPMENT_TEAM = DQC6TNKG5P; MTL_ENABLE_DEBUG_INFO = YES; @@ -1141,7 +1141,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MESHMAPPER_BUNDLE_PREFIX = net.meshmapper.app; MESHMAPPER_DEVELOPMENT_TEAM = DQC6TNKG5P; MTL_ENABLE_DEBUG_INFO = NO; diff --git a/ios/Runner/AppIntents/SiriIntentCoordinator.swift b/ios/Runner/AppIntents/SiriIntentCoordinator.swift index b21c6a38..489fc98b 100644 --- a/ios/Runner/AppIntents/SiriIntentCoordinator.swift +++ b/ios/Runner/AppIntents/SiriIntentCoordinator.swift @@ -1,6 +1,7 @@ import AppIntents import Flutter import Foundation +import os enum SiriBridgeError: LocalizedError { case appUnavailable @@ -90,6 +91,24 @@ struct SiriCommand { kind == .connectLastCompanion ? 30 : 10 } + /// iOS ends an App Intent on its own 30 seconds after `perform()` starts and + /// shows a generic failure ("an unknown error occurred" on iOS 26, a timeout + /// on iOS 27), discarding whatever the intent returns after that. Every + /// response deadline is capped at this much from the command's creation, so + /// our own answer always lands first. Measured on device: `perform()` starts + /// about 0.4 s into the run, and iOS cut the run at 30.01 s. + static let intentBudget: TimeInterval = 25 + + /// The instant the intent stops waiting: `responseTimeout` from now, but + /// never past `intentBudget` from creation, since the channel wait before it + /// already spent part of iOS's allowance. + func responseDeadline(from now: Date = Date()) -> Date { + min( + now.addingTimeInterval(responseTimeout), + issuedAt.addingTimeInterval(Self.intentBudget) + ) + } + func dictionary(expiresAt: Date) -> [String: Any?] { [ "id": id, @@ -140,6 +159,10 @@ final class SiriIntentCoordinator { static let shared = SiriIntentCoordinator() private var channel: FlutterMethodChannel? + private let log = Logger( + subsystem: Bundle.main.bundleIdentifier ?? "MeshMapper", + category: "Siri" + ) private init() {} func attach(channel: FlutterMethodChannel) { @@ -152,17 +175,28 @@ final class SiriIntentCoordinator { try Task.checkCancellation() try await Task.sleep(nanoseconds: 100_000_000) } - guard let channel else { throw SiriBridgeError.appUnavailable } + let kind = command.kind.rawValue + let shortId = String(command.id.prefix(8)) + let channelWaitMs = Int(Date().timeIntervalSince(command.issuedAt) * 1_000) + guard let channel else { + log.error("\(kind, privacy: .public) \(shortId, privacy: .public): channel not ready after \(channelWaitMs)ms") + throw SiriBridgeError.appUnavailable + } + let log = self.log return try await withCheckedThrowingContinuation { continuation in var completed = false // Measured from here, not from the command's creation, because the wait - // for the channel above can consume most of a cold launch on its own. - let responseTimeout = command.responseTimeout - let expiresAt = Date().addingTimeInterval(responseTimeout) + // for the channel above can consume most of a cold launch on its own, + // then capped so it never outlives iOS's own limit on the intent. + let sentAt = Date() + let expiresAt = command.responseDeadline(from: sentAt) + let responseTimeout = max(0, expiresAt.timeIntervalSince(sentAt)) + log.notice("\(kind, privacy: .public) \(shortId, privacy: .public): sent to Dart after \(channelWaitMs)ms channel wait, waiting \(Int(responseTimeout * 1_000))ms") let timeout = DispatchWorkItem { guard !completed else { return } completed = true + log.error("\(kind, privacy: .public) \(shortId, privacy: .public): no answer from Dart within \(Int(responseTimeout * 1_000))ms") continuation.resume(throwing: SiriBridgeError.timedOut(command.kind)) } DispatchQueue.main.asyncAfter(deadline: .now() + responseTimeout, execute: timeout) @@ -170,12 +204,19 @@ final class SiriIntentCoordinator { "command", arguments: command.dictionary(expiresAt: expiresAt) ) { response in - guard !completed else { return } + guard !completed else { + log.notice("\(kind, privacy: .public) \(shortId, privacy: .public): late answer from Dart ignored") + return + } completed = true timeout.cancel() + let elapsedMs = Int(Date().timeIntervalSince(sentAt) * 1_000) do { - continuation.resume(returning: try SiriCommandResult(response: response)) + let result = try SiriCommandResult(response: response) + log.notice("\(kind, privacy: .public) \(shortId, privacy: .public): answered in \(elapsedMs)ms, \(result.disposition.rawValue, privacy: .public) success=\(result.success)") + continuation.resume(returning: result) } catch { + log.error("\(kind, privacy: .public) \(shortId, privacy: .public): bad answer after \(elapsedMs)ms: \(error.localizedDescription, privacy: .public)") continuation.resume(throwing: error) } } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 8aae773a..d7dc90b3 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -42,6 +42,11 @@ This app needs background GPS for continuous wardriving NSLocationWhenInUseUsageDescription This app needs GPS for wardriving location tracking + NSLocationTemporaryUsageDescriptionDictionary + + CoverageMapping + MeshMapper needs your precise location to place coverage on the map. + NSMicrophoneUsageDescription This app uses audio for notification sounds NSPhotoLibraryUsageDescription diff --git a/lib/debug/store_capture.dart b/lib/debug/store_capture.dart new file mode 100644 index 00000000..89e2b353 --- /dev/null +++ b/lib/debug/store_capture.dart @@ -0,0 +1,322 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import '../models/log_entry.dart'; +import '../models/noise_floor_session.dart'; +import '../models/ping_data.dart'; +import 'store_capture_route.dart'; + +// Debug-only "capture mode" data for the app store screenshots. Screenshots +// are taken on simulators with no radio, so a made-up wardrive is loaded in +// memory. Nothing here touches Hive, the API queue or any upload path. + +/// Name of the config file looked up in the app's documents directory. +const storeCaptureFileName = 'store_capture.json'; + +/// Radio name shown in the header while capture mode is active. +const storeCaptureRadioName = 'Ottawa Mobile'; + +/// Repeater ids used when no repeaters have been loaded from the server. +const storeCaptureFallbackIds = [ + '4E5D', + '77A1', + 'A2F3', + 'B914', + 'C3F0', + '1D7E' +]; + +/// Device id stamped on every sample ping. +const _deviceId = 'store-capture'; + +/// Index of the route point whose TX is forced to be a miss, so a drive always +/// has at least one red ping whatever the random draw gives. The newest ping +/// (the GPS arrow) is the opposite: it is always heard. +const _forcedMissIndex = 30; + +/// Bottom-bar tab the capture opens on. +enum StoreCaptureScreen { + map, + log, + history; + + /// Index of the tab in the main scaffold. + int get tabIndex => index; +} + +/// What the capture should show, read from [storeCaptureFileName]. +class StoreCaptureConfig { + /// Set once at startup when a valid config file was found. + static StoreCaptureConfig? active; + + final StoreCaptureScreen screen; + + const StoreCaptureConfig({required this.screen}); + + /// Parses the file body. Returns null for anything that is not a JSON object + /// with a known `screen`. + static StoreCaptureConfig? parse(String json) { + try { + final decoded = jsonDecode(json); + if (decoded is! Map) return null; + final name = decoded['screen']; + for (final screen in StoreCaptureScreen.values) { + if (screen.name == name) return StoreCaptureConfig(screen: screen); + } + return null; + } catch (_) { + return null; + } + } + + /// Reads [storeCaptureFileName] from [documents]. Null when the file is + /// missing or invalid. + static Future load(Directory documents) async { + try { + final file = File('${documents.path}/$storeCaptureFileName'); + if (!await file.exists()) return null; + return parse(await file.readAsString()); + } catch (_) { + return null; + } + } +} + +/// The made-up drive: every list the Map, Log and History screens read, plus +/// the numbers shown in the header. +class StoreCaptureSample { + final List txPings; + final List txLog; + final List rxPings; + final List rxLog; + final List disc; + final List trace; + final List sessions; + final PingStats stats; + final int noiseFloor; + final int batteryPercent; + + const StoreCaptureSample({ + required this.txPings, + required this.txLog, + required this.rxPings, + required this.rxLog, + required this.disc, + required this.trace, + required this.sessions, + required this.stats, + required this.noiseFloor, + required this.batteryPercent, + }); +} + +/// Builds the sample drive along [storeCaptureRoute]. The last point is the +/// newest TX, at [newest]; earlier points are 22 s apart. Repeaters heard come +/// from [repeaters] (nearest within 12 km), or from +/// [storeCaptureFallbackIds] when none are loaded. Same inputs, same output. +StoreCaptureSample buildStoreCaptureSample({ + required DateTime newest, + required List<({String id, double lat, double lon})> repeaters, +}) { + final rnd = math.Random(7); + const route = storeCaptureRoute; + final last = route.length - 1; + + double km(double la1, double lo1, double la2, double lo2) { + final dy = (la2 - la1) * 111.0; + final dx = (lo2 - lo1) * 111.0 * math.cos(la1 * math.pi / 180); + return math.sqrt(dx * dx + dy * dy); + } + + // 1 to 4 repeaters that could hear a ping at this spot, as (id, snr, rssi). + List<(String, double, int)> heardAt(double lat, double lon) { + final near = repeaters + .map((r) => (r.id, km(lat, lon, r.lat, r.lon))) + .where((e) => e.$2 < 12) + .toList() + ..sort((a, b) => a.$2.compareTo(b.$2)); + final n = 1 + rnd.nextInt(4); + final List<(String, double)> picks; + if (near.isNotEmpty) { + picks = near.take(n).toList(); + } else { + final start = rnd.nextInt(storeCaptureFallbackIds.length); + picks = [ + for (var i = 0; i < n; i++) + ( + storeCaptureFallbackIds[ + (start + i) % storeCaptureFallbackIds.length], + 1.0 + i * 2.5, + ), + ]; + } + return picks.map((e) { + final snr = (11 - e.$2 * 1.6 + rnd.nextDouble() * 3) + .clamp(-14.0, 12.0) + .toDouble(); + final rssi = (-58 - e.$2 * 6 - rnd.nextInt(8)).round(); + return (e.$1, double.parse(snr.toStringAsFixed(1)), rssi); + }).toList(); + } + + final txPings = []; + final txLog = []; + final rxPings = []; + final rxLog = []; + + for (var i = 0; i < route.length; i++) { + final (lat, lon) = route[i]; + final ts = newest.subtract(Duration(seconds: (last - i) * 22)); + // The draw is always taken so the stream stays the same whatever is forced. + final draw = rnd.nextDouble(); + final miss = i != last && (draw < 0.1 || i == _forcedMissIndex); + final heard = miss ? <(String, double, int)>[] : heardAt(lat, lon); + txPings.add(TxPing( + latitude: lat, + longitude: lon, + power: 22, + timestamp: ts, + deviceId: _deviceId, + heardRepeaters: [ + for (final h in heard) + HeardRepeater(repeaterId: h.$1, snr: h.$2, rssi: h.$3), + ], + )); + txLog.add(TxLogEntry( + timestamp: ts, + latitude: lat, + longitude: lon, + power: 1.0, + events: [ + for (final h in heard) RxEvent(repeaterId: h.$1, snr: h.$2, rssi: h.$3), + ], + )); + + // An RX heard midway to the next point, 9 s after this one. + if (i % 3 == 1) { + final h = heardAt(lat, lon).first; + final rts = ts.add(const Duration(seconds: 9)); + final (nLat, nLon) = route[math.min(i + 1, last)]; + final rLat = (lat + nLat) / 2; + final rLon = (lon + nLon) / 2; + rxPings.add(RxPing( + latitude: rLat, + longitude: rLon, + repeaterId: h.$1, + timestamp: rts, + snr: h.$2, + rssi: h.$3, + )); + rxLog.add(RxLogEntry( + timestamp: rts, + repeaterId: h.$1, + snr: h.$2, + rssi: h.$3, + pathLength: 0, + header: 0, + latitude: rLat, + longitude: rLon, + )); + } + } + + final (dLat, dLon) = route[20]; + final disc = [ + DiscLogEntry( + timestamp: newest.subtract(const Duration(minutes: 9)), + latitude: dLat, + longitude: dLon, + noiseFloor: -111, + discoveredNodes: [ + for (final h in heardAt(dLat, dLon)) + DiscoveredNodeEntry( + repeaterId: h.$1, + nodeType: 'REPEATER', + localSnr: h.$2, + localRssi: h.$3, + remoteSnr: h.$2 - 1.5, + ), + ], + ), + ]; + + final (tLat, tLon) = route[34]; + final th = heardAt(tLat, tLon).first; + final trace = [ + TraceLogEntry( + timestamp: newest.subtract(const Duration(minutes: 4)), + latitude: tLat, + longitude: tLon, + targetRepeaterId: th.$1, + noiseFloor: -110, + localSnr: th.$2, + remoteSnr: th.$2 - 2, + localRssi: th.$3, + success: true, + ), + ]; + + // Four finished sessions on the days before, newest first. + const modes = ['active', 'hybrid', 'passive', 'active']; + final sessions = []; + for (var s = 0; s < modes.length; s++) { + final start = newest.subtract(Duration(days: s + 1, hours: 2 + s * 3)); + final mins = 18 + s * 11; + final samples = []; + for (var k = 0; k < mins * 6; k++) { + final bump = (k % 90 > 70) ? 6 : 0; + samples.add(NoiseFloorSample( + timestamp: start.add(Duration(seconds: k * 10)), + noiseFloor: -112 + rnd.nextInt(5) + bump, + )); + } + final markers = []; + for (var k = 0; k < mins; k++) { + final (lat, lon) = route[(k * 2 + s * 5) % route.length]; + final ok = rnd.nextDouble() > 0.15; + markers.add(PingEventMarker( + timestamp: start.add(Duration(minutes: k)), + type: ok + ? (k % 4 == 0 ? PingEventType.rx : PingEventType.txSuccess) + : PingEventType.txFail, + noiseFloor: -111 + rnd.nextInt(4), + latitude: lat, + longitude: lon, + repeaters: ok + ? [ + for (final h in heardAt(lat, lon)) + MarkerRepeaterInfo(repeaterId: h.$1, snr: h.$2, rssi: h.$3), + ] + : null, + )); + } + sessions.add(NoiseFloorSession( + id: 'store-capture-$s', + startTime: start, + endTime: start.add(Duration(minutes: mins)), + mode: modes[s], + samples: samples, + markers: markers, + )); + } + + return StoreCaptureSample( + txPings: txPings, + txLog: txLog, + rxPings: rxPings, + rxLog: rxLog, + disc: disc, + trace: trace, + sessions: sessions, + stats: PingStats( + txCount: txPings.length, + rxCount: rxPings.length, + discCount: disc.length, + traceCount: trace.length, + successfulUploads: txPings.length + rxPings.length, + ), + noiseFloor: -109, + batteryPercent: 86, + ); +} diff --git a/lib/debug/store_capture_route.dart b/lib/debug/store_capture_route.dart new file mode 100644 index 00000000..2721a32a --- /dev/null +++ b/lib/debug/store_capture_route.dart @@ -0,0 +1,49 @@ +// Recorded street route through downtown Ottawa (OSRM, OpenStreetMap data), +// resampled every 35 m and cut before the final turn. Last point = GPS arrow. +const List<(double, double)> storeCaptureRoute = [ + (45.416821, -75.706822), + (45.417053, -75.706996), + (45.416887, -75.707378), + (45.416718, -75.707757), + (45.416550, -75.708137), + (45.416375, -75.708511), + (45.416102, -75.708463), + (45.415811, -75.708292), + (45.415803, -75.707988), + (45.415969, -75.707607), + (45.416135, -75.707225), + (45.416301, -75.706843), + (45.416466, -75.706461), + (45.416632, -75.706078), + (45.416798, -75.705696), + (45.416963, -75.705314), + (45.417127, -75.704930), + (45.417292, -75.704547), + (45.417456, -75.704163), + (45.417619, -75.703779), + (45.417781, -75.703394), + (45.417943, -75.703008), + (45.418105, -75.702623), + (45.418274, -75.702244), + (45.418444, -75.701865), + (45.418609, -75.701483), + (45.418775, -75.701100), + (45.418941, -75.700719), + (45.419107, -75.700337), + (45.419272, -75.699954), + (45.419438, -75.699572), + (45.419603, -75.699189), + (45.419768, -75.698806), + (45.419933, -75.698423), + (45.420098, -75.698041), + (45.420110, -75.697711), + (45.419841, -75.697477), + (45.419572, -75.697243), + (45.419411, -75.696972), + (45.419570, -75.696584), + (45.419729, -75.696196), + (45.419888, -75.695808), + (45.420048, -75.695421), + (45.420207, -75.695033), + (45.420368, -75.694647), +]; diff --git a/lib/main.dart b/lib/main.dart index 98cf00f0..607c9b76 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,9 +4,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart' as fbp; import 'package:hive_flutter/hive_flutter.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; +import 'debug/store_capture.dart'; import 'models/noise_floor_session.dart'; import 'providers/app_state_provider.dart'; import 'screens/main_scaffold.dart'; @@ -23,18 +25,31 @@ import 'utils/debug_logger_io.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); + // Debug builds only: a store_capture.json in the documents directory turns + // on the sample-drive mode used for store screenshots. + if (kDebugMode && !kIsWeb) { + try { + StoreCaptureConfig.active = await StoreCaptureConfig.load( + await getApplicationDocumentsDirectory()); + } catch (e) { + // No documents directory: capture mode is simply off. + debugPrint('[CAPTURE] Could not look for $storeCaptureFileName: $e'); + } + } + + // Hold every startup line in memory until the stored preference says + // whether a log file should exist at all. Opening one here and closing it + // when the preference read off left a stub file on every launch. + if (!kIsWeb) { + DebugFileLogger.beginCapture(); + } + // Before anything slow. A watch command can launch this process, and the // native relay fires as soon as WatchConnectivity delivers — long before the // provider finishes initializing and starts listening. WatchBridgeService.reserveCommandQueue(); AppIntentBridgeService.reserveCommandQueue(); - // Enable debug file logging FIRST on mobile to capture early logs - // This must happen before DebugLogger.initialize() to capture early logs - if (!kIsWeb) { - await DebugFileLogger.enable(); - } - // Initialize debug logger (checks for ?debug=1 URL param on web) DebugLogger.initialize(); debugLog('[APP] MeshMapper starting...'); @@ -43,9 +58,25 @@ void main() async { await Hive.initFlutter(); debugLog('[APP] Hive initialized'); - // Load theme preference BEFORE runApp to avoid flash of wrong theme - final initialThemeMode = await _loadInitialThemeMode(); + // Load the theme preference BEFORE runApp to avoid a flash of the wrong + // theme, and the debug log preference so the first file is only created + // when the user wants one. + final startupPrefs = await _loadStartupPreferences(); + final initialThemeMode = startupPrefs.themeMode; debugLog('[APP] Initial theme mode: $initialThemeMode'); + if (!kIsWeb) { + if (startupPrefs.debugLogsEnabled) { + try { + await DebugFileLogger.enable(); + } catch (e) { + // The provider reconciles later; startup must not die on a log file. + DebugFileLogger.discardCapture(); + debugPrint('[DEBUG] Could not open the debug log file: $e'); + } + } else { + DebugFileLogger.discardCapture(); + } + } // Register noise floor session adapters before opening any boxes // Note: MarkerRepeaterInfo (14) must be registered before PingEventMarker (12) @@ -86,25 +117,32 @@ void main() async { runApp(MeshMapperApp(initialThemeMode: initialThemeMode)); } -/// Load theme mode from Hive before app starts to avoid flash of wrong theme -Future _loadInitialThemeMode() async { +/// The two preferences main needs before runApp, read from one box open: +/// the theme (to avoid a flash) and whether to write a debug log file at all. +/// Defaults are dark and on; a Hive failure keeps them. +Future<({String themeMode, bool debugLogsEnabled})> + _loadStartupPreferences() async { + var themeMode = 'dark'; + var debugLogsEnabled = true; try { final box = await Hive.openBox('user_preferences') .timeout(const Duration(seconds: 5)); final json = box.get('preferences'); if (json != null && json is Map) { - final themeMode = json['themeMode'] as String?; - if (themeMode != null) { - return themeMode; + final stored = json['themeMode'] as String?; + if (stored != null) { + themeMode = stored; } } + debugLogsEnabled = + DebugFileLogger.wantsFileLogging(box.get('debug_logs_enabled')); } catch (e) { - debugLog('[HIVE] Initial theme load failed (non-fatal): $e'); + debugLog('[HIVE] Startup preference load failed (non-fatal): $e'); // Do NOT delete the box here. A transient open timeout would wipe every // saved setting. AppStateProvider's _attemptHiveRecovery handles real // corruption later with a user-visible logError() notification. } - return 'dark'; // Default to dark mode + return (themeMode: themeMode, debugLogsEnabled: debugLogsEnabled); } /// Request all required permissions on app startup diff --git a/lib/models/api_queue_item.dart b/lib/models/api_queue_item.dart index 6eacc255..b28f592d 100644 --- a/lib/models/api_queue_item.dart +++ b/lib/models/api_queue_item.dart @@ -1,5 +1,7 @@ import 'package:hive/hive.dart'; +import '../utils/public_key.dart'; + part 'api_queue_item.g.dart'; /// Item in the API upload queue @@ -17,7 +19,7 @@ part 'api_queue_item.g.dart'; @HiveType(typeId: 3) class ApiQueueItem extends HiveObject { @HiveField(0) - final String type; // 'TX', 'RX', 'DISC', 'TRACE' or 'DEFER' + final String type; // 'TX', 'RX', 'DISC', 'TRACE', 'DEFER' or 'SCOPES' @HiveField(1) final double latitude; @@ -65,10 +67,9 @@ class ApiQueueItem extends HiveObject { final String? wireTag; /// Altitude of the fix in meters, null when the phone did not know it. - /// iOS reports height above mean sea level. Android usually reports height - /// above the WGS84 ellipsoid, but Android 14+ substitutes mean sea level - /// when the fix carries it, so one device can report either. The two differ - /// by the local geoid separation (up to ~100 m). + /// Uploaded ONLY together with [altitudeRef]: an altitude whose reference + /// is not proved is stored but never emitted. Contract: + /// MeshMapper_Server/docs/APP_API.md. @HiveField(18) final double? altitude; @@ -90,6 +91,26 @@ class ApiQueueItem extends HiveObject { @HiveField(20) final String? radioFreq; + /// A repeater's scope discovery answer, sent only for a SCOPES item. The + /// list is exactly what the repeater sent (case kept, `*` kept, at most + /// 33 entries, may be empty). Null for every other type. The answering + /// repeater's public key rides in [heardRepeats] instead, the DISC/DEFER + /// packing precedent, since a list needs its own field. + @HiveField(21) + final List? scopes; + + /// The vertical reference [altitude] is measured from, `msl` (above mean + /// sea level) or `ellipsoid` (above the WGS84 ellipsoid). Null when the + /// app could not prove it, in which case [toApiJson] emits no altitude. + @HiveField(22) + final String? altitudeRef; + + /// Vertical accuracy of the fix in meters, about one standard deviation. + /// Null when the phone did not know it. Emitted only beside a labelled + /// altitude and only when finite and above zero. + @HiveField(23) + final double? altitudeAccuracy; + ApiQueueItem({ required this.type, required this.latitude, @@ -105,8 +126,11 @@ class ApiQueueItem extends HiveObject { this.pingCounter, this.wireTag, this.altitude, + this.altitudeRef, + this.altitudeAccuracy, this.autoMode, this.radioFreq, + this.scopes, }); /// Create from TX ping @@ -122,6 +146,8 @@ class ApiQueueItem extends HiveObject { int? pingCounter, String? wireTag, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, String? autoMode, String? radioFreq, }) { @@ -139,6 +165,8 @@ class ApiQueueItem extends HiveObject { pingCounter: pingCounter, wireTag: wireTag, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoMode, radioFreq: radioFreq, ); @@ -155,6 +183,8 @@ class ApiQueueItem extends HiveObject { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, String? autoMode, String? radioFreq, }) { @@ -169,6 +199,8 @@ class ApiQueueItem extends HiveObject { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoMode, radioFreq: radioFreq, ); @@ -190,6 +222,8 @@ class ApiQueueItem extends HiveObject { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, String? autoMode, String? radioFreq, }) { @@ -207,6 +241,8 @@ class ApiQueueItem extends HiveObject { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoMode, radioFreq: radioFreq, ); @@ -226,6 +262,8 @@ class ApiQueueItem extends HiveObject { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, String? autoMode, String? radioFreq, }) { @@ -242,6 +280,8 @@ class ApiQueueItem extends HiveObject { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoMode, radioFreq: radioFreq, ); @@ -256,6 +296,8 @@ class ApiQueueItem extends HiveObject { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, String? autoMode, String? radioFreq, }) { @@ -270,6 +312,8 @@ class ApiQueueItem extends HiveObject { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoMode, radioFreq: radioFreq, ); @@ -299,8 +343,79 @@ class ApiQueueItem extends HiveObject { ); } + /// A repeater's answer to a direct scope discovery question, sent only + /// after a discovery found it. The public key rides in [heardRepeats] + /// (the DISC/DEFER packing precedent); the answer itself needs its own + /// field since a list cannot be squeezed safely into that string. Never + /// stamped with the auto mode, the DEFER precedent again: this is a + /// repeater fact, not a session-mode analytics stamp. + /// + /// [publicKeyHex] is normalized to 64 upper-case hex via + /// [normalizePublicKey], so the item never serializes any other shape. + /// Anything that does not normalize throws [ArgumentError]: the server + /// would reject the whole item, and a caller that can meet a bad key + /// (`ApiQueueService.enqueueScopes` does) validates it first and refuses + /// it without building the item. + factory ApiQueueItem.fromScopes({ + required String publicKeyHex, + required List scopes, + required double lat, + required double lon, + required int timestamp, + String? radioFreq, + }) { + final key = normalizePublicKey(publicKeyHex); + if (key == null) { + throw ArgumentError.value(publicKeyHex, 'publicKeyHex', + 'must be a 64 hex character public key'); + } + return ApiQueueItem( + type: 'SCOPES', + latitude: lat, + longitude: lon, + timestamp: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), + heardRepeats: key, + canUploadAfter: DateTime.now().millisecondsSinceEpoch, // Immediate + externalAntenna: false, + scopes: scopes, + radioFreq: radioFreq, + ); + } + /// Convert to API JSON format (matches WebClient exactly) + /// The altitude trio, or nothing. An altitude is never emitted without its + /// reference, and the accuracy only beside both and when usable. The + /// enqueue paths already pass null for all three when the reference is + /// unknown; this gate makes sure neither side alone can leak a bare value. + Map get _altitudeFields { + final meters = altitude; + final ref = altitudeRef; + if (meters == null || ref == null) return const {}; + final acc = altitudeAccuracy; + return { + 'altitude': meters.round(), + 'altitude_ref': ref, + if (acc != null && acc.isFinite && acc > 0) 'altitude_acc': acc.round(), + }; + } + Map toApiJson() { + // A repeater's scope answer: public key, the scopes exactly as heard, + // when the answer arrived, and where the discovery that found it was + // made. Never the mode stamp and never external_antenna/noisefloor/ + // altitude/power, the DEFER precedent. + if (type == 'SCOPES') { + return { + 'type': type, + 'public_key': heardRepeats, + 'scopes': scopes ?? const [], + 'timestamp': timestamp.millisecondsSinceEpoch ~/ 1000, + 'lat': latitude, + 'lon': longitude, + if (radioFreq != null) 'radio_freq': radioFreq, + }; + } + // A deferral carries only the square and which kind of ping was held. // Never the mode stamp (the server stores none for a deferral), but the // radio tag rides along. @@ -334,7 +449,7 @@ class ApiQueueItem extends HiveObject { 'timestamp': timestamp.millisecondsSinceEpoch ~/ 1000, 'external_antenna': externalAntenna, 'power': power != null ? '${power!.toStringAsFixed(1)}w' : null, - if (altitude != null) 'altitude': altitude!.round(), + ..._altitudeFields, if (autoMode != null) 'auto_mode': autoMode, if (radioFreq != null) 'radio_freq': radioFreq, }; @@ -353,7 +468,7 @@ class ApiQueueItem extends HiveObject { 'timestamp': timestamp.millisecondsSinceEpoch ~/ 1000, 'external_antenna': externalAntenna, 'power': power != null ? '${power!.toStringAsFixed(1)}w' : null, - if (altitude != null) 'altitude': altitude!.round(), + ..._altitudeFields, if (autoMode != null) 'auto_mode': autoMode, if (radioFreq != null) 'radio_freq': radioFreq, }; @@ -376,7 +491,7 @@ class ApiQueueItem extends HiveObject { 1000, // Unix timestamp in seconds 'external_antenna': externalAntenna, 'power': power != null ? '${power!.toStringAsFixed(1)}w' : null, - if (altitude != null) 'altitude': altitude!.round(), + ..._altitudeFields, if (autoMode != null) 'auto_mode': autoMode, if (radioFreq != null) 'radio_freq': radioFreq, }; @@ -396,8 +511,8 @@ class ApiQueueItem extends HiveObject { // absence (coords mode / RX) is the unchanged-from-today coords path. if (pingCounter != null) 'ping_counter': pingCounter, if (wireTag != null) 'wire_tag': wireTag, - // Whole meters, omitted when the phone did not know its altitude. - if (altitude != null) 'altitude': altitude!.round(), + // Altitude, its reference and its accuracy together, or nothing. + ..._altitudeFields, if (autoMode != null) 'auto_mode': autoMode, if (radioFreq != null) 'radio_freq': radioFreq, }; diff --git a/lib/models/log_entry.dart b/lib/models/log_entry.dart index d8022b16..bb460195 100644 --- a/lib/models/log_entry.dart +++ b/lib/models/log_entry.dart @@ -1,3 +1,5 @@ +import 'scope_log_entry.dart'; + /// TX Log Entry /// Reference: txLogState in wardrive.js class TxLogEntry { @@ -221,7 +223,7 @@ enum SnrSeverity { } /// Ping type for unified log view -enum PingLogType { tx, rx, disc, trace } +enum PingLogType { tx, rx, disc, trace, scopes } /// Wrapper for unified chronological ping log view class UnifiedPingLogEntry implements Comparable { @@ -236,6 +238,7 @@ class UnifiedPingLogEntry implements Comparable { RxLogEntry get asRx => entry as RxLogEntry; DiscLogEntry get asDisc => entry as DiscLogEntry; TraceLogEntry get asTrace => entry as TraceLogEntry; + ScopeLogEntry get asScopes => entry as ScopeLogEntry; @override int compareTo(UnifiedPingLogEntry other) => @@ -246,6 +249,7 @@ class UnifiedPingLogEntry implements Comparable { PingLogType.rx => asRx.timeString, PingLogType.disc => asDisc.timeString, PingLogType.trace => asTrace.timeString, + PingLogType.scopes => asScopes.timeString, }; String get locationString => switch (type) { @@ -253,6 +257,7 @@ class UnifiedPingLogEntry implements Comparable { PingLogType.rx => asRx.locationString, PingLogType.disc => asDisc.locationString, PingLogType.trace => asTrace.locationString, + PingLogType.scopes => asScopes.locationString, }; String toCsv() => switch (type) { @@ -260,9 +265,36 @@ class UnifiedPingLogEntry implements Comparable { PingLogType.rx => 'RX,${asRx.toCsv()}', PingLogType.disc => 'DISC,${asDisc.toCsv()}', PingLogType.trace => 'TRC,${asTrace.toCsv()}', + PingLogType.scopes => 'SCOPES,${asScopes.toCsv()}', }; } +/// Merges every per-type log list into one chronological (newest first) view. +/// The single place `AppStateProvider.unifiedPingLogEntries` builds from, so +/// the merge order is testable without the provider. +List mergeUnifiedPingLog({ + required List tx, + required List rx, + required List disc, + required List trace, + required List scopes, +}) { + final merged = [ + ...tx.map((e) => UnifiedPingLogEntry( + type: PingLogType.tx, timestamp: e.timestamp, entry: e)), + ...rx.map((e) => UnifiedPingLogEntry( + type: PingLogType.rx, timestamp: e.timestamp, entry: e)), + ...disc.map((e) => UnifiedPingLogEntry( + type: PingLogType.disc, timestamp: e.timestamp, entry: e)), + ...trace.map((e) => UnifiedPingLogEntry( + type: PingLogType.trace, timestamp: e.timestamp, entry: e)), + ...scopes.map((e) => UnifiedPingLogEntry( + type: PingLogType.scopes, timestamp: e.timestamp, entry: e)), + ]; + merged.sort(); + return merged; +} + /// User Error Entry for error log class UserErrorEntry { final DateTime timestamp; diff --git a/lib/models/map_view_state.dart b/lib/models/map_view_state.dart new file mode 100644 index 00000000..96e4fcdd --- /dev/null +++ b/lib/models/map_view_state.dart @@ -0,0 +1,138 @@ +/// How the user last left the map screen: the camera zoom and which panels +/// were folded away. Restored on the next launch so the map comes back the way +/// it was left. +/// +/// Stored as its own key (`map_view_state`) in the `user_preferences` Hive box, +/// beside `preferences` rather than inside it, because it is screen state that +/// changes during a pinch: a write here must not run the settings save path or +/// notify anything that keys on [UserPreferences]. +/// +/// Only lasting state lives here. A focus camera on a tapped ping or cell, the +/// history session view and a log-screen jump are transient and never recorded. +class MapViewState { + /// Lowest zoom the map allows (matches the map's `minMaxZoomPreference`). + static const double minZoom = 3.0; + + /// Highest zoom the map allows: 17 nudged off the integer, because MapLibre + /// blinks labels when the camera settles on an integer zoom. + static const double maxZoom = 17.0 - zoomEpsilon; + + /// The nudge applied to every programmatic zoom (see [maxZoom]). + static const double zoomEpsilon = 0.001; + + /// Smallest zoom change worth a write. Auto-follow animates the camera on + /// every GPS tick and each one ends in a camera-idle at the same zoom. + static const double zoomSaveThreshold = 0.01; + + /// Last zoom the user left the map at; null until one has been recorded, in + /// which case the map keeps its first-launch zooms. + final double? zoom; + + /// The control panel (portrait bottom card, landscape side card) is folded to + /// its compact strip. Shared by both orientations. + final bool controlsMinimized; + + /// Landscape only: the control panel is shown at all (closed = a small + /// Controls button). + final bool controlPanelShown; + + /// Landscape only: the map's control column is open. + final bool landscapeMapControlsExpanded; + + /// Portrait only: the map's control column on the right is open. + final bool mapControlsExpanded; + + const MapViewState({ + this.zoom, + this.controlsMinimized = false, + this.controlPanelShown = true, + this.landscapeMapControlsExpanded = false, + this.mapControlsExpanded = true, + }); + + /// Read a stored value back. Anything missing or malformed falls back to the + /// first-launch default for that field, so a bad entry never throws. + factory MapViewState.fromStored(Object? stored) { + if (stored is! Map) return const MapViewState(); + bool flag(String key, bool fallback) { + final v = stored[key]; + return v is bool ? v : fallback; + } + + return MapViewState( + zoom: clampZoom(stored['zoom']), + controlsMinimized: flag('controlsMinimized', false), + controlPanelShown: flag('controlPanelShown', true), + landscapeMapControlsExpanded: + flag('landscapeMapControlsExpanded', false), + mapControlsExpanded: flag('mapControlsExpanded', true), + ); + } + + /// The value written to Hive. + Map toStorage() => { + if (zoom != null) 'zoom': zoom, + 'controlsMinimized': controlsMinimized, + 'controlPanelShown': controlPanelShown, + 'landscapeMapControlsExpanded': landscapeMapControlsExpanded, + 'mapControlsExpanded': mapControlsExpanded, + }; + + /// A zoom the map can safely be handed: null for anything not a finite + /// number, otherwise clamped to [minZoom]..[maxZoom] and nudged off an + /// integer by [zoomEpsilon]. + static double? clampZoom(Object? value) { + if (value is! num || !value.isFinite) return null; + var z = value.toDouble().clamp(minZoom, maxZoom).toDouble(); + if ((z - z.roundToDouble()).abs() < zoomEpsilon / 2) { + z = z.roundToDouble() - zoomEpsilon; + if (z < minZoom) z = minZoom + zoomEpsilon; + } + return z; + } + + /// Whether a camera at [current] differs enough from the remembered zoom to + /// be worth recording. + static bool zoomWorthSaving(double? remembered, double current) { + if (!current.isFinite) return false; + if (remembered == null) return true; + return (current - remembered).abs() >= zoomSaveThreshold; + } + + MapViewState copyWith({ + double? zoom, + bool? controlsMinimized, + bool? controlPanelShown, + bool? landscapeMapControlsExpanded, + bool? mapControlsExpanded, + }) { + return MapViewState( + zoom: zoom ?? this.zoom, + controlsMinimized: controlsMinimized ?? this.controlsMinimized, + controlPanelShown: controlPanelShown ?? this.controlPanelShown, + landscapeMapControlsExpanded: + landscapeMapControlsExpanded ?? this.landscapeMapControlsExpanded, + mapControlsExpanded: mapControlsExpanded ?? this.mapControlsExpanded, + ); + } + + @override + bool operator ==(Object other) => + other is MapViewState && + other.zoom == zoom && + other.controlsMinimized == controlsMinimized && + other.controlPanelShown == controlPanelShown && + other.landscapeMapControlsExpanded == landscapeMapControlsExpanded && + other.mapControlsExpanded == mapControlsExpanded; + + @override + int get hashCode => Object.hash(zoom, controlsMinimized, controlPanelShown, + landscapeMapControlsExpanded, mapControlsExpanded); + + @override + String toString() => 'MapViewState(zoom=${zoom?.toStringAsFixed(2)}, ' + 'controlsMinimized=$controlsMinimized, ' + 'controlPanelShown=$controlPanelShown, ' + 'landscapeMapControlsExpanded=$landscapeMapControlsExpanded, ' + 'mapControlsExpanded=$mapControlsExpanded)'; +} diff --git a/lib/models/ping_data.dart b/lib/models/ping_data.dart index 09defe62..7f8ac6ce 100644 --- a/lib/models/ping_data.dart +++ b/lib/models/ping_data.dart @@ -148,6 +148,13 @@ class PingStats { final int rxCount; final int discCount; // Discovery count (Passive Mode) final int traceCount; // Trace count (Targeted Mode) + + /// Scope requests a repeater answered with its scope list (Passive/Hybrid + /// scope discovery), one per answering repeater, counted whether or not the + /// hourly cap let the answer upload. Lives here, not on the scope log, so + /// it resets with TX/DISC/Trace (`PingService.resetStats`, a new + /// connection) and is not cut by Clear logs or the log's 500-entry cap. + final int scopeCount; final int successfulUploads; final int failedUploads; final int queuedCount; @@ -157,6 +164,7 @@ class PingStats { this.rxCount = 0, this.discCount = 0, this.traceCount = 0, + this.scopeCount = 0, this.successfulUploads = 0, this.failedUploads = 0, this.queuedCount = 0, @@ -167,6 +175,7 @@ class PingStats { int? rxCount, int? discCount, int? traceCount, + int? scopeCount, int? successfulUploads, int? failedUploads, int? queuedCount, @@ -176,6 +185,7 @@ class PingStats { rxCount: rxCount ?? this.rxCount, discCount: discCount ?? this.discCount, traceCount: traceCount ?? this.traceCount, + scopeCount: scopeCount ?? this.scopeCount, successfulUploads: successfulUploads ?? this.successfulUploads, failedUploads: failedUploads ?? this.failedUploads, queuedCount: queuedCount ?? this.queuedCount, diff --git a/lib/models/repeater.dart b/lib/models/repeater.dart index 1d317530..ede3f35f 100644 --- a/lib/models/repeater.dart +++ b/lib/models/repeater.dart @@ -1,5 +1,7 @@ import 'package:intl/intl.dart'; +import 'repeater_scope.dart'; + /// Represents a repeater from the MeshMapper API. /// Used to display repeater markers on the map. class Repeater { @@ -80,6 +82,40 @@ class Repeater { /// never polled. final double? backboneShare; + /// When the server last asked this repeater for its scopes, across every + /// phone (Unix seconds), or null when it has never been asked or the + /// server predates the field. Read by `isScopeQueryDue`'s server-side rule + /// so a repeater the server already checked recently is not asked again + /// just because this phone has no cached answer of its own. Non-numeric or + /// missing reads null, never logged: an ordinary case for an older server + /// or a repeater this feature has not reached yet. + final int? scopesCheckedAt; + + /// The scopes the server has confirmed for this repeater, one entry per + /// name with the time each source last confirmed it. Empty when the server + /// knows none or predates the field. Shown as the detail sheet's Scopes row + /// through [repeaterScopeChips]; never logged. + final List scopes; + + /// The repeater's default scope, read together: [defaultScopeState] is + /// `named` (with [defaultScope] set), `none` (the default is `*`), + /// `unknown` (an advert default the map has not confirmed yet) or null + /// (never learned, or an older server). [defaultScopeAt] is when it was + /// learned and [defaultScopeSrc] how (`advert` or `reported`). + final String? defaultScope; + final String? defaultScopeState; + final int? defaultScopeAt; + final String? defaultScopeSrc; + + /// The Scopes row's chips, in display order. Empty means no row. + List get scopeChips => repeaterScopeChips( + scopes: scopes, + defaultScope: defaultScope, + defaultScopeState: defaultScopeState, + defaultScopeAt: defaultScopeAt, + defaultScopeSrc: defaultScopeSrc, + ); + /// The site details an administrator fills in about their installation. /// Every one is additive, optional and free text the server does not /// validate, so they are null on most repeaters and on any server that @@ -132,6 +168,12 @@ class Repeater { this.admins = const [], this.backbone = false, this.backboneShare, + this.scopesCheckedAt, + this.scopes = const [], + this.defaultScope, + this.defaultScopeState, + this.defaultScopeAt, + this.defaultScopeSrc, this.hardware, this.antenna, this.heightMeters, @@ -192,6 +234,23 @@ class Repeater { final backboneShare = shareValue == null || !shareValue.isFinite ? null : shareValue.toDouble(); + // Non-numeric or missing is null, never logged: an older server simply + // predates the field, and a repeater this feature has not reached yet is + // the expected common case. + final rawScopesCheckedAt = json['scopes_checked_at']; + final scopesCheckedAt = rawScopesCheckedAt is int + ? rawScopesCheckedAt + : rawScopesCheckedAt is num + ? rawScopesCheckedAt.toInt() + : null; + + final rawDefaultScopeAt = json['default_scope_at']; + final defaultScopeAt = rawDefaultScopeAt is num && rawDefaultScopeAt.isFinite + ? rawDefaultScopeAt.toInt() + : rawDefaultScopeAt is String + ? int.tryParse(rawDefaultScopeAt.trim()) + : null; + final rawHopBytes = json['hop_bytes']; final hopBytes = rawHopBytes is num ? rawHopBytes.toInt() @@ -243,6 +302,12 @@ class Repeater { admins: admins, backbone: backbone, backboneShare: backboneShare, + scopesCheckedAt: scopesCheckedAt, + scopes: RepeaterScope.listFromJson(json['scopes']), + defaultScope: text('default_scope'), + defaultScopeState: text('default_scope_state'), + defaultScopeAt: defaultScopeAt, + defaultScopeSrc: text('default_scope_src'), hardware: text('hardware'), antenna: text('antenna'), heightMeters: heightMeters, @@ -274,6 +339,13 @@ class Repeater { // means not backbone" shape the server sends. if (backbone) 'backbone': 1, if (backboneShare != null) 'backbone_share': backboneShare, + if (scopesCheckedAt != null) 'scopes_checked_at': scopesCheckedAt, + if (scopes.isNotEmpty) + 'scopes': scopes.map((s) => s.toJson()).toList(), + if (defaultScope != null) 'default_scope': defaultScope, + if (defaultScopeState != null) 'default_scope_state': defaultScopeState, + if (defaultScopeAt != null) 'default_scope_at': defaultScopeAt, + if (defaultScopeSrc != null) 'default_scope_src': defaultScopeSrc, // Same rule for the site details: absent means "not filled in", so an // unset one must not come back as an explicit null. if (hardware != null) 'hardware': hardware, @@ -427,6 +499,12 @@ class Repeater { List? admins, bool? backbone, double? backboneShare, + int? scopesCheckedAt, + List? scopes, + String? defaultScope, + String? defaultScopeState, + int? defaultScopeAt, + String? defaultScopeSrc, String? hardware, String? antenna, double? heightMeters, @@ -453,6 +531,12 @@ class Repeater { admins: admins ?? this.admins, backbone: backbone ?? this.backbone, backboneShare: backboneShare ?? this.backboneShare, + scopesCheckedAt: scopesCheckedAt ?? this.scopesCheckedAt, + scopes: scopes ?? this.scopes, + defaultScope: defaultScope ?? this.defaultScope, + defaultScopeState: defaultScopeState ?? this.defaultScopeState, + defaultScopeAt: defaultScopeAt ?? this.defaultScopeAt, + defaultScopeSrc: defaultScopeSrc ?? this.defaultScopeSrc, hardware: hardware ?? this.hardware, antenna: antenna ?? this.antenna, heightMeters: heightMeters ?? this.heightMeters, diff --git a/lib/models/repeater_scope.dart b/lib/models/repeater_scope.dart new file mode 100644 index 00000000..cd422537 --- /dev/null +++ b/lib/models/repeater_scope.dart @@ -0,0 +1,239 @@ +/// A repeater's scopes as the server's repeater list reports them, and the +/// pure rule that turns them into the chips the repeater detail sheet shows. +/// +/// The list carries `scopes`, one entry per scope name with the time each +/// source last confirmed it (seen forwarding, reported to an observer, +/// uploaded by a wardriver's app), and the repeater's default scope as four +/// additive `default_scope*` fields. Everything is optional: an older server +/// sends none of it and the sheet then shows no Scopes row at all. +/// +/// Ported from the web popup's chip strip (`mmScopeChipsHtml` in the server's +/// `dev/index.php`) so the app and the web answer the same way for the same +/// repeater. `*` means "no scope set", never a wildcard, so it reads +/// "Not set" and is never labelled "all". +library; + +import '../utils/repeater_format.dart'; + +/// One scope name and when each source last confirmed it (Unix seconds, +/// null when that source never did). +class RepeaterScope { + /// The scope name exactly as the server sent it, case kept. `*` is the + /// "no scope set" entry. + final String name; + + /// When the repeater was last seen forwarding a packet in this scope. + final int? observedAt; + + /// How many packets it was seen forwarding in this scope. + final int? observedPkts; + + /// What proved the forwarding: `multibyte` (a multibyte path) or the + /// repeater's firmware version. + final String? proof; + + /// When the repeater last reported this scope to a nearby observer. + final int? reportedAt; + + /// When a wardriver's app last uploaded this scope for the repeater. + final int? uploadedAt; + + const RepeaterScope({ + required this.name, + this.observedAt, + this.observedPkts, + this.proof, + this.reportedAt, + this.uploadedAt, + }); + + /// How many of the three sources confirmed this scope. + int get sourceCount => + (observedAt != null ? 1 : 0) + + (reportedAt != null ? 1 : 0) + + (uploadedAt != null ? 1 : 0); + + static int? _int(Object? raw) { + if (raw is int) return raw > 0 ? raw : null; + if (raw is num && raw.isFinite) return raw > 0 ? raw.toInt() : null; + if (raw is String) { + final v = int.tryParse(raw.trim()); + return v != null && v > 0 ? v : null; + } + return null; + } + + /// Reads one entry, or null when it carries no usable name. A missing or + /// non-numeric time reads as "that source never confirmed it". + static RepeaterScope? fromJson(Object? raw) { + if (raw is! Map) return null; + final name = raw['scope']; + if (name is! String || name.trim().isEmpty) return null; + final proof = raw['proof']; + return RepeaterScope( + name: name.trim(), + observedAt: _int(raw['observed_at']), + observedPkts: _int(raw['observed_pkts']), + proof: proof is String && proof.isNotEmpty ? proof : null, + reportedAt: _int(raw['reported_at']), + uploadedAt: _int(raw['uploaded_at']), + ); + } + + /// Reads the `scopes` array. Anything that is not a list is empty, bad + /// entries are skipped, and a repeated name keeps its first entry. + static List listFromJson(Object? raw) { + if (raw is! List) return const []; + final seen = {}; + final out = []; + for (final item in raw) { + final s = fromJson(item); + if (s != null && seen.add(s.name)) out.add(s); + } + return out; + } + + Map toJson() => { + 'scope': name, + 'observed_at': observedAt, + 'observed_pkts': observedPkts, + 'proof': proof, + 'reported_at': reportedAt, + 'uploaded_at': uploadedAt, + }; +} + +/// One chip on the Scopes row. +class RepeaterScopeChip { + /// The text on the chip: the scope name, `Not set` for `*`, or `?` for a + /// default the map has not confirmed yet. + final String label; + + /// Whether this chip carries the default star. + final bool isDefault; + + /// One sentence per thing known about this chip, shown when it is tapped. + final List details; + + /// How many sources confirmed it (0 for a default-only chip). Sort key. + final int sourceCount; + + final String _sortName; + + const RepeaterScopeChip({ + required this.label, + required this.isDefault, + required this.details, + required this.sourceCount, + required String sortName, + }) : _sortName = sortName; +} + +/// How many chips show before the rest fold behind a "+N more" chip. +const int kRepeaterScopeChipsShown = 4; + +String _ago(int ts) { + final a = daysAgo(ts); + if (a.isEmpty) return ''; + return a == 'Today' ? 'today' : a; +} + +/// The Scopes row's chips for one repeater, in display order (the default +/// first, then more sources, then by name). Empty when there is nothing to +/// show, in which case the row is left out. +List repeaterScopeChips({ + required List scopes, + String? defaultScope, + String? defaultScopeState, + int? defaultScopeAt, + String? defaultScopeSrc, +}) { + String fromLine() { + final from = defaultScopeSrc == 'reported' + ? 'its observer report' + : 'its own adverts'; + final when = defaultScopeAt != null ? _ago(defaultScopeAt) : ''; + return 'Default scope, from $from${when.isEmpty ? '' : ', $when'}.'; + } + + String? defName; + var defNone = false; + var defUnknown = false; + if (defaultScopeState == 'named' && + defaultScope != null && + defaultScope.trim().isNotEmpty) { + defName = defaultScope.trim(); + } else if (defaultScopeState == 'unknown') { + defUnknown = true; + } else if (defaultScopeState == 'none') { + defNone = true; + } + + final chips = []; + for (final s in scopes) { + final details = []; + final isUnset = s.name == '*'; + if (isUnset) { + details.add('Passes messages that have no scope set. A message tagged ' + 'with a scope this repeater is not configured for is dropped.'); + } + if (s.observedAt != null) { + final pk = s.observedPkts ?? 0; + final proof = s.proof == 'multibyte' + ? 'a multibyte path' + : 'its firmware version'; + final when = _ago(s.observedAt!); + details.add('Seen forwarding $pk packet${pk == 1 ? '' : 's'}' + '${when.isEmpty ? '' : ', last $when'} (proven by $proof).'); + } + if (s.reportedAt != null) { + final when = _ago(s.reportedAt!); + details.add('Reported when a nearby observer asked it' + '${when.isEmpty ? '' : ', $when'}.'); + } + if (s.uploadedAt != null) { + final when = _ago(s.uploadedAt!); + details.add("Uploaded by a wardriver's app" + '${when.isEmpty ? '' : ', $when'}.'); + } + final isDefault = (defName != null && s.name == defName) || + (defNone && isUnset); + if (isDefault) details.insert(isUnset ? 1 : 0, fromLine()); + chips.add(RepeaterScopeChip( + label: isUnset ? 'Not set' : s.name, + isDefault: isDefault, + details: details, + sourceCount: s.sourceCount, + sortName: s.name, + )); + } + if (defName != null && !scopes.any((s) => s.name == defName)) { + chips.add(RepeaterScopeChip( + label: defName, + isDefault: true, + details: [fromLine()], + sourceCount: 0, + sortName: defName, + )); + } + if (defUnknown) { + chips.add(const RepeaterScopeChip( + label: '?', + isDefault: true, + details: [ + 'This repeater puts a default scope on its adverts that the map has ' + 'not confirmed yet.', + ], + sourceCount: 0, + sortName: '', + )); + } + chips.sort((a, b) { + if (a.isDefault != b.isDefault) return a.isDefault ? -1 : 1; + if (a.sourceCount != b.sourceCount) { + return b.sourceCount.compareTo(a.sourceCount); + } + return a._sortName.toLowerCase().compareTo(b._sortName.toLowerCase()); + }); + return chips; +} diff --git a/lib/models/scope_log_entry.dart b/lib/models/scope_log_entry.dart new file mode 100644 index 00000000..e6f43f8f --- /dev/null +++ b/lib/models/scope_log_entry.dart @@ -0,0 +1,126 @@ +/// What one scope request came to, as the log tab shows it. +/// +/// Only requests a repeater answered or refused are logged. A local failure, +/// an abort, a cancel or the distance gate never reached a repeater and stay +/// debug log lines. +enum ScopeLogOutcome { + /// The repeater answered with its scope list (possibly empty). + answered, + + /// The request went out and no answer came back in time. + noResponse, + + /// The radio flooded the request instead of sending it direct. + flooded, + + /// The repeater answered with something that is not a scope list. + malformed, + + /// The radio refused a step with an error code. + radioError, + + /// The radio refused the send because the repeater is not a saved contact + /// and its contact table is full (companion firmware bug, fixed in + /// v1.17.0). Set only for that exact case; every other ERR is + /// [radioError]. + radioContactsFull, + + /// The repeater answered, but this device's hourly upload cap was full. + withheldHourlyCap, +} + +extension ScopeLogOutcomeLabel on ScopeLogOutcome { + /// The outcome in plain words, as the log card shows it. + String get label => switch (this) { + ScopeLogOutcome.answered => 'Answered', + ScopeLogOutcome.noResponse => 'No response from repeater', + ScopeLogOutcome.flooded => 'Sent as a flood by the radio', + ScopeLogOutcome.malformed => 'Unreadable answer', + ScopeLogOutcome.radioError => 'Radio error', + ScopeLogOutcome.radioContactsFull => 'Radio contact list full', + ScopeLogOutcome.withheldHourlyCap => + 'Not uploaded: hourly limit reached', + }; +} + +/// One scope request in the log. +class ScopeLogEntry { + /// When the outcome was known (the answer's arrival for an answer). + final DateTime timestamp; + + /// The discovery point the repeater was found from. + final double latitude; + final double longitude; + + /// The short repeater id, as the discovery that found it printed it. + final String repeaterId; + + /// The repeater's full public key, upper-case hex. + final String pubkeyHex; + + final ScopeLogOutcome outcome; + + /// The scope names exactly as received, for [ScopeLogOutcome.answered] and + /// [ScopeLogOutcome.withheldHourlyCap]; null otherwise. + final List? scopes; + + const ScopeLogEntry({ + required this.timestamp, + required this.latitude, + required this.longitude, + required this.repeaterId, + required this.pubkeyHex, + required this.outcome, + this.scopes, + }); + + /// Get formatted timestamp (HH:MM:SS) + String get timeString { + return '${timestamp.hour.toString().padLeft(2, '0')}:' + '${timestamp.minute.toString().padLeft(2, '0')}:' + '${timestamp.second.toString().padLeft(2, '0')}'; + } + + /// Get formatted location (5 decimal places) + String get locationString { + return '${latitude.toStringAsFixed(5)},${longitude.toStringAsFixed(5)}'; + } + + /// Get CSV row: timestamp, lat, lon, repeater id, outcome (raw enum name), + /// then the scope names semicolon-joined in one quoted field (empty when + /// [scopes] is null or carries none). + String toCsv() { + final scopesStr = (scopes ?? const []).join(';'); + return '${timestamp.toIso8601String()},$latitude,$longitude,$repeaterId,' + '${outcome.name},"$scopesStr"'; + } +} + +/// The scope log's own list state: newest-first insertion capped at +/// [maxEntries], and a clear. `AppStateProvider` owns one instance and +/// delegates `_addScopeLogEntry`, `clearLogs` and `clearPings` to it, so the +/// add/cap/clear behaviour is unit-testable without constructing the +/// provider, and the provider's three call sites are each one line. +class ScopeLogStore { + /// The most entries kept before the oldest is dropped. + final int maxEntries; + + final List _entries = []; + + ScopeLogStore({this.maxEntries = 500}); + + /// Every logged entry, newest first. + List get entries => List.unmodifiable(_entries); + + /// Inserts [entry] at the front, then drops the oldest entry once the + /// list grows past [maxEntries]. + void add(ScopeLogEntry entry) { + _entries.insert(0, entry); + if (_entries.length > maxEntries) { + _entries.removeLast(); + } + } + + /// Empties the list. Called by `clearLogs` and `clearPings`. + void clear() => _entries.clear(); +} diff --git a/lib/models/user_preferences.dart b/lib/models/user_preferences.dart index a9e10764..1f59a606 100644 --- a/lib/models/user_preferences.dart +++ b/lib/models/user_preferences.dart @@ -1,3 +1,4 @@ +import '../utils/gps_marker_colors.dart'; import '../utils/public_key.dart'; /// User preferences for wardriving configuration @@ -65,9 +66,23 @@ class UserPreferences { /// Smart Pinging window in days ([SmartPingDays.min] to [SmartPingDays.max]). final int smartPingDays; + /// Smart Pinging holds a flood (TX) ping back only for a green square (a + /// heard echo), and never holds a discovery request. Off, a green or cyan + /// square holds both. The region's value wins while it enforces Smart + /// Pinging. + final bool smartPingFloodOnly; + /// Limit the map overlay to the effective Smart Pinging coverage window. final bool smartPingRecentCoverageOnly; + /// Scope discovery: after each discovery sweep, ask the repeaters found for + /// the scopes they carry. See DEVELOPMENT.md "Scope Discovery". + final bool scopeDiscoveryEnabled; + + /// Scope discovery refresh window in days ([ScopeDiscoveryDays.min] to + /// [ScopeDiscoveryDays.max]). + final int scopeDiscoveryDays; + /// Show hollow circle markers on the map where pings were deferred by /// Smart Pinging. final bool showDeferredMarkers; @@ -108,12 +123,26 @@ class UserPreferences { /// Auto-stop auto-ping after 30 minutes of idle (no movement) final bool autoStopAfterIdle; - /// Show top 3 repeaters by SNR on the map during wardriving + /// Show the Top Heard repeaters overlay (best SNR first) on the map during + /// wardriving final bool showTopRepeaters; - /// Double the size of the Top 3 repeaters overlay for easier reading + /// Double the size of the Top Heard overlay for easier reading final bool largerTopRepeaters; + /// Fewest and most rows the Top Heard overlay can show, and the default. + static const int topHeardRowsMin = 3; + static const int topHeardRowsMax = 8; + static const int topHeardRowsDefault = 3; + + /// Rows the in-app Top Heard overlay shows (the RX row is extra). The Live + /// Activity, CarPlay and watch always show 3. + final int topHeardRows; + + /// Top Heard rows with no nickname show the repeater's server name instead + /// of its hex ID. + final bool topHeardShowNames; + /// Live Activity heard rows show resolved repeater names (fewer, named /// rows). When false the card packs a two-column hex grid instead. final bool liveActivityShowNames; @@ -124,6 +153,10 @@ class UserPreferences { /// GPS position marker style (arrow, car, bike, boat, walk) final String gpsMarkerStyle; + /// GPS position marker colour, for every style ('default', 'green'). + /// See [GpsMarkerColors]. + final String gpsMarkerColor; + /// Color vision type for accessibility (none, protanopia, deuteranopia, tritanopia, achromatopsia) final String colorVisionType; @@ -140,6 +173,11 @@ class UserPreferences { /// applied server-side). Only these two values are valid. final int coverageGridSize; + /// Draw a dashed line from a selected repeater to each coverage square that + /// heard it. Off by default: near a busy repeater the lines hide the squares, + /// which already show the coverage. The web keeps them on (`mm_std_repcov`). + final bool showRepeaterCoverageLines; + /// Disconnect alert: play audible alert when pinging stops unexpectedly (BLE disconnect, idle timeout, maintenance) final bool disconnectAlertEnabled; @@ -179,7 +217,10 @@ class UserPreferences { this.hybridModeEnabled = true, this.smartPingEnabled = true, this.smartPingDays = SmartPingDays.defaultDays, + this.smartPingFloodOnly = true, this.smartPingRecentCoverageOnly = false, + this.scopeDiscoveryEnabled = false, + this.scopeDiscoveryDays = ScopeDiscoveryDays.defaultDays, this.showDeferredMarkers = true, this.mapAutoFollow = false, this.mapAlwaysNorth = true, @@ -194,13 +235,17 @@ class UserPreferences { this.autoStopAfterIdle = true, this.showTopRepeaters = false, this.largerTopRepeaters = false, + this.topHeardRows = topHeardRowsDefault, + this.topHeardShowNames = false, this.liveActivityShowNames = true, this.markerStyle = 'dot', this.gpsMarkerStyle = 'arrow', + this.gpsMarkerColor = GpsMarkerColors.defaultChoice, this.colorVisionType = 'none', this.mapTilesEnabled = true, this.coverageOverlayOpacity = 0.7, this.coverageGridSize = 300, + this.showRepeaterCoverageLines = false, this.disconnectAlertEnabled = false, this.customApiEnabled = false, this.customApiUrl, @@ -233,6 +278,7 @@ class UserPreferences { unitSystem: (json['unitSystem'] as String?) ?? 'metric', hybridModeEnabled: (json['hybridModeEnabled'] as bool?) ?? true, smartPingEnabled: (json['smartPingEnabled'] as bool?) ?? true, + smartPingFloodOnly: (json['smartPingFloodOnly'] as bool?) ?? true, smartPingRecentCoverageOnly: (json['smartPingRecentCoverageOnly'] as bool?) ?? false, showDeferredMarkers: (json['showDeferredMarkers'] as bool?) ?? true, @@ -240,6 +286,13 @@ class UserPreferences { final int d when d >= SmartPingDays.min && d <= SmartPingDays.max => d, _ => SmartPingDays.defaultDays, }, + scopeDiscoveryEnabled: (json['scopeDiscoveryEnabled'] as bool?) ?? false, + scopeDiscoveryDays: switch ((json['scopeDiscoveryDays'] as num?)?.toInt()) { + null => ScopeDiscoveryDays.defaultDays, + final int d when d < ScopeDiscoveryDays.min => ScopeDiscoveryDays.min, + final int d when d > ScopeDiscoveryDays.max => ScopeDiscoveryDays.max, + final int d => d, + }, mapAutoFollow: (json['mapAutoFollow'] as bool?) ?? false, mapAlwaysNorth: (json['mapAlwaysNorth'] as bool?) ?? true, mapRotationLocked: (json['mapRotationLocked'] as bool?) ?? false, @@ -254,9 +307,13 @@ class UserPreferences { autoStopAfterIdle: (json['autoStopAfterIdle'] as bool?) ?? true, showTopRepeaters: (json['showTopRepeaters'] as bool?) ?? false, largerTopRepeaters: (json['largerTopRepeaters'] as bool?) ?? false, + topHeardRows: _topHeardRowsFromJson(json['topHeardRows']), + topHeardShowNames: (json['topHeardShowNames'] as bool?) ?? false, liveActivityShowNames: (json['liveActivityShowNames'] as bool?) ?? true, markerStyle: (json['markerStyle'] as String?) ?? 'dot', gpsMarkerStyle: _migrateGpsMarkerStyle(json['gpsMarkerStyle'] as String?), + gpsMarkerColor: GpsMarkerColors.normalize( + json['gpsMarkerColor'] is String ? json['gpsMarkerColor'] : null), colorVisionType: (json['colorVisionType'] as String?) ?? 'none', mapTilesEnabled: (json['mapTilesEnabled'] as bool?) ?? true, coverageOverlayOpacity: @@ -265,6 +322,8 @@ class UserPreferences { 100 => 100, _ => 300, }, + showRepeaterCoverageLines: + (json['showRepeaterCoverageLines'] as bool?) ?? false, disconnectAlertEnabled: (json['disconnectAlertEnabled'] as bool?) ?? false, customApiEnabled: (json['customApiEnabled'] as bool?) ?? false, @@ -306,6 +365,14 @@ class UserPreferences { return value; } + /// A stored Top Heard row count, clamped to the supported range. A missing + /// or non-numeric value (or NaN/infinity) gives [topHeardRowsDefault], so a + /// bad stored value never reaches the UI. + static int _topHeardRowsFromJson(Object? value) { + if (value is! num || !value.isFinite) return topHeardRowsDefault; + return value.toInt().clamp(topHeardRowsMin, topHeardRowsMax); + } + /// Convert to JSON (for persistence) Map toJson() { return { @@ -329,7 +396,10 @@ class UserPreferences { 'hybridModeEnabled': hybridModeEnabled, 'smartPingEnabled': smartPingEnabled, 'smartPingDays': smartPingDays, + 'smartPingFloodOnly': smartPingFloodOnly, 'smartPingRecentCoverageOnly': smartPingRecentCoverageOnly, + 'scopeDiscoveryEnabled': scopeDiscoveryEnabled, + 'scopeDiscoveryDays': scopeDiscoveryDays, 'showDeferredMarkers': showDeferredMarkers, 'mapAutoFollow': mapAutoFollow, 'mapAlwaysNorth': mapAlwaysNorth, @@ -344,13 +414,17 @@ class UserPreferences { 'autoStopAfterIdle': autoStopAfterIdle, 'showTopRepeaters': showTopRepeaters, 'largerTopRepeaters': largerTopRepeaters, + 'topHeardRows': topHeardRows, + 'topHeardShowNames': topHeardShowNames, 'liveActivityShowNames': liveActivityShowNames, 'markerStyle': markerStyle, 'gpsMarkerStyle': gpsMarkerStyle, + 'gpsMarkerColor': gpsMarkerColor, 'colorVisionType': colorVisionType, 'mapTilesEnabled': mapTilesEnabled, 'coverageOverlayOpacity': coverageOverlayOpacity, 'coverageGridSize': coverageGridSize, + 'showRepeaterCoverageLines': showRepeaterCoverageLines, 'disconnectAlertEnabled': disconnectAlertEnabled, 'customApiEnabled': customApiEnabled, 'customApiUrl': customApiUrl, @@ -383,7 +457,10 @@ class UserPreferences { bool? hybridModeEnabled, bool? smartPingEnabled, int? smartPingDays, + bool? smartPingFloodOnly, bool? smartPingRecentCoverageOnly, + bool? scopeDiscoveryEnabled, + int? scopeDiscoveryDays, bool? showDeferredMarkers, bool? mapAutoFollow, bool? mapAlwaysNorth, @@ -398,13 +475,17 @@ class UserPreferences { bool? autoStopAfterIdle, bool? showTopRepeaters, bool? largerTopRepeaters, + int? topHeardRows, + bool? topHeardShowNames, bool? liveActivityShowNames, String? markerStyle, String? gpsMarkerStyle, + String? gpsMarkerColor, String? colorVisionType, bool? mapTilesEnabled, double? coverageOverlayOpacity, int? coverageGridSize, + bool? showRepeaterCoverageLines, bool? disconnectAlertEnabled, bool? customApiEnabled, String? customApiUrl, @@ -437,8 +518,11 @@ class UserPreferences { hybridModeEnabled: hybridModeEnabled ?? this.hybridModeEnabled, smartPingEnabled: smartPingEnabled ?? this.smartPingEnabled, smartPingDays: smartPingDays ?? this.smartPingDays, + smartPingFloodOnly: smartPingFloodOnly ?? this.smartPingFloodOnly, smartPingRecentCoverageOnly: smartPingRecentCoverageOnly ?? this.smartPingRecentCoverageOnly, + scopeDiscoveryEnabled: scopeDiscoveryEnabled ?? this.scopeDiscoveryEnabled, + scopeDiscoveryDays: scopeDiscoveryDays ?? this.scopeDiscoveryDays, showDeferredMarkers: showDeferredMarkers ?? this.showDeferredMarkers, mapAutoFollow: mapAutoFollow ?? this.mapAutoFollow, mapAlwaysNorth: mapAlwaysNorth ?? this.mapAlwaysNorth, @@ -455,15 +539,20 @@ class UserPreferences { autoStopAfterIdle: autoStopAfterIdle ?? this.autoStopAfterIdle, showTopRepeaters: showTopRepeaters ?? this.showTopRepeaters, largerTopRepeaters: largerTopRepeaters ?? this.largerTopRepeaters, + topHeardRows: topHeardRows ?? this.topHeardRows, + topHeardShowNames: topHeardShowNames ?? this.topHeardShowNames, liveActivityShowNames: liveActivityShowNames ?? this.liveActivityShowNames, markerStyle: markerStyle ?? this.markerStyle, gpsMarkerStyle: gpsMarkerStyle ?? this.gpsMarkerStyle, + gpsMarkerColor: gpsMarkerColor ?? this.gpsMarkerColor, colorVisionType: colorVisionType ?? this.colorVisionType, mapTilesEnabled: mapTilesEnabled ?? this.mapTilesEnabled, coverageOverlayOpacity: coverageOverlayOpacity ?? this.coverageOverlayOpacity, coverageGridSize: coverageGridSize ?? this.coverageGridSize, + showRepeaterCoverageLines: + showRepeaterCoverageLines ?? this.showRepeaterCoverageLines, disconnectAlertEnabled: disconnectAlertEnabled ?? this.disconnectAlertEnabled, customApiEnabled: customApiEnabled ?? this.customApiEnabled, @@ -524,7 +613,10 @@ class UserPreferences { other.hybridModeEnabled == hybridModeEnabled && other.smartPingEnabled == smartPingEnabled && other.smartPingDays == smartPingDays && + other.smartPingFloodOnly == smartPingFloodOnly && other.smartPingRecentCoverageOnly == smartPingRecentCoverageOnly && + other.scopeDiscoveryEnabled == scopeDiscoveryEnabled && + other.scopeDiscoveryDays == scopeDiscoveryDays && other.mapAutoFollow == mapAutoFollow && other.mapAlwaysNorth == mapAlwaysNorth && other.mapRotationLocked == mapRotationLocked && @@ -537,12 +629,16 @@ class UserPreferences { other.minPingDistanceMeters == minPingDistanceMeters && other.autoStopAfterIdle == autoStopAfterIdle && other.showTopRepeaters == showTopRepeaters && + other.topHeardRows == topHeardRows && + other.topHeardShowNames == topHeardShowNames && other.liveActivityShowNames == liveActivityShowNames && other.markerStyle == markerStyle && other.gpsMarkerStyle == gpsMarkerStyle && + other.gpsMarkerColor == gpsMarkerColor && other.colorVisionType == colorVisionType && other.mapTilesEnabled == mapTilesEnabled && other.coverageOverlayOpacity == coverageOverlayOpacity && + other.showRepeaterCoverageLines == showRepeaterCoverageLines && other.disconnectAlertEnabled == disconnectAlertEnabled && other.customApiEnabled == customApiEnabled && other.customApiUrl == customApiUrl && @@ -573,7 +669,10 @@ class UserPreferences { hybridModeEnabled, smartPingEnabled, smartPingDays, + smartPingFloodOnly, smartPingRecentCoverageOnly, + scopeDiscoveryEnabled, + scopeDiscoveryDays, mapAutoFollow, mapAlwaysNorth, mapRotationLocked, @@ -586,12 +685,16 @@ class UserPreferences { minPingDistanceMeters, autoStopAfterIdle, showTopRepeaters, + topHeardRows, + topHeardShowNames, liveActivityShowNames, markerStyle, gpsMarkerStyle, + gpsMarkerColor, colorVisionType, mapTilesEnabled, coverageOverlayOpacity, + showRepeaterCoverageLines, disconnectAlertEnabled, customApiEnabled, customApiUrl, @@ -645,3 +748,12 @@ class SmartPingDays { static const int max = 365; static const int defaultDays = 14; } + +/// Scope discovery refresh window bounds (days). Stored values are clamped +/// into range rather than falling back to the default, so an admin-set +/// window that briefly went out of bounds is never silently discarded. +class ScopeDiscoveryDays { + static const int min = 7; + static const int max = 365; + static const int defaultDays = 14; +} diff --git a/lib/providers/app_state_provider.dart b/lib/providers/app_state_provider.dart index 6ffff787..c6d6008e 100644 --- a/lib/providers/app_state_provider.dart +++ b/lib/providers/app_state_provider.dart @@ -6,7 +6,7 @@ import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' show SystemNavigator; import 'package:flutter/widgets.dart' - show WidgetsBinding, WidgetsBindingObserver, AppLifecycleState; + show WidgetsBinding, WidgetsBindingObserver, AppLifecycleState, Rect; import 'package:geolocator/geolocator.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:app_links/app_links.dart'; @@ -14,7 +14,9 @@ import 'package:uuid/uuid.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart' show SharePlus, ShareParams, XFile; import 'package:http/http.dart' as http; +import 'package:package_info_plus/package_info_plus.dart'; +import '../debug/store_capture.dart'; import '../models/connection_state.dart'; import '../models/device_model.dart'; import '../models/noise_floor_session.dart'; @@ -22,18 +24,29 @@ import '../models/onboarding_guide_progress.dart'; import '../models/ping_data.dart'; import '../models/log_entry.dart'; import '../models/remembered_device.dart'; +import '../models/scope_log_entry.dart'; import '../models/repeater.dart'; +import '../models/map_view_state.dart'; import '../models/user_preferences.dart'; import '../services/airborne_release.dart'; import '../services/api_queue_service.dart'; +import '../utils/coverage_refresh.dart'; +import '../utils/debouncer.dart'; import '../utils/mvt_cells.dart'; +import '../utils/store_links.dart'; import '../services/api_service.dart'; +import 'repeater_list_state.dart'; import '../services/audio_service.dart'; +import '../services/background_location_policy.dart'; +import '../services/precise_location_gate.dart'; +import '../services/noise_floor_session_store.dart'; import '../services/sound_notification_service.dart'; import '../services/background_service.dart'; +import '../services/border_loader.dart'; import '../services/debug_file_logger.dart'; import '../services/disconnect_alert_decision.dart'; import '../services/offline_session_service.dart'; +import '../services/offline_session_export.dart'; import '../services/bluetooth/ble_connect_retry_policy.dart'; import '../services/bluetooth/bluetooth_service.dart'; import '../services/transport/android_serial_service.dart'; @@ -42,9 +55,12 @@ import '../services/transport/tcp_service.dart'; import '../services/device_model_service.dart'; import '../services/gps_service.dart'; import '../services/gps_simulator_service.dart'; +import '../services/idle_session.dart'; import '../services/link_decision.dart'; +import '../services/location_consent.dart'; import '../services/meshcore/channel_service.dart'; import '../services/meshcore/connection.dart'; +import '../services/meshcore/scope_lease.dart' show ScopeCancelToken; import '../services/meshcore/crypto_service.dart'; import '../services/meshcore/packet_validator.dart' show PacketValidator, ChannelInfo; @@ -75,10 +91,16 @@ import '../services/watch/watch_models.dart'; import '../services/custom_api_service.dart'; import '../services/portal_account_service.dart'; import '../services/portal_token_store.dart'; +import '../services/reconnect_flap_guard.dart'; import '../services/recent_coverage_service.dart'; import '../services/reporting_power.dart'; import 'device_connection_setup.dart'; import '../services/repeater_admin/manage_target.dart'; +import '../services/scope_discovery/scope_discovery_rules.dart'; +import '../services/scope_discovery/scope_lifecycle.dart'; +import '../services/scope_discovery/scope_provider_support.dart'; +import '../services/scope_discovery/scope_runner.dart'; +import '../services/session_recovery_join.dart'; import '../services/repeater_admin/repeater_admin_api.dart'; import '../services/repeater_admin/repeater_claim_unclaim.dart'; import '../services/repeater_admin/repeater_claims_cache.dart'; @@ -86,10 +108,15 @@ import '../services/repeater_admin/repeater_admin_models.dart'; import '../services/repeater_admin/repeater_admin_module.dart'; import '../services/repeater_admin/repeater_admin_session.dart'; import '../utils/constants.dart'; +import '../utils/distance_formatter.dart'; import '../utils/geo_validation.dart'; +import '../utils/public_key.dart'; import '../utils/repeater_collision.dart'; +import '../utils/repeater_nicknames.dart'; +import '../utils/short_hop_ids.dart'; import '../utils/ping_colors.dart'; import '../utils/radio_filter.dart' as radio_filter; +import '../utils/zone_group.dart'; import '../services/wakelock_service.dart'; import '../utils/debug_logger_io.dart'; @@ -191,6 +218,199 @@ Future awaitSessionRecoveryBounded( } } +/// How long a Disconnect or Close App tap waits for the queued pings to +/// upload before it releases the session anyway. +@visibleForTesting +const Duration disconnectQueueUploadTimeout = Duration(seconds: 5); + +/// Run [upload], bounded by [limit]. True when it finished, false when it +/// timed out or threw. A slow or dead network must not hold the teardown +/// open with the UI already showing Disconnecting, and a failed upload must +/// not abandon it: the queue is cleared and the session released either way. +@visibleForTesting +Future uploadQueueBounded( + Future Function() upload, { + Duration limit = disconnectQueueUploadTimeout, +}) async { + try { + await upload().timeout(limit); + return true; + } on TimeoutException { + return false; + } catch (e) { + debugError('[APP] Queue upload before release failed: $e'); + return false; + } +} + +/// Seconds before the next zone check after [failures] checks in a row got no +/// answer: 5, 10, 20, 40, then every 60. A flat 5 s retried a dead network +/// twelve times a minute for as long as it lasted (500 tries in one Android +/// log), and in a server outage every phone would do the same to /status. +@visibleForTesting +int zoneCheckNetworkRetrySeconds(int failures) { + if (failures >= 5) return 60; + if (failures <= 1) return 5; + return 5 << (failures - 1); +} + +/// Whether the error log holds an error the user has not had on screen. +/// [logged] counts every error ever logged and [seen] is that count when the +/// Errors tab was last showing. Counts, not times: a phone clock stepped +/// backwards would stamp new errors before the seen mark and hide them. +@visibleForTesting +bool errorLogHasUnseen( + {required bool hasEntries, required int logged, required int seen}) => + hasEntries && logged > seen; + +/// The Go Online refusal when the server says this spot is in no zone, +/// naming the nearest zone when the answer carried one. Offline Mode stays +/// on, and so does wardriving: the check runs before anything is stopped. +@visibleForTesting +String goOnlineOutsideZoneMessage(Map? nearestZone, + {bool isImperial = false}) { + const outside = 'You are outside every MeshMapper zone.'; + const staysOn = 'Offline Mode stays on.'; + final name = nearestZone?['name'] as String?; + final km = (nearestZone?['distance_km'] as num?)?.toDouble(); + if (name == null || km == null) return '$outside $staysOn'; + final dist = formatKilometers(km, isImperial: isImperial); + return '$outside Nearest zone is $name, $dist away. $staysOn'; +} + +/// Whether a connected radio's companion firmware is too old for scope +/// discovery (below [AppStateProvider.kScopeDiscoveryCompanionVersionCode]). +/// The Scope Discovery switch still saves either way; this only decides +/// whether the Settings tile grows its extra warning line. Not connected +/// means nothing to warn about yet, whatever the last-seen firmware code was. +@visibleForTesting +bool scopeDiscoveryFirmwareTooOld( + {required bool connected, required int? firmwareCode}) => + connected && + (firmwareCode ?? 0) < AppStateProvider.kScopeDiscoveryCompanionVersionCode; + +/// Whether a "cannot ask non-contacts" flip should add a new error-log entry +/// for the connection that just hit it: only the first time, per connection. +/// `MeshCoreConnection` already fires +/// `onScopeCannotAskNonContactsChanged` at most once per connection life (its +/// own flag never resets to false mid-connection), so this mirrors that +/// guard at the call site rather than relying on it alone. +@visibleForTesting +bool shouldLogScopeContactsFull({required bool alreadyLoggedThisConnection}) => + !alreadyLoggedThisConnection; + +/// How long a countdown may sit past its deadline before the stuck-timer +/// watchdog names it. Its 500 ms tick clears a finished window a moment after +/// the deadline, so a check that lands in that gap is not a lockout. +const Duration stuckCountdownGrace = Duration(seconds: 2); + +/// Whether a countdown is still running at least [stuckCountdownGrace] past +/// its deadline, the stuck-lockout fingerprint. Running with no deadline at +/// all counts as stuck, as it always did. +@visibleForTesting +bool countdownLooksStuck( + {required bool isRunning, + required DateTime? endTime, + required DateTime now}) { + if (!isRunning) return false; + if (endTime == null) return true; + return now.difference(endTime) >= stuckCountdownGrace; +} + +/// Whether an auto-reconnect attempt that ended after its reconnect was over +/// should disconnect the connection that is up. [abandonedAtGeneration] is +/// the connect generation an abandon stamped when it caught this attempt in +/// flight, or null when none did (a user Disconnect ended the reconnect). +/// A stamped attempt may only close a connection nobody has started since +/// the abandon: a newer connect bumps the generation and owns what is up. +@visibleForTesting +bool shouldDisconnectOrphanedReconnect({ + required int? abandonedAtGeneration, + required int currentGeneration, + required bool connected, +}) { + if (!connected) return false; + if (abandonedAtGeneration == null) return true; + return abandonedAtGeneration == currentGeneration; +} + +/// Whether the auto-reconnect budget, running out, gives the attempt's +/// connect a bounded grace to finish instead of abandoning at once. A GATT +/// connect that is about to succeed was otherwise thrown away. +@visibleForTesting +bool reconnectBudgetGivesConnectGrace( + {required bool connectInFlight, required bool graceUsed}) => + connectInFlight && !graceUsed; + +/// Whether a connect workflow's auth callback belongs to an attempt that is +/// over. [createdAtGeneration] is the connect generation when the callback +/// was made; [sameConnection] is whether the provider still holds the +/// connection it was made for. An abandoned reconnect bumps the generation +/// and drops its connection, and a stale attempt must not POST /auth then. +@visibleForTesting +bool authCallbackSuperseded({ + required int createdAtGeneration, + required int currentGeneration, + required bool sameConnection, +}) => + createdAtGeneration != currentGeneration || !sameConnection; + +/// Whether a disconnect cleanup, at its end, still owns the provider's +/// current connection objects. [cleanupGeneration] is the connect generation +/// when the cleanup started; a connect begun during the cleanup's awaits +/// bumps it and owns whatever is current by then, for as long as it is +/// [newerConnectLive] (still connecting, or connected). A connect that +/// failed or was cancelled since owns nothing: the session and the objects +/// are the cleanup's again, or the session would be held until it expires. +@visibleForTesting +bool cleanupOwnsCurrentConnection({ + required int cleanupGeneration, + required int currentGeneration, + required bool newerConnectLive, +}) => + cleanupGeneration == currentGeneration || !newerConnectLive; + +/// An auto-reconnect attempt's connect call while it runs. An abandon that +/// catches it stamps the connect generation it moved to, which is how the +/// attempt learns, when it ends, that it no longer owns anything. +class _ReconnectConnectAttempt { + int? abandonedAtGeneration; +} + +/// Whether an /auth answer means this phone just took a TX slot the cached +/// /status count does not know about yet. Not when the server sent its own +/// count, and not for a reused session (it carries `resume_counter`): that +/// slot was already ours, and counting it again on every reconnect walked the +/// estimate down. +@visibleForTesting +bool authTookNewSlot(Map authResult) => + authResult['tx_allowed'] == true && + !authResult.containsKey('slots_available') && + !authResult.containsKey('resume_counter'); + +/// The least time between two claims refreshes made by auto-reconnects +/// inside one session. The server allows 60 `mine` calls an hour. +@visibleForTesting +const Duration claimsReconcileReconnectSpacing = Duration(minutes: 10); + +/// Whether a connect should refresh the companion's repeater claims (the +/// `mine` action). A manual connect always does. An auto-reconnect does only +/// when the session changed or [claimsReconcileReconnectSpacing] has passed +/// since the last connect-time refresh: a reconnect loop otherwise spent the +/// server's hourly cap in minutes. +@visibleForTesting +bool shouldReconcileClaimsOnConnect({ + required bool autoReconnect, + required String? sessionId, + required String? lastSessionId, + required DateTime? lastAt, + required DateTime now, +}) { + if (!autoReconnect || lastAt == null) return true; + if (sessionId != lastSessionId) return true; + return now.difference(lastAt) >= claimsReconcileReconnectSpacing; +} + /// Main application state provider class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Maximum sizes for in-memory lists to prevent unbounded growth during long sessions @@ -299,6 +519,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? _connectionError; bool _isAuthError = false; // Track if connection failed due to auth bool _isNetworkError = false; // Track if connection failed due to network + AppUpdateRequirement? _appUpdateRequirement; // Set when /auth said outofdate + + /// How the app was installed (`PackageInfo.installerStore`), read only when + /// the server refuses this build. Replaceable in tests, where the real + /// plugin call hangs. + @visibleForTesting + Future Function() installerStoreReader = + () async => (await PackageInfo.fromPlatform()).installerStore; // Bluetooth adapter state (on/off) BluetoothAdapterState _bluetoothAdapterState = BluetoothAdapterState.unknown; @@ -336,6 +564,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? get displayDeviceName => _displayDeviceName ?? connectedDeviceName?.replaceFirst('MeshCore-', ''); + /// Radio name set by debug-only store capture mode. Display only: it never + /// feeds connection logic, which reads [connectedDeviceName]. + String? _storeCaptureRadioName; + + /// Radio name for the Home screen header, or null when no radio is + /// connected. Capture mode shows a fixed name so screenshots carry no + /// personal device name. + String? get headerRadioName => + _storeCaptureRadioName ?? + (connectedDeviceName != null ? (displayDeviceName ?? 'Unknown') : null); + // Ping state PingStats _pingStats = const PingStats(); bool _autoPingEnabled = false; @@ -371,6 +610,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { bool _isScanning = false; StreamSubscription? _activeScanSubscription; + /// True while connectToDevice is waiting on the BLE transport connect, the + /// one stretch of a connect the user can cancel (up to 3 x 15 s when the + /// radio is off or out of range). + bool _bleTransportConnecting = false; + + /// True while [cancelConnect] is tearing the pending BLE connect down. + bool _isCancellingConnect = false; + // TX/RX markers for map final List _txPings = []; final List _rxPings = []; @@ -384,6 +631,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final List _rxLogEntries = []; final List _discLogEntries = []; final List _traceLogEntries = []; + final ScopeLogStore _scopeLog = ScopeLogStore(maxEntries: _maxLogEntries); final List _deferredPingMarkers = []; final List _startingDeferredHistory = []; @@ -400,14 +648,21 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Top repeaters overlay, updated live on each ping event. The map's Top // Heard box, the watch's heard rows and the Live Activity's rows all read - // this one list, so the three surfaces cannot disagree. + // this one list, so the three surfaces cannot disagree. It holds up to + // UserPreferences.topHeardRowsMax rows; the map shows the user's row + // setting of them and the other surfaces the first [_surfaceTopHeardRows]. List<({String repeaterId, double snr, OverlayPingType type})> _topRepeatersOverlay = []; DateTime? _topRepeatersOverlayUpdatedAt; - /// How many repeaters the latest ping heard in all, beyond the three the - /// overlay keeps. The Live Activity's "HEARD NOW n" header counts them. - int _topRepeatersOverlayTotalCount = 0; + /// Ping rows the Live Activity, CarPlay and the watch show, whatever the + /// in-app Top Heard Rows setting is. + static const int _surfaceTopHeardRows = 3; + + /// Every repeater the latest ping heard (upper-case display IDs), regardless + /// of how many rows are stored or shown. The Live Activity's "HEARD NOW n" + /// header counts them, plus the RX repeater only when it is not one of them. + Set _topRepeatersOverlayHeardIds = const {}; /// The fullest identity known for each overlay row, keyed by the display hash /// the row is shown under. @@ -434,6 +689,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // User error log entries final List _errorLogEntries = []; + // Errors logged so far, how many of them the user has had on screen, and + // whether the Errors tab is showing now. The Log tab's dot means an unseen + // error, not any error: it used to clear only with Clear all logs. + int _errorsLogged = 0; + int _errorsSeen = 0; + bool _errorLogOnScreen = false; + // User preferences UserPreferences _preferences = const UserPreferences(); @@ -501,6 +763,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { int _zoneCheckRetryCountdown = 0; // Seconds until next retry (0 = not counting) Timer? _zoneCheckRetryTimer; // Fires to trigger the retry + int _zoneCheckNetworkFailures = 0; // In a row; any real answer resets it Timer? _zoneCheckCountdownTimer; // Ticks every 1s for UI countdown // Maintenance mode state @@ -547,15 +810,82 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { int _sessionRecoveryGeneration = 0; Future? _liveSessionRecoveryInFlight; + /// True while a group handoff holds [_liveSessionRecoveryInFlight]. A + /// session_expired arriving then is answered superseded instead of being + /// handed the handoff's own future (see [resolveSessionRecoveryJoin]). + bool _groupHandoffOwnsRecoverySlot = false; + // Auto-reconnect state bool _userRequestedDisconnect = false; + /// Set while [exitApp] runs, so a second Close App cannot pop the app in + /// the middle of the first one's disconnect. + bool _exitInProgress = false; + /// Bumped by every transport connect entry point. A connection attempt that /// finds its captured generation stale has been superseded by a newer /// attempt and must not touch shared provider state (#500 review). int _connectGeneration = 0; bool _isAutoReconnecting = false; + /// True while a connect re-run (#500) is waiting to start. Both this and + /// [_isAutoReconnecting] run while [_connectionStep] reads `disconnected`, + /// yet the radio session is not over. + bool _connectRerunPending = false; + + /// True while a radio session is live, which is what lets GPS keep + /// collecting after the app leaves the screen. + bool get _sessionActive => radioSessionActive( + step: _connectionStep, + autoReconnecting: _isAutoReconnecting, + connectRerunPending: _connectRerunPending, + ); + + /// True when this provider stopped GPS (or never started it) because the app + /// is in the background with no radio session. It marks the GPS stream the + /// policy owes a restart on return, so a stream stopped for any other reason + /// is never started here. + bool _gpsStoppedByPolicy = false; + + /// True when init had to hold GPS back, so the first start after it is a + /// full one (the one-off position read and the usual resets) rather than the + /// quiet restart used when returning from the background. + bool _gpsInitialStartPending = false; + + /// How many full disconnect cleanups are running. The cleanup flips + /// [_connectionStep] to `disconnected` at its top, long before the queue + /// flush and session release finish, so [_sessionActive] alone would let GPS + /// stop mid-upload. A failed connect also reads it, to leave the session + /// service's stop to that cleanup's end. + int _disconnectCleanupDepth = 0; + + /// Whether Android's session service may use location: the permission and + /// the in-app disclosure, both. Read at the Connect tap, on return to the + /// app and after a permission change, and kept here because + /// [_syncConnectionService] runs on every notify and cannot ask. + bool _sessionLocationGranted = false; + + /// True while a session service start waits for its answer, so the notifies + /// in between do not send a second one. + bool _connectionServiceStarting = false; + + /// True once this session has logged that the service was held back for + /// want of location. Cleared when the session ends, so each session logs it + /// once rather than on every notify. + bool _serviceRefusalLogged = false; + + /// True when a session service start came back not started, or was + /// accepted and then failed to reach the foreground. No further start is + /// tried until the app comes back on screen or the session ends, so a start + /// that keeps failing is not resent (and logged) on every notify. + bool _connectionServiceStartFailed = false; + + /// True once a start since the app last came on screen was accepted. With + /// the session still live, the service can then only read not running + /// because the manager's status read shortly after the start found it never + /// reached the foreground. + bool _connectionServiceStartAccepted = false; + // ============================================ // MyMeshMapper account + companion linking // ============================================ @@ -656,6 +986,24 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { static const Duration _reconnectDelayAfterBondError = Duration(seconds: 5); bool _lastReconnectWasBondError = false; + /// Gives up on a radio that keeps dropping right after it reconnects. + final ReconnectFlapGuard _reconnectFlapGuard = ReconnectFlapGuard(); + + /// The auto-reconnect attempt whose connect call is running, if any. + _ReconnectConnectAttempt? _reconnectConnectInFlight; + + /// When, and in which session, a connect last refreshed the repeater + /// claims (see [shouldReconcileClaimsOnConnect]). + DateTime? _lastConnectClaimsReconcileAt; + String? _lastConnectClaimsReconcileSession; + + /// Set once the budget ran out and the in-flight connect got its grace: an + /// attempt that then fails abandons instead of retrying. + bool _reconnectBudgetSpent = false; + + /// How long a connect still in flight when the budget runs out gets. + static const Duration _reconnectInFlightGrace = Duration(seconds: 15); + // Idle disconnect timer — disconnects after 15 min without manual ping or auto-ping Timer? _idleDisconnectTimer; static const Duration _idleDisconnectTimeout = Duration(minutes: 15); @@ -673,6 +1021,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Zone transfer state — tracks session zone for zone-to-zone detection String? _sessionZoneCode; + // The group that zone belonged to when the session was minted, or null. + String? _sessionGroupCode; bool _isZoneTransferInProgress = false; String? _zoneTransferFrom; String? _zoneTransferTo; @@ -690,11 +1040,71 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { bool _anonymousReconnectEnabling = true; // Repeater markers state - List _repeaters = []; + RepeaterListState _repeaterListState = const RepeaterListState(); + List get _repeaters => _repeaterListState.repeaters; Set _repeaterConflictHexIds = const {}; int _siriRepeaterCatalogRevision = 0; - bool _repeatersLoaded = false; - String? _repeatersLoadedForIata; + bool get _repeatersLoaded => _repeaterListState.loadedAt != null; + String? get _repeatersLoadedForIata => _repeaterListState.zone; + final Set<(String, String?)> _repeaterLoadsInFlight = {}; + + /// When the repeater list last loaded (scope discovery refreshes a list + /// older than an hour at connect). + DateTime? get _repeatersLoadedAt => _repeaterListState.loadedAt; + + /// True while a scope-discovery repeater list refresh (connect-time, + /// mode-start or periodic) is in flight, so only one runs at a time. + bool _scopeRepeaterRefreshInFlight = false; + + // ============================================ + // Scope discovery (background scope runner) + // ============================================ + static const String _scopeHourBudgetKey = 'scope_hour_budget'; + static const String _scopeQueryCacheKey = 'scope_query_cache'; + ScopeQueryCache _scopeQueryCache = ScopeQueryCache.fromJson(null); + late ScopeHourlyBudget _scopeHourlyBudget = + ScopeHourlyBudget(save: _saveScopeHourBudget); + late final ScopeSerialWriter _scopeCacheWriter = + ScopeSerialWriter('scope query cache', _saveScopeQueryCache); + + /// The scope wiring: the runner gate, the badge, borrowed routes per + /// connection, the stop events and the refresh discard. + late final ScopeLifecycle _scopeLifecycle = ScopeLifecycle( + cancelHostRunner: (reason) => _pingService?.cancelScopeRunner(reason), + onBadgeChanged: () { + if (!_isDisposed) notifyListeners(); + }, + ); + + /// Short heard ids to the one repeater they can mean, rebuilt whenever + /// [_repeaters] is replaced. Top Heard reads it on every heard packet. + List? _shortHopIdsSource; + ShortHopIds? _shortHopIds; + + ShortHopIds get _heardIdResolver { + if (_shortHopIds == null || !identical(_shortHopIdsSource, _repeaters)) { + _shortHopIds = ShortHopIds.fromRepeaters(_repeaters); + _shortHopIdsSource = _repeaters; + } + return _shortHopIds!; + } + + /// The widest hop width in play: the device's and the region's. + int get _topHeardHopBytes => math.max(_hopBytes, _apiService.apiHopBytes); + + /// The id a heard repeater shows and groups under in Top Heard: a short + /// hop id ("A8") that only one known repeater starts with becomes that + /// repeater's id ("A81EA4"); anything else is kept. Display only, see + /// [ShortHopIds]. + String _topHeardId(String repeaterId) => + _heardIdResolver.displayId(repeaterId, hopBytes: _topHeardHopBytes); + + /// The server's scope stamps, rebuilt whenever [_repeaters] is replaced. + List? _scopeServerInfoSource; + Map _scopeServerInfo = const {}; + + /// True while a scope request is out (the Scopes badge). + bool get isScopeRequestActive => _scopeLifecycle.requestActive; // ============================================ // Regional CARpeaters (the region's shared list from /auth) @@ -731,6 +1141,134 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return null; } + // ============================================ + // Repeater nicknames (personal labels, kept on the phone) + // ============================================ + + /// Box key for the saved nicknames, an untyped map in the preferences box. + static const String _repeaterNicknamesKey = 'repeater_nicknames'; + + /// The user's nicknames, keyed by the repeater's full public key. + /// + /// Global to the phone and never scoped to a zone or IATA: a nickname must + /// survive leaving a region and coming back. Nothing clears or filters this + /// on a zone change, a catalogue reload, a disconnect, a log clear or a + /// session end. Only [setRepeaterNickname] and [setRepeaterNicknameByKey] + /// change it, and resolution against whatever catalogue is loaded brings a + /// nickname back when its repeater is in view again. + Map _repeaterNicknames = const {}; + + /// Every saved nickname as (full public key, entry), sorted by nickname + /// without regard to case, then by key so two repeaters given the same + /// nickname keep their order. Unmodifiable. + List> get repeaterNicknames => + List.unmodifiable(_repeaterNicknames.entries.toList() + ..sort((a, b) { + final byName = a.value.nickname + .toLowerCase() + .compareTo(b.value.nickname.toLowerCase()); + return byName != 0 ? byName : a.key.compareTo(b.key); + })); + + /// How many nicknames are saved. + int get repeaterNicknameCount => _repeaterNicknames.length; + + /// The nickname saved for [repeater], or null when it has none. + String? nicknameForRepeater(Repeater repeater) => + RepeaterNicknames.nicknameFor(repeater, _repeaterNicknames); + + /// The text for a Top Heard row: its nickname when the row resolves to one + /// repeater that has one, else that repeater's server name when the Top + /// Heard names setting is on, else [repeaterId] unchanged. + String topHeardLabel(String repeaterId) { + final id = repeaterId.toUpperCase(); + return RepeaterNicknames.labelFor( + displayId: id, + identity: _overlayIdentityById[id], + repeaters: _repeaters, + hopBytes: _hopBytes, + nicknames: _repeaterNicknames, + useServerName: _preferences.topHeardShowNames, + ) ?? + repeaterId; + } + + /// Give [repeater] the nickname [nickname], or remove its nickname when + /// [nickname] is null or blank. Does nothing for a repeater without a full + /// public key, which the UI never offers. + Future setRepeaterNickname(Repeater repeater, String? nickname) async { + final key = normalizePublicKey(repeater.hexId); + if (key == null) { + debugWarn('[SETTINGS] Repeater nickname ignored: no full public key'); + return; + } + final n = RepeaterNicknames.normalizeNickname(nickname); + await _onRepeaterNicknamesChanged( + key, + set: n == null + ? null + : RepeaterNickname( + nickname: n, + name: repeater.name, + hex: repeater.displayHexId(), + ), + ); + } + + /// Like [setRepeaterNickname] for a repeater known only by [publicKey], as + /// in the Settings list, whose entries may not be in the current catalogue. + /// + /// [name] and [hex] describe the repeater in the list: the arguments when + /// given (Undo re-adds a removed entry this way), else the existing entry's. + Future setRepeaterNicknameByKey( + String publicKey, + String? nickname, { + String? name, + String? hex, + }) async { + final key = normalizePublicKey(publicKey); + if (key == null) { + debugWarn('[SETTINGS] Repeater nickname ignored: not a full public key'); + return; + } + final n = RepeaterNicknames.normalizeNickname(nickname); + final existing = _repeaterNicknames[key]; + await _onRepeaterNicknamesChanged( + key, + set: n == null + ? null + : RepeaterNickname( + nickname: n, + name: name ?? existing?.name ?? '', + hex: hex ?? existing?.hex ?? key.substring(0, 4), + ), + ); + } + + /// Apply one change to the nicknames: [set] is the new entry for [key], or + /// null to remove it. Replaces the map rather than editing it, since the + /// getters hand out views of it. + Future _onRepeaterNicknamesChanged( + String key, { + required RepeaterNickname? set, + }) async { + final next = Map.of(_repeaterNicknames); + if (set == null) { + next.remove(key); + } else { + next[key] = set; + } + _repeaterNicknames = Map.unmodifiable(next); + // Part of the Siri preflight key, so the snapshot rebuilds. + _siriRepeaterCatalogRevision++; + // The Top Heard overlay only rebuilds on the map revision. + _notifyMapNow(); + _scheduleLiveActivitySync(); + await _saveRepeaterNicknames(); + debugLog('[SETTINGS] Repeater nickname ' + '${set != null ? 'set' : 'cleared'} for ${_pkPrefix(key)}'); + } + // ============================================ // Radio preset (multiple radio configurations per region) // ============================================ @@ -773,10 +1311,53 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { isPingSending: _isPingSending, isRepeaterAdminActive: isRepeaterAdminActive, isAutoReconnecting: _isAutoReconnecting, + scopeRadioBusy: isScopeRadioBusy, companionFirmwareSupported: companionSupportsRepeaterAdmin(companionFirmwareVersionCode), ); + /// True while a scope lease holds the radio or a reply to a command it + /// wrote is still owed (Manage waits for it). Replies owed to ordinary + /// traffic do not count. + bool get isScopeRadioBusy => scopeRadioBusy( + isScopeLeaseActive: _meshCoreConnection?.isScopeLeaseActive ?? false, + hasScopeReplyDebt: _meshCoreConnection?.hasScopeReplyDebt ?? false); + + /// Rebuilds Manage when [connection]'s scope-busy flag flips. The + /// connection fires only on a real change, never per frame, and this is a + /// plain notify: the map does not render it (Rule 9). + void _wireScopeRadioBusy(MeshCoreConnection connection) { + connection.onScopeRadioBusyChanged = () { + if (_isDisposed || !identical(_meshCoreConnection, connection)) return; + notifyListeners(); + }; + } + + /// Drops a warning in the error log the first time [connection]'s "cannot + /// ask non-contacts" flag flips to true: users rarely go back to Settings + /// mid-drive to see a note there. Fired once, only on the transition, and + /// [shouldLogScopeContactsFull] latches it to once per connection even so. + /// The plain notify afterward is a rebuild hook for the raw flag; the map + /// does not render it (Rule 9). + void _wireScopeCannotAskNonContacts(MeshCoreConnection connection) { + var loggedThisConnection = false; + connection.onScopeCannotAskNonContactsChanged = () { + if (_isDisposed || !identical(_meshCoreConnection, connection)) return; + if (shouldLogScopeContactsFull( + alreadyLoggedThisConnection: loggedThisConnection)) { + loggedThisConnection = true; + logError( + "Your radio's contact list is full, so scope discovery can only " + 'ask repeaters saved as contacts. Companion firmware v1.17 or ' + 'newer fixes this, or remove some contacts.', + severity: ErrorSeverity.warning, + autoSwitch: false, + ); + } + notifyListeners(); + }; + } + /// The connected companion's cached claims, or the deduplicated cache while /// no companion is connected. List get repeaterClaims => @@ -811,8 +1392,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Regional boundary polygons (from /border API — always displayed on map) List> _regionBorders = []; - String? _bordersLoadedForZone; - bool _bordersFetchInProgress = false; + final BorderLoader _borderLoader = + BorderLoader(cache: kIsWeb ? null : HiveBorderCacheStore()); // Regional channels from API (for UI display) List _regionalChannels = []; @@ -835,6 +1416,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { List _storedNoiseFloorSessions = []; Box? _noiseFloorSessionBox; + /// Writes the running session to Hive every few minutes and when the app + /// leaves the screen, so a kill does not lose it from History. + final NoiseFloorCheckpoint _noiseFloorCheckpoint = NoiseFloorCheckpoint(); + Timer? _noiseFloorCheckpointTimer; + static const Duration _noiseFloorCheckpointInterval = Duration(minutes: 3); + // History session map view List? _historySessionMarkers; bool _viewingHistorySession = false; @@ -854,11 +1441,222 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _initialize(); } + /// The background-location policy does not apply on web (the browser owns + /// the lifecycle) or while the GPS simulator feeds positions. + bool get _gpsPolicyApplies => !kIsWeb && !_gpsService.isSimulatorEnabled; + + GpsRunDecision get _gpsRunDecision => gpsRunDecision( + lifecycle: WidgetsBinding.instance.lifecycleState, + // GPS outlives the step change: the location stream keeps the + // backgrounded iOS process alive through the final upload. + radioActive: _sessionActive || _disconnectCleanupDepth > 0, + isIos: defaultTargetPlatform == TargetPlatform.iOS, + ); + + /// Stops GPS while the app is in the background with no radio session, and + /// starts it again quietly when the app is back on screen. + /// + /// Runs on every lifecycle change and every notify, so it must stay cheap + /// and synchronous apart from the unawaited restart. [why] names the trigger + /// in the log. + void _syncGpsWithPolicy(String why) { + if (!_gpsPolicyApplies) return; + switch (_gpsRunDecision) { + case GpsRunDecision.stop: + if (_gpsService.isWatching) { + _gpsStoppedByPolicy = true; + _gpsService.stopWatching(); + debugLog( + '[GPS] Stopped: app in the background with no radio ($why)'); + } + case GpsRunDecision.run: + if (_gpsStoppedByPolicy) { + final keepTracking = !_gpsInitialStartPending; + // Cleared before the restart so a notify during it cannot start a + // second one. + _gpsStoppedByPolicy = false; + _gpsInitialStartPending = false; + debugLog(keepTracking + ? '[GPS] Restarting: $why' + : '[GPS] Starting: $why'); + unawaited(restartGpsAfterPermission(keepTracking: keepTracking)); + } + case GpsRunDecision.keep: + break; + } + } + + /// Whether the session service holds its wake lock: while a mode runs, and + /// while a reconnect or a zone grace period has paused one that will + /// resume. Their own timers (the reconnect's 30 s give-up, the grace + /// period's 5 s polling) must not drift with the screen off. The hand-offs + /// count too: a mode's start (its session check runs before the mode is + /// on), and the short wait before a mode is restored after a reconnect or + /// a zone change, so the lock does not drop for that moment. + bool get _keepServiceAwake => + _autoPingEnabled || + _autoPingStarting || + _restoreAutoPingTimer != null || + (_isAutoReconnecting && _autoPingWasEnabled) || + (_isInZoneGracePeriod && _autoPingWasEnabledBeforeGrace); + + /// What Android's session service notification says right now. The service + /// runs for the whole radio session, so it reads the mode's stats while one + /// runs and the connection's state between modes. + ({String title, String body}) _serviceNotificationNow() { + if (_autoPingEnabled) { + return androidNotificationContent( + mode: _autoMode, + txCount: _pingStats.txCount, + rxCount: _pingStats.rxCount, + queueSize: _queueSize, + ); + } + if (_isInZoneGracePeriod) return androidZoneGraceNotificationContent(); + if (_isAutoReconnecting) { + return ( + title: 'MeshMapper - Reconnecting', + body: 'Trying to reach ${_rememberedDevice?.name ?? 'your radio'}', + ); + } + // From the Connect tap on, and through a connect re-run's wait. + if (_connectionStep != ConnectionStep.connected) { + return androidConnectingNotificationContent(); + } + return androidConnectedNotificationContent( + radioName: _rememberedDevice?.name ?? 'your radio', + ); + } + + /// Reads whether location may be used for the session service (see + /// [_sessionLocationGranted]). Android only. A check that fails counts as + /// not granted: the service cannot reach the foreground without location. + Future _refreshSessionLocationGranted() async { + if (!BackgroundServiceManager.followsConnection) return; + try { + _sessionLocationGranted = await _gpsService.checkPermissions() && + await LocationConsent.hasAgreed(); + } catch (e) { + debugWarn('[BACKGROUND] Could not check location permission: $e'); + _sessionLocationGranted = false; + } + } + + /// Starts Android's session service while a radio session is live and the + /// app is on screen, and keeps its notification in step with the session. + /// + /// Runs on every notify, so it stays synchronous and cheap: it asks the + /// platform nothing, and the start and the update are sent without waiting + /// (the update drops content that has not changed). It never stops the + /// service. The paths that end a session do that, once their upload and + /// session release are done. Until then (disconnecting, or the cleanup + /// after the step reads disconnected) nothing is pushed, so the + /// notification and the mode's wake lock stay as they were through the + /// upload. + void _syncConnectionService() { + if (!BackgroundServiceManager.followsConnection) return; + if (!_sessionActive) { + _serviceRefusalLogged = false; + _clearConnectionServiceStartFailure(); + return; + } + bool wouldStart({required bool locationGranted}) => + shouldStartConnectionService( + followsConnection: BackgroundServiceManager.followsConnection, + running: BackgroundServiceManager.isRunning, + starting: _connectionServiceStarting, + sessionActive: _sessionActive, + step: _connectionStep, + lifecycle: WidgetsBinding.instance.lifecycleState, + locationGranted: locationGranted, + ); + if (wouldStart(locationGranted: _sessionLocationGranted)) { + if (_connectionServiceStartFailed) return; + if (_connectionServiceStartAccepted) { + // Accepted, and now not running with the session still live: the + // check after the start found it never reached the foreground. + _markConnectionServiceStartFailed(); + return; + } + _connectionServiceStarting = true; + final n = _serviceNotificationNow(); + unawaited(BackgroundServiceManager.startService( + title: n.title, + body: n.body, + keepAwake: _keepServiceAwake, + mayStart: () => + WidgetsBinding.instance.lifecycleState == + AppLifecycleState.resumed && + _sessionActive, + ).whenComplete(() { + _connectionServiceStarting = false; + if (BackgroundServiceManager.isRunning) { + _connectionServiceStartAccepted = true; + } else if (_sessionActive) { + // Refused, or the channel call failed; the manager logged why. A + // session that ended meanwhile sent a stop, which is no failure. + _markConnectionServiceStartFailed(); + } + })); + return; + } + if (!_sessionLocationGranted && + !_serviceRefusalLogged && + wouldStart(locationGranted: true)) { + _serviceRefusalLogged = true; + debugWarn('[BACKGROUND] Not starting the service: location not granted'); + } + if (BackgroundServiceManager.isRunning && + _connectionStep != ConnectionStep.disconnecting) { + final n = _serviceNotificationNow(); + unawaited(BackgroundServiceManager.updateNotification( + title: n.title, + body: n.body, + keepAwake: _keepServiceAwake, + )); + } + } + + /// Holds back further session service starts (see + /// [_connectionServiceStartFailed]). Logged once, when it is set. + void _markConnectionServiceStartFailed() { + _connectionServiceStartFailed = true; + _connectionServiceStartAccepted = false; + debugWarn('[BACKGROUND] Not retrying the service start until the app is ' + 'back on screen'); + } + + /// Lets the session service be started again: on return to the app, and + /// when a session ends. + void _clearConnectionServiceStartFailure() { + _connectionServiceStartFailed = false; + _connectionServiceStartAccepted = false; + } + + /// On return to the app (Android): re-read the location grant, bring the + /// service in line with the session (a service that died in the background + /// is noticed, one left running with no session is stopped), then start it + /// again if the session still wants it. + Future _syncConnectionServiceAfterResume() async { + await _refreshSessionLocationGranted(); + await BackgroundServiceManager.healAfterResume( + sessionActive: _sessionActive); + if (_isDisposed) return; + _syncConnectionService(); + } + @override void didChangeAppLifecycleState(AppLifecycleState state) { + _syncGpsWithPolicy('app ${state.name}'); if (state == AppLifecycleState.resumed) { debugLog('[APP] App resumed from background'); + if (BackgroundServiceManager.followsConnection) { + // Back on screen: a start that failed earlier gets one more try. + _clearConnectionServiceStartFailure(); + unawaited(_syncConnectionServiceAfterResume()); + } _checkTcpHealthAfterResume(); + unawaited(_recheckLocationAccuracyAfterResume()); // Diagnostic: timers can be suspended while backgrounded; on resume, log // any countdown timer stuck past its deadline (intermittent ping lockout). _logStuckTimers('resume'); @@ -866,10 +1664,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { unawaited(_portalAccountService.checkLinkOnResume()); } else if (state == AppLifecycleState.paused) { debugLog('[APP] App paused (backgrounded)'); + // The process may be killed in the background before the debounce fires. + _mapViewStateSaver.flush(); // Save offline pings immediately on pause to prevent data loss if OS kills app if (_preferences.offlineMode && _apiQueueService.offlinePingCount > 0) { _autoSaveOfflinePings(); } + // Likewise the History session, which otherwise reaches storage only + // when its mode ends. + unawaited(_checkpointNoiseFloorSession('app paused')); } } @@ -915,8 +1718,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// This logging is here to capture the real trigger on-device; the actual fix /// is deferred until a debug log confirms it. See countdown_timer_service.dart. void _logStuckTimers(String reason) { + final now = DateTime.now(); void check(String name, CountdownTimerService t) { - if (t.isRunning && t.remainingMs == 0) { + if (countdownLooksStuck( + isRunning: t.isRunning, endTime: t.endTime, now: now)) { debugWarn( '[TIMER] $name isRunning past its deadline (stuck, remaining=0) — ' 'locks ping controls until restart [$reason]'); @@ -971,6 +1776,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String get deviceId => _deviceId; bool get preferencesLoaded => _preferencesLoaded; + + /// How the user last left the map (zoom, folded panels). See [MapViewState]. + MapViewState get mapViewState => _mapViewState; bool get onboardingGuideStateLoaded => _onboardingGuideProgress.isLoaded; bool get shouldShowOnboardingGuide => _onboardingGuideProgress.isDue; WatchBridgeService get watchBridge => _watchBridge; @@ -991,6 +1799,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? get connectionError => _connectionError; bool get isAuthError => _isAuthError; bool get isNetworkError => _isNetworkError; + + /// Non-null while the current connection error is the server refusing + /// this build as out of date. Tied to the error text so every path that + /// clears or replaces the error also drops the panel. + AppUpdateRequirement? get appUpdateRequirement { + final requirement = _appUpdateRequirement; + if (requirement == null || _connectionError != requirement.errorMessage) { + return null; + } + return requirement; + } BluetoothAdapterState get bluetoothAdapterState => _bluetoothAdapterState; bool get isBluetoothOn => _bluetoothAdapterState == BluetoothAdapterState.on; bool get isBluetoothOff => @@ -1066,39 +1885,62 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { int? get currentBatteryPercent => _currentBatteryPercent; List get discoveredDevices => _discoveredDevices; bool get isScanning => _isScanning; + + /// Whether the connect in progress can be cancelled right now: a BLE + /// transport connect on mobile, not an auto-reconnect. + bool get canCancelConnect => + !kIsWeb && + _bleTransportConnecting && + !_isAutoReconnecting && + _connectionStep == ConnectionStep.transportConnecting; + + /// True while a user cancel of the pending connect is still unwinding. + bool get isCancellingConnect => _isCancellingConnect; List get txPings => List.unmodifiable(_txPings); List get rxPings => List.unmodifiable(_rxPings); - /// Top 3 repeaters by best SNR from TX/DISC/Trace pings + /// The in-app Top Heard rows: the latest ping's repeaters by best SNR from + /// TX/DISC/Trace pings, up to the user's Top Heard Rows setting. List<({String repeaterId, double snr, OverlayPingType type})> - get topRepeatersBySnr => _topRepeatersOverlay; + get topRepeatersBySnr => + _topRepeatersOverlay.take(_preferences.topHeardRows).toList(); /// Best RX observation in the current 5-second window ({String repeaterId, double snr})? get rxOverlaySlot => _rxOverlaySlot; /// Update the top repeaters overlay with results from the latest TX/DISC/Trace ping. - /// Replaces all 3 slots entirely (no carryover from previous pings). Only a - /// ping that heard something calls this, so a silent ping leaves the last + /// Replaces every stored row entirely (no carryover from previous pings), + /// keeping up to [UserPreferences.topHeardRowsMax] so a higher Top Heard Rows + /// setting takes effect on the next rebuild without waiting for a ping. Only + /// a ping that heard something calls this, so a silent ping leaves the last /// heard set in place on the map, the watch and the Live Activity alike. /// - Parameter identities: display hash to the fullest identity this ping /// carried for it, for the ping types that carry more than a path byte. void _updateTopRepeaters( List<({String repeaterId, double snr})> current, OverlayPingType type, {Map? identities}) { - _overlayIdentityById = identities ?? const {}; - final bestSnr = {}; - for (final r in current) { - final key = r.repeaterId.toUpperCase(); - if (!bestSnr.containsKey(key) || r.snr > bestSnr[key]!) { - bestSnr[key] = r.snr; - } - } + // A short hop id that only one known repeater starts with joins that + // repeater's row (issue #637), so the identities move with it. Two + // different identities landing on one row cancel out, as contested + // discovery hashes do. + final rekeyed = {}; + final contested = {}; + (identities ?? const {}).forEach((displayId, identity) { + final key = _topHeardId(displayId); + final existing = rekeyed[key]; + if (existing != null && existing != identity) contested.add(key); + rekeyed[key] = identity; + }); + contested.forEach(rekeyed.remove); + _overlayIdentityById = rekeyed.isEmpty ? const {} : rekeyed; + final bestSnr = _heardIdResolver.bestSnrByRepeater(current, + hopBytes: _topHeardHopBytes); final fresh = bestSnr.entries .map((e) => (repeaterId: e.key, snr: e.value, type: type)) .toList() ..sort((a, b) => b.snr.compareTo(a.snr)); - _topRepeatersOverlay = fresh.take(3).toList(); - _topRepeatersOverlayTotalCount = fresh.length; + _topRepeatersOverlay = fresh.take(UserPreferences.topHeardRowsMax).toList(); + _topRepeatersOverlayHeardIds = bestSnr.keys.toSet(); _topRepeatersOverlayUpdatedAt = DateTime.now(); } @@ -1142,7 +1984,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Update the RX overlay slot — window matches auto-ping interval (best SNR wins). void _updateRxOverlaySlot(String repeaterId, double snr) { - final entry = (repeaterId: repeaterId.toUpperCase(), snr: snr); + final entry = (repeaterId: _topHeardId(repeaterId), snr: snr); if (_rxOverlayWindowTimer?.isActive ?? false) { if (_rxOverlaySlot == null || snr > _rxOverlaySlot!.snr) { _rxOverlaySlot = entry; @@ -1158,10 +2000,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } } - /// Clear all overlay state (top 3 + RX slot). + /// Clear all overlay state (top heard rows + RX slot). void _clearOverlayState() { _topRepeatersOverlay = []; - _topRepeatersOverlayTotalCount = 0; + _topRepeatersOverlayHeardIds = const {}; _topRepeatersOverlayUpdatedAt = null; _overlayIdentityById = const {}; _rxOverlaySlot = null; @@ -1175,22 +2017,32 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { List get discLogEntries => List.unmodifiable(_discLogEntries); List get traceLogEntries => List.unmodifiable(_traceLogEntries); + List get scopeLogEntries => _scopeLog.entries; List get errorLogEntries => List.unmodifiable(_errorLogEntries); - List get unifiedPingLogEntries { - final merged = [ - ..._txLogEntries.map((e) => UnifiedPingLogEntry( - type: PingLogType.tx, timestamp: e.timestamp, entry: e)), - ..._rxLogEntries.map((e) => UnifiedPingLogEntry( - type: PingLogType.rx, timestamp: e.timestamp, entry: e)), - ..._discLogEntries.map((e) => UnifiedPingLogEntry( - type: PingLogType.disc, timestamp: e.timestamp, entry: e)), - ..._traceLogEntries.map((e) => UnifiedPingLogEntry( - type: PingLogType.trace, timestamp: e.timestamp, entry: e)), - ]; - merged.sort(); - return merged; + + /// True while the error log holds an error the user has not seen yet. + bool get hasUnseenErrors => errorLogHasUnseen( + hasEntries: _errorLogEntries.isNotEmpty, + logged: _errorsLogged, + seen: _errorsSeen); + + /// Told by the Log screen whenever the Errors tab comes on or goes off + /// screen. Everything logged so far counts as seen once it is showing. + void setErrorLogOnScreen(bool onScreen) { + if (_errorLogOnScreen == onScreen) return; + _errorLogOnScreen = onScreen; + if (!onScreen || !hasUnseenErrors) return; + _errorsSeen = _errorsLogged; + notifyListeners(); } + List get unifiedPingLogEntries => mergeUnifiedPingLog( + tx: _txLogEntries, + rx: _rxLogEntries, + disc: _discLogEntries, + trace: _traceLogEntries, + scopes: _scopeLog.entries, + ); ({double lat, double lon})? get mapNavigationTarget => _mapNavigationTarget; int get mapNavigationTrigger => _mapNavigationTrigger; @@ -1218,6 +2070,46 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? get zoneName => _currentZone?['name'] as String?; String? get zoneCode => _currentZone?['code'] as String?; + /// The multi-region group the current zone belongs to, or null. + ZoneGroup? get zoneGroup => parseZoneGroup(_currentZone); + String? get zoneGroupCode => zoneGroup?.code; + + /// Full code to show for the zone: the group's when there is one. + String? get displayZoneCode => zoneGroupCode ?? zoneCode; + + /// [displayZoneCode] cut for the short labels (chips, status bar, + /// Live Activity, watch, Siri). + String? get shortZoneCode { + final code = displayZoneCode; + return code == null ? null : shortZoneLabel(code); + } + + /// Name to show for the zone: the group's when the server sent one. + String? get displayZoneName => zoneGroup?.name ?? zoneName; + + /// Subdomain coverage is read from (`.meshmapper.net`): the group's + /// own site merges every member. Repeaters and borders are still fetched + /// from the member's site (which already answers for the whole group) but + /// are keyed on this code, see [_repeaterContextKey]. + String? get coverageHostCode => zoneGroupCode ?? zoneCode; + + /// The context the repeater list and the borders are keyed on: the group + /// when the zone belongs to one, else the zone. A move between two members + /// of the same group keeps the key, so neither list is cleared or refetched + /// for it. Leaving the group changes the key and clears both, as a plain + /// zone change always did. + String? get _repeaterContextKey => coverageHostCode; + + /// Logs the group once per change, so a drive across a group's members + /// does not repeat it on every zone check. + void _noteZoneGroupChange(String? previous) { + final group = zoneGroup; + if (group?.code == previous) return; + debugLog(group == null + ? '[APP] Zone group: none' + : '[APP] Zone group: ${group.code} (${group.members.length} members)'); + } + /// MapWidget handshake: whether the coverage overlay is currently on the /// map. Gates the post-wardrive fresh-tile flow — no overlay, no fetches. void reportVectorOverlayActive(bool active) { @@ -1235,8 +2127,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ? _coveragePatchCells : const {}; - /// Drop the session patch — the cells belong to one region + grid preset - /// (called on zone change and when the Grid Mode preference changes). + /// Drop the session patch: the cells belong to one region or group plus + /// grid preset (called on a coverage host change and when the Grid Mode + /// preference changes). void clearCoveragePatch() { _coveragePatchCells.clear(); _coveragePatchVersion++; @@ -1251,13 +2144,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// the z14 tile. attempt 1 fires +7s after upload; attempt 2 (+10s) runs /// only when attempt 1 saw no changed tiles (ingestion can lag the post). Future _freshenAffectedVectorTiles({required int attempt}) async { - final zone = zoneCode; + final zone = coverageHostCode; if (zone == null || zone != _pendingFreshZone || _pendingFreshCoords.isEmpty) { - // Zone changed since the coords were queued: they belong to the OLD - // region's grid — freshening them against the new region's server - // would be pure wasted renders. + // Coverage host changed since the coords were queued: they belong to + // the OLD region's (or group's) grid, so freshening them against the + // new host's server would be pure wasted renders. _pendingFreshCoords.clear(); return; } @@ -1347,7 +2240,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { anyVerdict = true; debugLog('[COVERAGE] No new tile ${e.key} (unchanged)'); } else { - debugLog('[COVERAGE] Tile ${e.key} fresh check failed'); + final reason = result.noVerdictReason ?? 'unknown'; + if (reason == 'header absent') { + debugLog('[COVERAGE] Tile ${e.key} no verdict (header absent)'); + } else { + debugLog('[COVERAGE] Tile ${e.key} fresh check failed ($reason)'); + } } if (e.value[0] == 14 && result.body != null) { z14Bodies.add(result.body!); @@ -1438,6 +2336,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final seen = {}; for (final body in bodies) { for (final cell in decodeCoverageCells(body)) { + // A block's i/j index k by k 300 m blocks, not cells of this grid, + // so it can never be the user's own cell. Fresh z14 tiles carry no + // blocks today; this keeps a block from matching by accident. + if (cell.isBlock) continue; if (wanted.contains('${cell.i}_${cell.j}') && seen.add(cell.id)) { out.add(cell); } @@ -1448,6 +2350,16 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { int? get zoneSlotsAvailable => _currentZone?['slots_available'] as int?; int? get zoneSlotsMax => _currentZone?['slots_max'] as int?; + + /// The zone's flood veto for the current radio preset, as /status (or a + /// later /auth) reported it. Null when the server sent no `flood_disabled` + /// key (an older server); `slotsChipState` then falls back to guessing + /// from `slots_max == 0`. + bool? get zoneFloodDisabled { + final zone = _currentZone; + if (zone == null || !zone.containsKey('flood_disabled')) return null; + return zone['flood_disabled'] == true; + } String? get nearestZoneName => _nearestZone?['name'] as String?; String? get nearestZoneCode => _nearestZone?['code'] as String?; double? get nearestZoneDistanceKm => @@ -1532,6 +2444,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { '${(_zoneGraceSecondsRemaining % 60).toString().padLeft(2, '0')}'; // Zone transfer getters + /// The group the session's zone belonged to when the session was minted, + /// or null. Compared against [zoneGroupCode] on every zone check. + String? get sessionGroupCode => _sessionGroupCode; bool get isZoneTransferInProgress => _isZoneTransferInProgress; String? get zoneTransferFrom => _zoneTransferFrom; String? get zoneTransferTo => _zoneTransferTo; @@ -1569,15 +2484,16 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { int get repeaterCount => _repeaters.length; /// Lazy tap-to-inspect: fetch raw coverage points for a clicked map cell from - /// the current zone's app endpoint. Returns `[]` when there is no zone or on - /// failure. The caller aggregates these into a GRID SUMMARY (read-only — no - /// state mutation, so no `notifyListeners`). + /// the coverage host's app endpoint (the region's, or the group's when the + /// zone belongs to one). Returns `[]` when there is no zone or on failure. + /// The caller aggregates these into a GRID SUMMARY (read-only: no state + /// mutation, so no `notifyListeners`). Future>> fetchCellCoverage({ required double lat, required double lon, required double radiusMeters, }) { - final zone = zoneCode; + final zone = coverageHostCode; if (zone == null || zone.isEmpty) { return Future.value(const >[]); } @@ -1590,7 +2506,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } /// Lazy tap-to-inspect: fetch the coverage points referencing a repeater - /// (hex-prefix superset) from the current zone's app endpoint. The caller + /// (hex-prefix superset) from the coverage host's app endpoint (the + /// region's, or the group's when the zone belongs to one). The caller /// aggregates these into the repeater's BIDIR/TX/RX/DISC/DEAD totals + max /// range. /// @@ -1602,7 +2519,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { Future>?> fetchRepeaterCoveragePoints({ required String prefix, }) { - final zone = zoneCode; + final zone = coverageHostCode; if (zone == null || zone.isEmpty) { debugWarn('[COVERAGE] repeater points requested with no zone, ' 'reporting unavailable rather than empty'); @@ -1663,15 +2580,69 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ? _apiService.apiSmartPingDays : _preferences.smartPingDays; + /// Whether flood (TX) pings wait only in green squares and discovery + /// requests are never held: the server's when enforced, else the user's. + bool get smartPingFloodOnly => _apiService.enforceSmartPing + ? _apiService.apiSmartPingFloodOnly + : _preferences.smartPingFloodOnly; + + /// Companion firmware code (byte 1 of RESP_CODE_DEVICE_INFO) scope + /// discovery needs to ask a repeater at all. Below it the setting still + /// saves, but nothing is asked and nothing extra goes on the air. + static const int kScopeDiscoveryCompanionVersionCode = + kScopeDiscoveryFirmwareFloor; + + /// Whether scope discovery is forced on by the regional admin (auth + /// `scope_discovery`). + bool get enforceScopeDiscovery => _apiService.enforceScopeDiscovery; + + /// Effective scope discovery switch: the admin's veto wins over the user, + /// same shape as [smartPingEnabled]. + bool get scopeDiscoveryEnabled => + _apiService.enforceScopeDiscovery || _preferences.scopeDiscoveryEnabled; + + /// Effective refresh window in days: the server's when enforced, else the + /// user's. + int get scopeRefreshDays => _apiService.enforceScopeDiscovery + ? _apiService.apiScopeRefreshDays + : _preferences.scopeDiscoveryDays; + + /// Whether scope discovery may actually run right now: the server offered + /// it on the last live auth, the effective switch is on, Offline Mode never + /// asks, and the connected companion's firmware can carry the request. + bool get scopeDiscoveryActive => scopeDiscoveryGateOpen(_scopeGateInputs); + + ScopeGateInputs get _scopeGateInputs => ( + offered: _apiService.scopeDiscoveryOffered, + enforced: _apiService.enforceScopeDiscovery, + userEnabled: _preferences.scopeDiscoveryEnabled, + offlineMode: offlineMode, + firmwareCode: companionFirmwareVersionCode, + ); + + /// Whether the connected radio's firmware is below the scope discovery + /// floor. Drives the extra warning line on the Settings switch; see + /// [scopeDiscoveryFirmwareTooOld]. + bool get scopeDiscoveryNeedsNewerFirmware => scopeDiscoveryFirmwareTooOld( + connected: isConnected, firmwareCode: companionFirmwareVersionCode); + + /// True while the connected companion has stopped asking a repeater that + /// is not a saved contact for its scopes (its contact table is full). + /// Raw, not gated on being connected. The transition to true also drops a + /// warning in the error log; see [_wireScopeCannotAskNonContacts]. + bool get scopeCannotAskNonContacts => + _meshCoreConnection?.scopeCannotAskNonContacts ?? false; + /// Null means the ordinary all-time overlay. Regional window overrides apply. int? get coverageOverlayDays => smartPingEnabled && _preferences.smartPingRecentCoverageOnly ? smartPingDays : null; - /// A patch must come from the same region, grid, preset and time filter. + /// A patch must come from the same region or group, grid, preset and time + /// filter. String get coverageOverlayContext => - '$zoneCode|${_preferences.coverageGridSize}|$radioFilterKey|$coverageOverlayDays'; + '$coverageHostCode|${_preferences.coverageGridSize}|$radioFilterKey|$coverageOverlayDays'; bool get discDropEnabled => _preferences.discDropEnabled || _apiService.enforceDiscDrop; @@ -1859,7 +2830,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { phaseEndsAt: phase.endsAt, phaseDurationMs: _phaseDurationMsFor(phase.endsAt), isConnected: isConnected, - zoneCode: zoneCode ?? _sessionZoneCode ?? _preferences.iataCode, + zoneCode: shortZoneCode ?? _sessionZoneCode ?? _preferences.iataCode, showRepeaterNames: _preferences.liveActivityShowNames, ); } @@ -1923,7 +2894,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { phaseDurationMs: phaseDurationMs, pingColor: pingColor, isConnected: isConnected, - zoneCode: zoneCode ?? _sessionZoneCode ?? _preferences.iataCode, + zoneCode: shortZoneCode ?? _sessionZoneCode ?? _preferences.iataCode, txCount: _pingStats.txCount, rxCount: _pingStats.rxCount, discoveryCount: _pingStats.discCount, @@ -1974,10 +2945,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final position = _resolveWatchPosition(); final ranking = _resolveRankingPosition(); - // The wrist mirrors the map's "Top Heard" overlay: the latest ping's top - // three by SNR plus the current RX slot. Same source, so the two surfaces - // can never disagree. - final top = _topRepeatersOverlay; + // The wrist mirrors the map's "Top Heard" overlay: the top three of the + // same stored list, plus the current RX slot. Same source, so the two + // surfaces can never disagree. The list is cut to three here by design: the + // Live Activity, CarPlay and watch show 3 ping rows plus RX, whatever the + // in-app Top Heard Rows setting is. buildHeard's RX cap is the backstop. + final top = _topRepeatersOverlay.take(_surfaceTopHeardRows).toList(); final rxSlot = _rxOverlaySlot; // Overlay IDs are hex path hashes. Resolved from the fullest identity each @@ -2006,6 +2979,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { rxAt: _liveActivityRxUpdatedAt, lat: ranking?.lat, lon: ranking?.lon, + nicknames: _repeaterNicknames, ); // The readout still needs the fix and Top Heard, but none of the arrays @@ -2295,6 +3269,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { traceEntries: _traceLogEntries, repeaters: _repeaters, hopBytes: _hopBytes, + nicknames: _repeaterNicknames, ); final phase = _resolveWatchPhase(); final passive = sessionStartAvailability(AutoMode.passive); @@ -2331,7 +3306,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { phaseTitle: phase.title, phaseDetail: phase.detail, phaseEndsAt: phase.endsAt, - zoneCode: zoneCode ?? _sessionZoneCode ?? _preferences.iataCode, + zoneCode: shortZoneCode ?? _sessionZoneCode ?? _preferences.iataCode, txCount: _pingStats.txCount, rxCount: _pingStats.rxCount, discoveryCount: _pingStats.discCount, @@ -2389,7 +3364,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { phase.title, phase.detail, phase.endsAt?.millisecondsSinceEpoch, - zoneCode ?? _sessionZoneCode ?? _preferences.iataCode, + shortZoneCode ?? _sessionZoneCode ?? _preferences.iataCode, _pingStats.txCount, _pingStats.rxCount, _pingStats.discCount, @@ -2716,11 +3691,51 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ); } + // The dial runs on its own and is never abandoned. The intent only waits + // up to the answer window for it: a reachable radio finishes well inside + // that, and an unreachable one would outlast iOS's 30 second limit on the + // intent, which then discards our answer and shows a generic failure. + final shortId = + command.id.length > 8 ? command.id.substring(0, 8) : command.id; + final window = lastCompanionAnswerWindow(command.expiresAt); + final dialStarted = DateTime.now(); + debugLog('[SIRI] Connect $shortId: dialling ${remembered!.displayName}, ' + 'answering within ${window.inMilliseconds}ms'); + var answered = false; + final dial = _reconnectForSiri(remembered).then((completion) { + final elapsed = DateTime.now().difference(dialStarted).inMilliseconds; + debugLog('[SIRI] Connect $shortId: dial finished in ${elapsed}ms, ' + 'success=${completion.success}' + '${answered ? ' (after the intent was answered)' : ''}'); + return completion; + }); + final completion = await dial.timeout(window, onTimeout: () { + debugLog('[SIRI] Connect $shortId: still dialling after ' + '${window.inMilliseconds}ms, answering that it is underway'); + return ExternalCommandCompletion( + success: true, + disposition: ExternalCommandDisposition.admitted, + message: ExternalCommandReason.other( + 'MeshMapper is connecting to ${remembered.displayName}. ' + 'Check the app in a moment.', + ), + ); + }); + answered = true; + return completion; + } + + /// One reconnect to [remembered] for the connect intent, as a completion. + /// Never throws, because the intent may already have been answered and + /// nothing else awaits it. + Future _reconnectForSiri( + RememberedDevice remembered, + ) async { try { await reconnectToRememberedDevice(); final reconnectedDevice = (_activeTransport ?? _bluetoothService).connectedDevice; - if (isConnected && reconnectedDevice?.id == remembered!.id) { + if (isConnected && reconnectedDevice?.id == remembered.id) { return ExternalCommandCompletion( success: true, disposition: ExternalCommandDisposition.admitted, @@ -2729,12 +3744,19 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ), ); } + if (_connectRefusedForPreciseLocation) { + return const ExternalCommandCompletion( + success: false, + disposition: ExternalCommandDisposition.refused, + message: ExternalCommandReason.other(preciseLocationVoiceMessage), + ); + } return ExternalCommandCompletion( success: false, disposition: ExternalCommandDisposition.refused, message: ExternalCommandReason.other( _connectionError ?? - 'MeshMapper could not connect to ${remembered!.displayName}.', + 'MeshMapper could not connect to ${remembered.displayName}.', ), ); } catch (error) { @@ -2744,7 +3766,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { disposition: ExternalCommandDisposition.refused, message: ExternalCommandReason.other( _connectionError ?? - 'MeshMapper could not connect to ${remembered!.displayName}.', + 'MeshMapper could not connect to ${remembered.displayName}.', ), ); } @@ -2969,7 +3991,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { pingColor: pingColor, modeColor: _resolveLiveActivityModeColor(phase.phase), isConnected: isConnected, - zoneCode: zoneCode ?? _sessionZoneCode ?? _preferences.iataCode, + zoneCode: shortZoneCode ?? _sessionZoneCode ?? _preferences.iataCode, noiseFloorDbm: _bucketedNoiseFloorDbm(), companionBatteryPct: _bucketedCompanionBatteryPct(), showRepeaterNames: _preferences.liveActivityShowNames, @@ -3090,16 +4112,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ? (endsAt: t.endTime!, durationMs: null, remainingSec: t.remainingSec) : null; - /// The Live Activity's rows are the map's Top Heard box, the same list the - /// watch mirrors, so the three surfaces cannot disagree. The ordering, the - /// RX slot and the current-or-last rule live in [buildLiveActivityHeard]. + /// The Live Activity's rows are the first three of the map's Top Heard list, + /// the same three the watch mirrors, so the surfaces cannot disagree. The + /// ordering, the RX slot and the current-or-last rule live in + /// [buildLiveActivityHeard]. ({ List repeaters, int totalCount, bool isCurrent, }) _buildLiveActivityRepeaters() => buildLiveActivityHeard( - top: _topRepeatersOverlay, - topTotalCount: _topRepeatersOverlayTotalCount, + top: _topRepeatersOverlay.take(_surfaceTopHeardRows).toList(), + topHeardIds: _topRepeatersOverlayHeardIds, rxSlot: _rxOverlaySlot, topAt: _topRepeatersOverlayUpdatedAt, rxAt: _liveActivityRxUpdatedAt, @@ -3120,31 +4143,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? _resolveRepeaterDisplayName(String rawId) { final displayId = rawId.toUpperCase(); - - // Try the fullest identity the row arrived with, then the display hash. - // - // **The fallback is the point.** A discovery response's public key is a - // better identity, but the catalogue is matched by an 8-character `hexId` - // that the API frequently omits, and the display hash additionally resolves - // through `displayHexId` — which falls back to the short numeric ID when - // there is no hex at all. Trying only the longer form threw away the lookup - // that was doing the work, and left named repeaters unnamed. - final identity = _overlayIdentityById[displayId]; - final match = (identity == null - ? null - : ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: _repeaters, - id: identity, - hopBytes: _hopBytes, - )) ?? - ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: _repeaters, - id: displayId, - hopBytes: _hopBytes, - ); - - final name = match?.name; - return name == null || name == 'Unknown' ? null : name; + // Why the display hash is tried as well as the identity: see + // resolveOverlayRow. + final match = ExternalSurfaceGeoBuilder.resolveOverlayRow( + displayId: displayId, + identity: _overlayIdentityById[displayId], + repeaters: _repeaters, + hopBytes: _hopBytes, + ); + if (match == null) return null; + // The user's nickname wins over the server's name. + final nickname = RepeaterNicknames.nicknameFor(match, _repeaterNicknames); + if (nickname != null) return nickname; + final name = match.name; + return name == 'Unknown' ? null : name; } // ============================================ @@ -3178,6 +4190,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Every queued item is stamped with the mode that produced it. _apiQueueService.autoModeGetter = () => wireAutoMode; _apiQueueService.radioConfigGetter = () => liveRadioConfig; + _apiQueueService.scopesAllowedGetter = () => _apiService.scopeDiscoveryOffered; // MyMeshMapper portal account. Mobile only — the sign-in flow needs an // OS-registered URL scheme, which the web build cannot have. @@ -3244,14 +4257,34 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // those pings honestly instead of uploading claims the server will skip // while reporting success. _apiService.onSessionIdChanged = (previousSessionId, newSessionId) async { - await _apiQueueService.dropStaleTaggedItems(); - // The server credits one deferred square per session id, so a square - // reported under the old session is owed again under the new one. - _recentCoverage.clearDeferred(); + await _onSessionReplaced(); }; _apiService.onSessionExpiredRecovery = _recoverExpiredLiveSession; + // A keepalive that finds the session expired while nothing is running + // lets it lapse instead of minting one that would never see a ping. The + // next Start or manual ping re-mints it through its own session check. + _apiService.isSessionIdle = () => sessionIsIdle( + autoPingEnabled: _autoPingEnabled, + autoPingStarting: _autoPingStarting, + pendingDisable: isPendingDisable, + pingSending: _isPingSending, + pingInProgress: isPingInProgress, + repeaterAdminOpen: _repeaterAdminSession != null, + queuedItems: _apiQueueService.queueSize, + ); + + // A live /auth answer (a session recovery included) can withdraw scope + // discovery while a lease is mid-exchange; the runner must stop before + // its next write, not at the next sweep. Restoring it while Passive or + // Hybrid keeps running re-arms the periodic repeater refresh, the same + // sequence a fresh mode start uses. + _apiService.onScopeDiscoveryChanged = () => _scopeLifecycle.onGateChanged( + _scopeGateInputs, + passiveOrHybridRunning: _isPassiveOrHybridModeRunning, + startRepeaterRefresh: _startScopeRepeaterRefreshForRunningMode); + _apiService.onRegionalCarpeaters = (keys, error) { unawaited(_onRegionalCarpeaters(keys, error)); }; @@ -3334,6 +4367,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { BackgroundServiceManager.updateNotification( title: n.title, body: n.body, + keepAwake: _keepServiceAwake, ); } }; @@ -3349,17 +4383,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (_vectorOverlayActive) { // Queue the batch's coords for the +7s fresh-tile check; the user's // own cells land on the map via the session patch (see - // _freshenAffectedVectorTiles). A DEFER changes no tile (the server - // keeps deferrals in a table nothing renders), so it is left out and - // a batch of nothing but deferrals arms nothing. - final hasCoverageRows = uploadedItems.any((i) => i.type != 'DEFER'); - for (final item in uploadedItems) { - if (item.type == 'DEFER') continue; - if (_pendingFreshCoords.length >= 16) break; - _pendingFreshCoords.add([item.latitude, item.longitude]); - } - if (hasCoverageRows) { - _pendingFreshZone = zoneCode; + // _freshenAffectedVectorTiles). A DEFER or a SCOPES changes no tile + // (see changesCoverage), so each is left out and a batch of nothing + // but those arms nothing: a SCOPES uploaded after its DISC used to + // schedule a second refresh, retry included, for unchanged tiles. + final refresh = coverageRefreshFor(uploadedItems, + alreadyPending: _pendingFreshCoords.length); + _pendingFreshCoords.addAll(refresh.coords); + if (refresh.armsRefresh) { + _pendingFreshZone = coverageHostCode; _vectorFreshTimer?.cancel(); _vectorFreshTimer = Timer(const Duration(seconds: 7), () { _freshenAffectedVectorTiles(attempt: 1); @@ -3395,7 +4427,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[INIT] Loading preferences...'); await _loadPreferences(); await _loadRegionalCarpeaters(); + await _loadRepeaterNicknames(); await _loadRepeaterClaims(); + await _loadScopeDiscoveryState(); await _loadLastRadioConfig(); await _loadWatchPairingPreference(); await _loadDeviceAntennaPreferences(); @@ -3559,9 +4593,28 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Check zone on first GPS lock (when _inZone is null) // Skip zone checks when offline mode is enabled - if (_inZone == null && !_preferences.offlineMode) { - debugLog('[GEOFENCE] First GPS lock, triggering zone check'); - await checkZoneStatus(); + // A coarse fix is never sent: the server would only answer 403 + // gps_inaccurate, once per fix. Wait for the stream (or the 10 s + // retry's fresh read) to bring a better one. A retry already armed for + // another reason (network, server) owns the next attempt, so a fix does + // not stack a second request on top of it. + // Nor while the policy holds GPS off (a background launch, or a late + // fix after a background stop): the zone check would send this fix to + // the server with the app off screen and no radio. The start on resume + // brings a fresh first lock. + if (_gpsStoppedByPolicy) { + // Held; see above. + } else if (_inZone == null && !_preferences.offlineMode) { + if (!GpsService.isAccurateForZoneCheck(position)) { + _noteZoneCheckWaitingForGps(position); + } else if (_isCheckingZone || + (_zoneCheckCountdownTimer != null && + _zoneCheckErrorReason != 'gps_inaccurate')) { + // In flight or a retry is already scheduled; let that one answer. + } else { + debugLog('[GEOFENCE] First GPS lock, triggering zone check'); + await checkZoneStatus(); + } _firstGpsLockLogged = true; } else if (_inZone == null && _preferences.offlineMode && @@ -3575,9 +4628,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Skip zone checks when offline mode is enabled // Not while airborne: at cruise every fix is 100 m from the last, and // this branch would ask the server about zones once a second for hours. + // Not on a coarse fix either: a jumpy weak fix often lands 100 m away, + // and its 403 used to replace a good result moments old. + // Nor while a no-answer retry is counting down: driving in an outage + // hit /status every 100 m and reset the backoff each time. if (!isConnected && + !_gpsStoppedByPolicy && !_preferences.offlineMode && !_gpsService.isAirborne && + GpsService.isAccurateForZoneCheck(position) && + !(_zoneCheckCountdownTimer != null && + _zoneCheckErrorReason == 'network') && _shouldRecheckZone(position)) { // Throttle log to once per 30s to avoid spam while driving final now = DateTime.now(); @@ -3611,9 +4672,18 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[INIT] GPS position listener attached to stream'); // Start GPS (may skip if permissions not yet granted - disclosure flow handles that) - debugLog('[INIT] Starting GPS service...'); - await _gpsService.startWatching(); - debugLog('[INIT] GPS service started, status: ${_gpsService.status}'); + // A cold start that is not on screen yet, with no radio (a location- + // triggered launch, say), must not start GPS. _syncGpsWithPolicy makes the + // first, full start when the app comes on screen. + if (!_gpsPolicyApplies || _gpsRunDecision == GpsRunDecision.run) { + debugLog('[INIT] Starting GPS service...'); + await _gpsService.startWatching(); + debugLog('[INIT] GPS service started, status: ${_gpsService.status}'); + } else { + _gpsStoppedByPolicy = true; + _gpsInitialStartPending = true; + debugLog('[GPS] Not started yet: waiting for the app to be on screen'); + } // Initialize audio service for sound notifications await _audioService.initialize(); @@ -3623,17 +4693,39 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[INIT] Final init state: gpsStatus=$_gpsStatus, ' 'inZone=$_inZone, isCheckingZone=$_isCheckingZone, hasPosition=${_currentPosition != null}, ' 'offlineMode=${_preferences.offlineMode}'); + if (kDebugMode && StoreCaptureConfig.active != null) { + unawaited(_seedStoreCapture()); + } notifyListeners(); } /// Restart GPS service after permission disclosure is accepted - /// Called from MainScaffold after user grants location permission - Future restartGpsAfterPermission() async { + /// Called from MainScaffold after user grants location permission. + /// + /// [keepTracking] is for the return from the background, where the watcher + /// was running a moment ago (see [GpsService.startWatching]). + Future restartGpsAfterPermission({bool keepTracking = false}) async { debugLog('[GPS] restartGpsAfterPermission() called'); debugLog('[GPS] Pre-restart state: gpsStatus=$_gpsStatus, inZone=$_inZone, ' 'isCheckingZone=$_isCheckingZone, hasPosition=${_currentPosition != null}'); - await _gpsService.startWatching(); + // Not on screen and no radio (a background launch, say): hold the start. + // _syncGpsWithPolicy makes the first, full start once the app is resumed. + if (deferGpsStartAfterPermission( + keepTracking: keepTracking, + alreadyWatching: _gpsService.isWatching, + policyApplies: _gpsPolicyApplies, + decision: _gpsRunDecision, + )) { + _gpsStoppedByPolicy = true; + _gpsInitialStartPending = true; + debugLog('[GPS] Not started yet: waiting for the app to be on screen'); + return; + } + + _gpsStoppedByPolicy = false; + _gpsInitialStartPending = false; + await _gpsService.startWatching(keepTracking: keepTracking); _gpsStatus = _gpsService.status; // Sync after restart debugLog('[GPS] GPS restarted, new status: $_gpsStatus'); @@ -3649,6 +4741,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { '[GPS] Permission granted with existing position - triggering zone check'); await checkZoneStatus(); } + // A permission just granted lets the session service start on this + // notify, for a radio session already live. + if (BackgroundServiceManager.followsConnection) { + await _refreshSessionLocationGranted(); + } notifyListeners(); } @@ -3713,6 +4810,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _isScanning = true; _discoveredDevices = []; _connectionError = null; + // A failed connect leaves the step at error, and the bottom Scan button + // only enables at disconnected, so clearing the error alone left it grey + // until the app was restarted. + if (_connectionStep == ConnectionStep.error) { + debugLog('[SCAN] Clearing failed connect state (error -> disconnected)'); + _connectionStep = ConnectionStep.disconnected; + } _isAuthError = false; _isNetworkError = false; notifyListeners(); @@ -3742,6 +4846,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } _discoveredDevices.add(enrichedDevice); selectedDevice = enrichedDevice; + // Once per new device, so "my companion is not listed" reports + // show what the scan actually saw. + debugLog('[SCAN] Found "${enrichedDevice.name}" ' + 'id=${enrichedDevice.id} rssi=${enrichedDevice.rssi}'); notifyListeners(); } }, @@ -3756,6 +4864,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await completer.future; _activeScanSubscription = null; + if (_isScanning) _logScanSummary('ended'); _isScanning = false; notifyListeners(); @@ -3773,10 +4882,16 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await _activeScanSubscription?.cancel(); _activeScanSubscription = null; await _bluetoothService.stopScan(); + if (_isScanning) _logScanSummary('stopped'); _isScanning = false; notifyListeners(); } + void _logScanSummary(String how) { + final n = _discoveredDevices.length; + debugLog('[SCAN] Scan $how: $n device${n == 1 ? '' : 's'} found'); + } + // ============================================ // Connection // ============================================ @@ -3827,7 +4942,27 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Creates the two-stage auth callback for MeshCoreConnection Step 6. /// Shared by all transport types (BLE, TCP, USB Serial). Future?> Function() _createAuthCallback() { + // Made right after the attempt installs its connection, so these name + // the attempt this callback serves. + final generation = _connectGeneration; + final connection = _meshCoreConnection; + bool superseded() => authCallbackSuperseded( + createdAtGeneration: generation, + currentGeneration: _connectGeneration, + sameConnection: identical(_meshCoreConnection, connection), + ); + Map supersededResult(String where) { + debugLog('[AUTH] Connect attempt superseded $where, not calling the ' + 'API'); + return { + 'success': false, + 'reason': 'superseded', + 'message': 'Connection attempt superseded', + }; + } + return () async { + if (superseded()) return supersededResult('before auth'); final publicKey = _meshCoreConnection!.devicePublicKey; if (publicKey == null) { debugError('[APP] Cannot request auth: no public key'); @@ -3913,6 +5048,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // last one left in preferences (#426). _applyConnectingDevicePower(deviceName); + // The server refuses a fix coarser than 50 m, so send the best one + // there is: the current fix, a good one from the last 60 s, or a short + // bounded wait for one. With none, the current fix goes as before. + final authFix = await _pickAuthFix(); + if (superseded()) return supersededResult('while preparing auth'); + // Stage 1: Try existing public_key authentication debugLog( '[APP] Stage 1: Attempting auth with public_key: ${publicKey.substring(0, 16)}...'); @@ -3932,6 +5073,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final result = await _apiService.requestAuth( reason: 'connect', + // An answer that lands after an abandon must not install a session + // the disconnected app would then think it holds. + shouldStoreSession: () => !superseded(), publicKey: publicKey, who: deviceName, appVersion: _appVersion, @@ -3941,10 +5085,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _meshCoreConnection!.deviceInfo?.manufacturer ?? 'Unknown', radioFreq: _meshCoreConnection?.selfInfo?.radioConfigApi, - lat: _currentPosition?.latitude, - lon: _currentPosition?.longitude, - accuracyMeters: _currentPosition?.accuracy, + lat: authFix?.latitude, + lon: authFix?.longitude, + accuracyMeters: authFix?.accuracy, ); + if (superseded()) return supersededResult('during auth'); if (result != null && result['maintenance'] == true) { _maintenanceMode = true; @@ -4013,8 +5158,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { }; } + if (superseded()) return supersededResult('before registration'); final registerResult = await _apiService.requestAuth( reason: 'register', + shouldStoreSession: () => !superseded(), contactUri: contactUri, who: deviceName, appVersion: _appVersion, @@ -4024,9 +5171,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _meshCoreConnection!.deviceInfo?.manufacturer ?? 'Unknown', radioFreq: _meshCoreConnection?.selfInfo?.radioConfigApi, - lat: _currentPosition?.latitude, - lon: _currentPosition?.longitude, - accuracyMeters: _currentPosition?.accuracy, + lat: authFix?.latitude, + lon: authFix?.longitude, + accuracyMeters: authFix?.accuracy, ); if (registerResult == null) { @@ -4122,6 +5269,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { errorParts.length > 1 ? errorParts.sublist(1).join(':') : null; _isNetworkError = reason == 'network_error'; _connectionError = _getErrorMessage(reason, serverMessage); + if (reason == 'outofdate') { + _appUpdateRequirement = await _buildAppUpdateRequirement( + _connectionError!, serverMessage); + } } else { _connectionError = 'Authentication failed'; } @@ -4139,6 +5290,42 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _isConnecting = false; _connectionStep = ConnectionStep.error; notifyListeners(); + // The failed connect ends the session, unless a reconnect or a connect + // re-run carries it on. A disconnect cleanup still running (the failed + // link's own, usually) stops the service at its end instead, after its + // session release: a stop landing in the middle of that release can let + // the backgrounded process freeze before it is sent. + if (BackgroundServiceManager.followsConnection && + !_isAutoReconnecting && + !_connectRerunPending && + _disconnectCleanupDepth == 0) { + unawaited(BackgroundServiceManager.stopService()); + } + } + + /// Works out the update panel's version line and store link after the + /// server refused this build. The installer read never throws: a failure + /// falls back to the store listing for the platform. + Future _buildAppUpdateRequirement( + String errorMessage, String? serverMessage) async { + String? installerStore; + try { + installerStore = + await installerStoreReader().timeout(const Duration(seconds: 2)); + } catch (e) { + debugWarn('[APP] Could not read installer store: $e'); + } + final link = StoreLinks.resolve(defaultTargetPlatform, installerStore, + isBetaBuild: AppConstants.isDevelopmentBuild); + final required = parseRequiredAppVersion(serverMessage); + debugLog('[APP] App out of date: have $_appVersion, server needs ' + '${required ?? 'unknown'}, installer ${installerStore ?? 'unknown'}, ' + 'update via ${link.uri}'); + return AppUpdateRequirement( + errorMessage: errorMessage, + versionLine: appUpdateVersionLine(_appVersion, required), + link: link, + ); } /// Set up disconnect listener for non-BLE transports (TCP, USB Serial). @@ -4165,6 +5352,44 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { }); } + /// Cancel a BLE connect that is still waiting on the radio. + /// + /// Only the transport stage can be cancelled: past it the handshake is + /// talking to the radio and has its own cleanup. The in-flight + /// connectToDevice is invalidated through [_connectGeneration], so its + /// failure is ignored and no error card is shown. + Future cancelConnect() async { + if (!canCancelConnect || _isCancellingConnect) { + debugLog('[CONN] Cancel ignored: connect is not at a cancellable stage ' + '(step=$_connectionStep, transport=$_bleTransportConnecting, ' + 'cancelling=$_isCancellingConnect)'); + return; + } + debugLog('[CONN] User cancelled the connect'); + _isCancellingConnect = true; + _connectGeneration++; + _bleTransportConnecting = false; + notifyListeners(); + try { + await _bluetoothService.cancelConnect(); + } catch (e) { + debugWarn('[CONN] Cancelling the BLE connect failed: $e'); + } finally { + _isCancellingConnect = false; + _isConnecting = false; + _connectionStep = ConnectionStep.disconnected; + _connectionError = null; + _isAuthError = false; + _isNetworkError = false; + notifyListeners(); + // The cancelled attempt is abandoned without a cleanup of its own, so + // the session ends here. + if (BackgroundServiceManager.followsConnection) { + unawaited(BackgroundServiceManager.stopService()); + } + } + } + /// Connect to a discovered device Future connectToDevice(DiscoveredDevice device) async { if (_isConnecting) { @@ -4172,8 +5397,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } if (_refuseConnectIfAirborne()) return; + if (await _refuseConnectIfImprecise('BLE')) return; _isConnecting = true; final myGeneration = ++_connectGeneration; + // Read now, so the notify below can start the session service with no + // await between the tap's state change and the start. + if (BackgroundServiceManager.followsConnection) { + await _refreshSessionLocationGranted(); + } _connectionStep = ConnectionStep.transportConnecting; _connectionError = null; _isAuthError = false; @@ -4201,12 +5432,30 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // During auto-reconnect the internal retry loop is capped to one // attempt: the reconnect ladder retries on its own, and a 3x15s // internal loop would eat the whole 30s reconnect budget in one call. - await _bluetoothService.connect(device.id, - maxAttempts: _isAutoReconnecting ? 1 : null); + _bleTransportConnecting = true; + notifyListeners(); // shows the Cancel button + try { + await _bluetoothService.connect(device.id, + maxAttempts: _isAutoReconnecting ? 1 : null); + } finally { + if (myGeneration == _connectGeneration) { + _bleTransportConnecting = false; + notifyListeners(); // hides it + } + } + if (myGeneration != _connectGeneration) { + // Cancelled (or superseded) just as the link opened. The canceller + // closes the link; this attempt must not build on it. + debugLog('[CONN] Transport connected after the attempt was ' + 'cancelled, abandoning it'); + return; + } transportConnectedAt = DateTime.now(); _activeTransport = _bluetoothService; debugLog('[APP] Creating new MeshCoreConnection'); _meshCoreConnection = MeshCoreConnection(transport: _bluetoothService); + _wireScopeRadioBusy(_meshCoreConnection!); + _wireScopeCannotAskNonContacts(_meshCoreConnection!); if (!_preferences.offlineMode) { _meshCoreConnection!.onRequestAuth = _createAuthCallback(); @@ -4217,6 +5466,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Listen for step changes _meshCoreConnection!.stepStream.listen((step) { + // A superseded attempt (an abandoned reconnect) must not move the + // step a newer connection or the abandon's cleanup now owns. + if (myGeneration != _connectGeneration) return; _connectionStep = step; if (step == ConnectionStep.connected) { // Update device info @@ -4283,6 +5535,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final connectionResult = await _deviceModelService.runConnection( _meshCoreConnection!.connect, ); + if (myGeneration != _connectGeneration) { + // Abandoned while the workflow ran. The abandon closed the link and + // its cleanup owns the state; a newer connect may own the transport. + debugLog('[CONN] Connection workflow finished after the attempt ' + 'was superseded, abandoning it'); + return; + } await _postConnectionSetup(connectionResult, device); _isConnecting = false; @@ -4311,20 +5570,48 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { workflowRerunUsed = true; debugLog( '[CONN] Handshake died ${sinceTransportConnect!.inSeconds}s after transport connect, re-running connection workflow once: $e'); + // Set before the failure's cleanup can flip the step to disconnected, + // so the session reads as live (GPS, the session service) until the + // re-run takes over or is abandoned. Every exit below clears it. + _connectRerunPending = true; // The failed run's transport disconnect emits a 'disconnected' event // whose listener starts _fullDisconnectCleanup. That event was queued // before this timer, and microtasks drain before timers fire, so after // the delay the tracked future (if any) is the cleanup for THIS // failure. Waiting it out means the cleanup cannot tear down the // re-run's fresh connection. - await Future.delayed(const Duration(milliseconds: 100)); - final cleanupInFlight = _fullCleanupInFlight; - if (cleanupInFlight != null) { - await cleanupInFlight; + try { + await Future.delayed(const Duration(milliseconds: 100)); + final cleanupInFlight = _fullCleanupInFlight; + if (cleanupInFlight != null) { + await cleanupInFlight; + } + } catch (cleanupError) { + // The cleanup's error would otherwise leave this method with the + // flag still set, and the session would read as live for good: no + // later disconnect could stop GPS or the session service. + _connectRerunPending = false; + debugWarn('[CONN] Disconnect cleanup failed, abandoning the ' + 'workflow re-run: $cleanupError'); + // A newer attempt owns the shared state; the check below hands + // over to it without touching that state. + if (myGeneration == _connectGeneration) { + await _handleConnectionError(e); + return; + } } if (myGeneration != _connectGeneration) { debugLog( '[CONN] Skipping workflow re-run: a newer connection attempt owns the transport'); + _connectRerunPending = false; + // The newer attempt may already have failed, and its stop was held + // back while this re-run was pending. One still connecting owns + // the service. + if (BackgroundServiceManager.followsConnection && + !_sessionActive && + !_isConnecting) { + unawaited(BackgroundServiceManager.stopService()); + } return; } if (_isConnecting) { @@ -4332,11 +5619,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // still up (e.g. _postConnectionSetup threw on a live link), so // there is nothing safe to re-run on top of. Hand the error to the // normal failure path instead of swallowing it. + _connectRerunPending = false; await _handleConnectionError(e); return; } _isConnecting = true; _connectionStep = ConnectionStep.transportConnecting; + _connectRerunPending = false; _connectionError = null; // The disconnect cleanup cleared the BLE scan cache; restore the // device name for the re-run. @@ -4359,13 +5648,35 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } if (_refuseConnectIfAirborne()) return; + if (await _refuseConnectIfImprecise('TCP')) return; _isConnecting = true; - _connectGeneration++; // invalidate any pending BLE workflow re-run + // Also invalidates any pending BLE workflow re-run. An abandoned TCP + // reconnect bumps it again, and this attempt then stands down as the BLE + // one in connectToDevice does. + final myGeneration = ++_connectGeneration; + // Read now, so the notify below can start the session service with no + // await between the tap's state change and the start. + if (BackgroundServiceManager.followsConnection) { + await _refreshSessionLocationGranted(); + } _connectionStep = ConnectionStep.transportConnecting; _connectionError = null; _isAuthError = false; _isNetworkError = false; notifyListeners(); + TcpService? tcpService; + StreamSubscription? mySubscription; + // Closes only what this attempt opened, leaving anything a newer + // connection has installed since. + void releaseSupersededTransport() { + if (identical(_transportConnectionSubscription, mySubscription)) { + _transportConnectionSubscription = null; + } + mySubscription?.cancel(); + if (identical(_activeTransport, tcpService)) _activeTransport = null; + tcpService?.dispose(); + } + try { if (_meshCoreConnection != null) { debugLog('[APP] Disposing previous MeshCoreConnection'); @@ -4375,14 +5686,23 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await _apiQueueService.clearBeforeConnect(); - final tcpService = TcpService(host: host, port: port); + tcpService = TcpService(host: host, port: port); debugLog('[APP] Connecting TCP transport to $host:$port'); await tcpService.openConnection(); + if (myGeneration != _connectGeneration) { + debugLog('[CONN] TCP transport connected after the attempt was ' + 'superseded, abandoning it'); + releaseSupersededTransport(); + return; + } _activeTransport = tcpService; _setupTransportDisconnectListener(tcpService); + mySubscription = _transportConnectionSubscription; debugLog('[APP] Creating new MeshCoreConnection (TCP)'); _meshCoreConnection = MeshCoreConnection(transport: tcpService); + _wireScopeRadioBusy(_meshCoreConnection!); + _wireScopeCannotAskNonContacts(_meshCoreConnection!); if (!_preferences.offlineMode) { _meshCoreConnection!.onRequestAuth = _createAuthCallback(); @@ -4392,6 +5712,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } _meshCoreConnection!.stepStream.listen((step) { + // A superseded attempt must not move the step a newer connection or + // the abandon's cleanup now owns. + if (myGeneration != _connectGeneration) return; _connectionStep = step; if (step == ConnectionStep.connected) { _manufacturerString = _meshCoreConnection!.deviceInfo?.manufacturer; @@ -4450,6 +5773,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final connectionResult = await _deviceModelService.runConnection( _meshCoreConnection!.connect, ); + if (myGeneration != _connectGeneration) { + debugLog('[CONN] TCP connection workflow finished after the attempt ' + 'was superseded, abandoning it'); + releaseSupersededTransport(); + return; + } final device = DiscoveredDevice( id: '$host:$port', @@ -4461,6 +5790,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await TcpService.saveConnection(host, port, displayDeviceName ?? ''); _isConnecting = false; } catch (e) { + if (myGeneration != _connectGeneration) { + // A newer attempt (or the abandon's cleanup) owns the error state + // and whatever transport is current now. + debugLog('[CONN] Superseded TCP connection attempt failed, ' + 'ignoring: $e'); + releaseSupersededTransport(); + return; + } await _handleConnectionError(e); if (_activeTransport != null && _activeTransport != _bluetoothService) { _activeTransport!.dispose(); @@ -4477,8 +5814,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } if (_refuseConnectIfAirborne()) return; + if (await _refuseConnectIfImprecise('USB')) return; _isConnecting = true; _connectGeneration++; // invalidate any pending BLE workflow re-run + // Read now, so the notify below can start the session service with no + // await between the tap's state change and the start. + if (BackgroundServiceManager.followsConnection) { + await _refreshSessionLocationGranted(); + } _connectionStep = ConnectionStep.transportConnecting; _connectionError = null; _isAuthError = false; @@ -4513,6 +5856,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[APP] Creating new MeshCoreConnection (USB Serial)'); _meshCoreConnection = MeshCoreConnection(transport: serialService); + _wireScopeRadioBusy(_meshCoreConnection!); + _wireScopeCannotAskNonContacts(_meshCoreConnection!); if (!_preferences.offlineMode) { _meshCoreConnection!.onRequestAuth = _createAuthCallback(); @@ -4615,8 +5960,14 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } if (_refuseConnectIfAirborne()) return; + if (await _refuseConnectIfImprecise('serial')) return; _isConnecting = true; _connectGeneration++; // invalidate any pending BLE workflow re-run + // Read now, so the notify below can start the session service with no + // await between the tap's state change and the start. + if (BackgroundServiceManager.followsConnection) { + await _refreshSessionLocationGranted(); + } _connectionStep = ConnectionStep.transportConnecting; _connectionError = null; _isAuthError = false; @@ -4636,6 +5987,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[APP] Creating new MeshCoreConnection (generic transport)'); _meshCoreConnection = MeshCoreConnection(transport: transport); + _wireScopeRadioBusy(_meshCoreConnection!); + _wireScopeCannotAskNonContacts(_meshCoreConnection!); if (!_preferences.offlineMode) { _meshCoreConnection!.onRequestAuth = _createAuthCallback(); @@ -4819,12 +6172,23 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[MAP] Radio preset changed for repeaters ' '(${priorRepeaterFilterKey ?? 'none'} -> ${radioFilterKey ?? 'none'}); ' 'reloading repeater list for zone ${zone ?? 'unknown'}'); - _repeatersLoaded = false; - _repeatersLoadedForIata = null; + _invalidateRepeatersForContext(); if (zone != null && zone.isNotEmpty) { _fetchRepeatersForZone( zone); // fire-and-forget, matches the zone-check path } + } else { + // Scope discovery reads the server's scope stamps off this list, so a + // stale one is refreshed at connect (fire-and-forget). + final zone = zoneCode; + if (zone != null && + zone.isNotEmpty && + scopeRepeaterRefreshDue( + active: scopeDiscoveryActive, + loadedAt: _repeatersLoadedAt, + now: DateTime.now())) { + unawaited(_refreshRepeatersForScopes(zone)); + } } _syncRecentCoverage(); @@ -4888,6 +6252,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ); _pingService!.unifiedRxHandler = _unifiedRxHandler; + _pingService!.scopeRunnerFactory = _buildScopeRunner; _pingService!.checkExternalAntennaConfigured = () { return _preferences.externalAntennaSet; @@ -4969,11 +6334,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { BackgroundServiceManager.updateNotification( title: n.title, body: n.body, + keepAwake: _keepServiceAwake, ); } }; - _pingService!.checkRecentCoverage = _recentCoverage.isCovered; + _pingService!.checkRecentCoverage = + (lat, lon, kind) => _recentCoverage.isCovered(lat, lon, + forTx: kind == BankedPingType.tx); + _pingService!.isRecentCoverageActive = () => _recentCoverage.isActive; // A marker per deferral once the phone has moved the minimum ping // distance, and one DEFER per fixed 300 m square per API session. The @@ -5034,7 +6403,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { }; _pingService!.onEchoReceived = (txPing, repeater, isNew) { - _recentCoverage.markCovered(txPing.latitude, txPing.longitude); + _recentCoverage.markCovered( + txPing.latitude, txPing.longitude, CoverageColor.green); debugLog('[APP] ========== ECHO CALLBACK RECEIVED =========='); debugLog( '[APP] Real-time echo: ${repeater.repeaterId} (SNR: ${repeater.snr ?? 'null'}, isNew: $isNew)'); @@ -5173,8 +6543,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _addDiscLogEntry(entry); }; + _pingService!.onDiscPingAborted = _removeDiscLogEntry; + _pingService!.onDiscNodeDiscovered = (discPing, nodeEntry, isNew) { - _recentCoverage.markCovered(discPing.latitude, discPing.longitude); + _recentCoverage.markCovered( + discPing.latitude, discPing.longitude, CoverageColor.cyan); debugLog( '[APP] Real-time disc node: ${nodeEntry.repeaterId}, isNew=$isNew'); if (isNew) { @@ -5462,6 +6835,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } _sessionZoneCode = zoneCode; + _sessionGroupCode = zoneGroupCode; if (!_preferences.offlineMode) { _startZoneRefreshTimer(); @@ -5510,11 +6884,27 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } // Repeater administrators: refresh the cached claims for this companion. - // Strictly non-fatal, and skipped on an old server. - try { - unawaited(_reconcileRepeaterClaims(reason: 'connect')); - } catch (e) { - debugWarn('[RADMIN] Claims reconcile failed to start: $e'); + // Strictly non-fatal, and skipped on an old server. Auto-reconnects in + // one session refresh at most every few minutes. + final now = DateTime.now(); + final session = _apiService.sessionId; + if (shouldReconcileClaimsOnConnect( + autoReconnect: _isAutoReconnecting, + sessionId: session, + lastSessionId: _lastConnectClaimsReconcileSession, + lastAt: _lastConnectClaimsReconcileAt, + now: now, + )) { + _lastConnectClaimsReconcileAt = now; + _lastConnectClaimsReconcileSession = session; + try { + unawaited(_reconcileRepeaterClaims(reason: 'connect')); + } catch (e) { + debugWarn('[RADMIN] Claims reconcile failed to start: $e'); + } + } else { + debugLog('[RADMIN] Claims reconcile skipped on reconnect: refreshed ' + '${now.difference(_lastConnectClaimsReconcileAt!).inSeconds}s ago'); } } @@ -5727,7 +7117,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { externalAntenna: _preferences.externalAntenna, noiseFloor: _meshCoreConnection?.lastNoiseFloor, power: _preferences.powerLevel, - altitude: entry.alt, + altitude: entry.altitude.meters, + altitudeRef: entry.altitude.wireReference, + altitudeAccuracy: entry.altitude.accuracy, ); // Update UI (throttled — dense mesh RX must not churn the map) @@ -5744,7 +7136,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return ( lat: pos.latitude, lon: pos.longitude, - alt: GpsService.altitudeOrNull(pos), + altitude: _gpsService.fixAltitudeOf(pos), ); }, @@ -6007,6 +7399,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { bool flushQueue = true, }) { late final Future cleanup; + // Counted before the call: its synchronous prefix runs inside it and can + // already notify. + _disconnectCleanupDepth++; cleanup = _fullDisconnectCleanupImpl( releaseExtras: releaseExtras, flushQueue: flushQueue, @@ -6014,11 +7409,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (identical(_fullCleanupInFlight, cleanup)) { _fullCleanupInFlight = null; } + _disconnectCleanupDepth--; + if (!_isDisposed) _syncGpsWithPolicy('disconnect cleanup done'); }); _fullCleanupInFlight = cleanup; return cleanup; } + /// A connect is running or has connected. + bool get _connectLive => + _isConnecting || _connectionStep == ConnectionStep.connected; + Future _fullDisconnectCleanupImpl({ Map? releaseExtras, bool flushQueue = true, @@ -6030,8 +7431,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } _cancelPendingAutoPingRestore(); + _scopeLifecycle.onEvent(ScopeStopEvent.disconnectCleanup); _isConnecting = false; _connectionStep = ConnectionStep.disconnected; + // Connect is enabled again from here, so a connect the user starts during + // the awaits below can install its own connection before this cleanup + // ends. The end disposes only what is current now (see there). + final cleanupGeneration = _connectGeneration; + final cleanupConnection = _meshCoreConnection; + final cleanupPingService = _pingService; + final cleanupTransport = _activeTransport; + final cleanupTransportSubscription = _transportConnectionSubscription; // Cancel any active zone grace period _cancelZoneGraceTimers(); @@ -6064,6 +7474,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Stop RX logger _rxLogger?.stopWardriving(trigger: 'ble_disconnect'); + // Save offline pings, as disconnect() does. The noise floor session above + // is already stored, so skipping this left a drive in History with no + // offline file once the unsaved pings were gone (no-op with no pings). + await _saveOfflineSession(); + // Force upload any pending items BEFORE releasing session if (flushQueue && _apiService.hasSession) { debugLog('[CONN] Flushing API queue before session release'); @@ -6079,8 +7494,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Clear any remaining items and stop batch timer await _apiQueueService.clearOnDisconnect(); - // Release API session (best effort - don't block on failure) - if (_devicePublicKey != null && _apiService.hasSession) { + // Release API session (best effort - don't block on failure). + // A connect the user started during the awaits above may already hold + // the session (the server hands the same key the same id), so only + // release it when nothing has connected since this cleanup began. An + // unreleased session expires on the server. + final releaseOwned = cleanupOwnsCurrentConnection( + cleanupGeneration: cleanupGeneration, + currentGeneration: _connectGeneration, + newerConnectLive: _connectLive, + ); + if (!releaseOwned && _apiService.hasSession) { + debugLog('[CONN] Not releasing the API session: a newer connect owns it'); + } + if (releaseOwned && _devicePublicKey != null && _apiService.hasSession) { debugLog('[CONN] Releasing API session due to disconnect'); try { await _apiService.requestAuth( @@ -6102,22 +7529,84 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await closeRepeaterAdminSession(); - _meshCoreConnection?.dispose(); - _meshCoreConnection = null; - _pingService?.dispose(); - _pingService = null; - - // Clean up non-BLE transport - _transportConnectionSubscription?.cancel(); - _transportConnectionSubscription = null; - if (_activeTransport != null && _activeTransport != _bluetoothService) { - _activeTransport!.dispose(); + if (cleanupOwnsCurrentConnection( + cleanupGeneration: cleanupGeneration, + currentGeneration: _connectGeneration, + newerConnectLive: _connectLive, + )) { + // Nothing is connected or connecting since the cleanup started, so + // what is current is this cleanup's to dispose, and so is anything it + // started with that a failed connect has since swapped out. + if (!identical(_meshCoreConnection, cleanupConnection)) { + cleanupConnection?.dispose(); + } + if (!identical(_pingService, cleanupPingService)) { + cleanupPingService?.dispose(); + } + if (!identical( + _transportConnectionSubscription, cleanupTransportSubscription)) { + cleanupTransportSubscription?.cancel(); + } + if (cleanupTransport != null && + cleanupTransport != _bluetoothService && + !identical(_activeTransport, cleanupTransport)) { + cleanupTransport.dispose(); + } + _meshCoreConnection?.dispose(); + _meshCoreConnection = null; + _pingService?.dispose(); + _pingService = null; + + // Clean up non-BLE transport + _transportConnectionSubscription?.cancel(); + _transportConnectionSubscription = null; + if (_activeTransport != null && _activeTransport != _bluetoothService) { + _activeTransport!.dispose(); + } + _activeTransport = null; + } else { + // A connect started during this cleanup owns the current objects. + // Dispose only the ones this cleanup started with, where the new + // connect has not taken them over (the shared BLE service, say). + debugLog('[CONN] A newer connect started during disconnect cleanup, ' + 'leaving its connection alone'); + if (!identical(_meshCoreConnection, cleanupConnection)) { + cleanupConnection?.dispose(); + } + if (!identical(_pingService, cleanupPingService)) { + cleanupPingService?.dispose(); + } + if (!identical( + _transportConnectionSubscription, cleanupTransportSubscription)) { + cleanupTransportSubscription?.cancel(); + } + if (cleanupTransport != null && + cleanupTransport != _bluetoothService && + !identical(_activeTransport, cleanupTransport)) { + cleanupTransport.dispose(); + } + } + + // A reconnect keeps the foreground service running (see + // _startAutoReconnect), and nothing else stops it once the reconnect is + // given up, or when a drop skips the reconnect (USB, no remembered + // radio). Stop it last, after the queue upload and session release above, + // so the process is not frozen in the background halfway through them. + // Android's session service runs for the whole radio session, so it stays + // up when the session carries on past this cleanup (a connect re-run). + if (shouldStopServiceAtCleanupEnd( + followsConnection: BackgroundServiceManager.followsConnection, + sessionActive: _sessionActive, + )) { + await BackgroundServiceManager.stopService(); } - _activeTransport = null; } /// Start auto-reconnect after unexpected transport disconnect Future _startAutoReconnect() async { + // Counted at the drop, before the waits below. + final keepsDropping = _reconnectFlapGuard.onDrop(DateTime.now()); + _scopeLifecycle.onEvent(ScopeStopEvent.autoReconnect); _invalidateLiveSessionRecovery(); await _waitForLiveSessionRecovery(); // Defensive: cancel zone grace period if active @@ -6131,6 +7620,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _cancelIdleDisconnectTimer(); _isAutoReconnecting = true; _reconnectAttempt = 0; + _reconnectBudgetSpent = false; _reconnectStartedAt = DateTime.now(); _lastReconnectWasBondError = false; _connectionStep = ConnectionStep.reconnecting; @@ -6164,10 +7654,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // to the car instead of at the radio going out of range. The abandon path // stops the service through _fullDisconnectCleanup, and a success that // restores auto-ping updates this notification rather than starting a - // second service. + // second service. The notification reads Reconnecting from here (see + // _serviceNotificationNow). + final reconnecting = _serviceNotificationNow(); await BackgroundServiceManager.updateNotification( - title: 'MeshMapper - Reconnecting', - body: 'Trying to reach ${_rememberedDevice?.name ?? 'your radio'}', + title: reconnecting.title, + body: reconnecting.body, + keepAwake: _keepServiceAwake, ); // Clean up dead BLE-dependent objects @@ -6208,6 +7701,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return; } + // A link that reconnects and drops again within seconds, time after time, + // would otherwise loop for as long as the user let it, with no alert. + if (keepsDropping) { + debugWarn('[CONN] Radio dropped ${_reconnectFlapGuard.flaps} times in ' + 'a row within ${_reconnectFlapGuard.window.inSeconds}s of ' + 'reconnecting, giving up'); + logError( + 'Disconnected: the radio kept dropping right after reconnecting. ' + 'Check its power and battery.', + severity: ErrorSeverity.error); + _abandonAutoReconnect(); + return; + } + // Start overall timeout _reconnectTimeoutTimer = Timer(_autoReconnectBudget, () { final armed = _reconnectStartedAt; @@ -6216,6 +7723,18 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { : ' (armed ${DateTime.now().difference(armed).inSeconds}s ago)'; debugLog('[CONN] Auto-reconnect timed out after ' '${_autoReconnectBudget.inSeconds}s$late'); + if (reconnectBudgetGivesConnectGrace( + connectInFlight: _reconnectConnectInFlight != null, + graceUsed: _reconnectBudgetSpent)) { + _reconnectBudgetSpent = true; + debugLog('[CONN] A connect is still in flight, giving it ' + '${_reconnectInFlightGrace.inSeconds}s more'); + _reconnectTimeoutTimer = Timer(_reconnectInFlightGrace, () { + debugLog('[CONN] Auto-reconnect grace ran out'); + _abandonAutoReconnect(); + }); + return; + } _abandonAutoReconnect(); }); @@ -6225,6 +7744,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Attempt a single reconnection void _attemptReconnect() { + if (_reconnectBudgetSpent) { + debugLog('[CONN] Auto-reconnect: budget spent, not retrying'); + _abandonAutoReconnect(); + return; + } if (_reconnectAttempt >= _maxReconnectAttempts) { debugLog( '[CONN] Auto-reconnect: max attempts reached ($_maxReconnectAttempts)'); @@ -6250,19 +7774,49 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _abandonAutoReconnectForAirborne(); return; } + // Cheap re-read, no prompt: the session started precise, so this only + // catches Precise Location turned off while the radio was away. + final precise = await _preciseLocationGate.allowsConnect( + platform: PreciseLocationGate.currentPlatform, + simulatorEnabled: _gpsService.isSimulatorEnabled, + canPrompt: false, + entry: 'auto-reconnect', + ); + if (!_isAutoReconnecting) return; // Cancelled during the read + if (!precise) { + _abandonAutoReconnectForImpreciseLocation(); + return; + } + final attempt = _ReconnectConnectAttempt(); try { debugLog( '[CONN] Auto-reconnect: calling reconnectToRememberedDevice()'); - await reconnectToRememberedDevice(); + _reconnectConnectInFlight = attempt; + try { + await reconnectToRememberedDevice(); + } finally { + if (identical(_reconnectConnectInFlight, attempt)) { + _reconnectConnectInFlight = null; + } + } - // Timeout or cancel fired while connection was in-flight. - // Disconnect the orphaned connection — abandon already cleaned up state. - if (!_isAutoReconnecting) { - if (_connectionStep == ConnectionStep.connected) { + // Timeout or cancel fired while connection was in-flight. Disconnect + // an orphaned connection, but only one that is this attempt's own: + // after a cancel the user may already be on a newer connection, and + // a newer reconnect may own the state by now. + if (attempt.abandonedAtGeneration != null || !_isAutoReconnecting) { + if (shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: attempt.abandonedAtGeneration, + currentGeneration: _connectGeneration, + connected: _connectionStep == ConnectionStep.connected, + )) { debugLog( '[CONN] Auto-reconnect completed after timeout — disconnecting orphaned connection'); disconnect(); + } else { + debugLog('[CONN] Auto-reconnect attempt ended after the ' + 'reconnect was over, leaving the current connection alone'); } return; } @@ -6272,7 +7826,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog( '[CONN] Auto-reconnect succeeded on attempt $_reconnectAttempt'); _lastReconnectWasBondError = false; - _onReconnectSuccess(); + await _onReconnectSuccess(); } else if (_isAutoReconnecting) { // Connection failed but didn't throw - try again debugLog( @@ -6284,7 +7838,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } catch (e) { debugError( '[CONN] Auto-reconnect attempt $_reconnectAttempt failed: $e'); - if (_isAutoReconnecting) { + if (attempt.abandonedAtGeneration == null && _isAutoReconnecting) { // Check for iOS apple-code 14 (Peer removed pairing information) // The MeshCore device cleared its bond keys — clear iOS stale bond before retrying await _handleBondErrorIfNeeded(e); @@ -6342,19 +7896,32 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } /// Called when auto-reconnect succeeds - void _onReconnectSuccess() { + Future _onReconnectSuccess() async { + _reconnectFlapGuard.onReconnectSuccess(DateTime.now()); // Cancel timers _reconnectTimer?.cancel(); _reconnectTimer = null; _reconnectTimeoutTimer?.cancel(); _reconnectTimeoutTimer = null; + // The connect workflow's step 6 POSTs /auth on every reconnect (the + // server reuses a live session, else mints one), so an online reconnect + // lands with a session and this branch is not taken. It is the backstop + // for the one state that must never persist: connected, online, and no + // session (a group handoff superseded in its release-to-mint gap). Ends + // as the abandon path does when the session cannot be had, before the + // reconnect state below is cleared so that path sees it as today. + if (!_preferences.offlineMode && !_apiService.hasSession) { + if (!await _reacquireSessionAfterReconnect()) return; + } + final wasAutoPing = _autoPingWasEnabled; final previousMode = _autoModeBeforeReconnect; // Clear reconnect state _isAutoReconnecting = false; _reconnectAttempt = 0; + _reconnectBudgetSpent = false; _reconnectStartedAt = null; _autoPingWasEnabled = false; @@ -6387,11 +7954,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } }); } else { - // No auto-ping to restore, so nothing needs the foreground service any - // more. _startAutoReconnect deliberately left it running to keep the - // process alive through the reconnect window; without this it would sit - // there showing "Reconnecting" for a link that is already back up. - unawaited(BackgroundServiceManager.stopService()); + // iOS: no auto-ping to restore, so nothing needs the per-mode service + // any more. _startAutoReconnect deliberately left it running to keep + // the process alive through the reconnect window; without this it + // would sit there for a link that is already back up. Android's session + // service runs for the whole connection, and the notify below turns its + // notification back to Connected. + if (!BackgroundServiceManager.followsConnection) { + unawaited(BackgroundServiceManager.stopService()); + } // No auto-ping to restore — start idle timer _startIdleDisconnectTimer(); } @@ -6399,16 +7970,141 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { notifyListeners(); } + /// Re-acquires an API session for a reconnected radio that has none, the + /// way a live session is replaced (`_mintAndApplyReplacementSession`, the + /// recovery's and the handoff's back half), then re-arms what the connect + /// path's session branch arms: session zone, zone refresh timer, keepalive. + /// False means the reconnect ended here (or was superseded): with the + /// radio still connected, through the live-link path; with the link gone, + /// by handing back to the ordinary auto-reconnect. + Future _reacquireSessionAfterReconnect() async { + final connection = _meshCoreConnection; + final publicKey = _devicePublicKey; + final zone = zoneCode; + if (connection == null || + publicKey == null || + zone == null || + zone.isEmpty) { + debugError('[CONN] Reconnected without an API session and no zone to ' + 're-join: ending the session'); + await _abandonReconnectOnLiveLink( + 'no region to re-join after reconnecting'); + return false; + } + debugWarn('[CONN] Reconnected without an API session: re-acquiring one ' + 'in $zone'); + // _ownsSessionRecovery reads !_isAutoReconnecting, which is still set + // here on purpose (the abandon path reads the reconnect state), so the + // ownership test is the reconnect's own. + bool owns() => + !_isDisposed && + _isAutoReconnecting && + !_userRequestedDisconnect && + !_preferences.offlineMode && + _connectionStep == ConnectionStep.connected && + identical(_meshCoreConnection, connection) && + _devicePublicKey == publicKey; + final result = await _mintAndApplyReplacementSession( + connection: connection, + publicKey: publicKey, + iataCode: zone, + owns: owns, + tag: '[CONN]', + what: 'reconnect', + ); + // The step does not change on a transport drop, and the BLE listener + // leaves a drop alone while _isAutoReconnecting is set (an attempt's own + // failure is the usual cause), so a link lost during the POST above is + // read off the transport itself rather than off owns(). + final linkUp = + _activeTransport?.connectionStatus == ConnectionStatus.connected; + switch (reconnectBackstopOutcome( + superseded: result == SessionRecoveryResult.superseded, + minted: result == SessionRecoveryResult.recovered, + linkUp: linkUp, + )) { + case ReconnectBackstopOutcome.superseded: + return false; + case ReconnectBackstopOutcome.handBackToReconnect: + debugWarn('[CONN] Link dropped while re-acquiring a session after ' + 'reconnect (mint ${result.name}): reconnecting again'); + await _restartAutoReconnectAfterBackstop(); + return false; + case ReconnectBackstopOutcome.abandonOnLiveLink: + debugError('[CONN] Could not re-acquire a session after reconnect: ' + 'ending the session'); + await _abandonReconnectOnLiveLink( + 'could not re-acquire a session after reconnecting'); + return false; + case ReconnectBackstopOutcome.restore: + break; + } + _sessionZoneCode = zone; + _sessionGroupCode = zoneGroupCode; + _startZoneRefreshTimer(); + _apiService.enableHeartbeat( + gpsProvider: () { + final pos = _gpsService.lastPosition; + if (pos == null) return null; + return (lat: pos.latitude, lon: pos.longitude); + }, + ); + debugLog('[CONN] Session re-acquired after reconnect in $zone'); + return true; + } + + /// Ends a reconnect that landed with the radio connected but no session, + /// the way a failed visible transfer's auth does: through `disconnect()`, + /// which deletes the channel while BLE is still up (Rule 8), restores the + /// radio's name and path mode, and closes the transport. + /// `_abandonAutoReconnect` assumes a dead link and does none of that, so + /// taken here it showed Disconnected with the radio still connected and + /// the channel still on it, and a later Connect could stumble on the open + /// link. The abandon's alert is kept, dated to the drop as there, and the + /// reason goes to the error log so the user learns why the session ended. + Future _abandonReconnectOnLiveLink(String why) async { + if (_autoPingWasEnabled) { + _playDisconnectAlert(_reconnectStartedAt ?? DateTime.now()); + } + logError('Disconnected: $why', severity: ErrorSeverity.error); + await disconnect(); + } + + /// Hands a reconnect whose link dropped during the session backstop back + /// to the ordinary auto-reconnect. The BLE listener already saw the drop + /// and, with `_isAutoReconnecting` still set, left it to an attempt that + /// was no longer running, and `_onReconnectSuccess` cancelled the reconnect + /// timers before the backstop ran, so nothing else restarts it. The + /// auto-ping state captured at the original drop is carried over: + /// `_startAutoReconnect` reads it from `_autoPingEnabled`, which the + /// backstop never got as far as restoring. + Future _restartAutoReconnectAfterBackstop() async { + final wasAutoPing = _autoPingWasEnabled; + final previousMode = _autoModeBeforeReconnect; + _isAutoReconnecting = false; + _reconnectAttempt = 0; + await _startAutoReconnect(); + // The airborne branch inside abandons at once and has already cleared + // this state; only a reconnect that is actually running takes it back. + if (_isAutoReconnecting) { + _autoPingWasEnabled = wasAutoPing; + _autoModeBeforeReconnect = previousMode; + } + } + /// Cancel auto-reconnect (called from UI cancel button) void cancelAutoReconnect() { debugLog('[CONN] Auto-reconnect cancelled by user'); - _abandonAutoReconnect(); + // The user ended it, so the "stopped unexpectedly" alert would be wrong. + _abandonAutoReconnect(alert: false); } /// Abandon auto-reconnect and do full cleanup. [releaseExtras] rides on the /// session release; [flushQueue] false drops the preserved queue instead of - /// uploading it first. + /// uploading it first. [alert] false skips the disconnect alert (a user + /// cancel). void _abandonAutoReconnect({ + bool alert = true, Map? releaseExtras, bool flushQueue = true, }) { @@ -6418,12 +8114,35 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _reconnectTimeoutTimer?.cancel(); _reconnectTimeoutTimer = null; _cancelPendingAutoPingRestore(); + _reconnectBudgetSpent = false; + + // Supersede a connect still in flight, so that when it ends it touches + // nothing a newer connection owns (the shared BLE transport, the step). + final inFlight = _reconnectConnectInFlight; + _reconnectConnectInFlight = null; + if (inFlight != null) { + _connectGeneration++; + inFlight.abandonedAtGeneration = _connectGeneration; + _bleTransportConnecting = false; + // The reconnect's prep already disposed the connection from before the + // drop, so one here is the stale attempt's own. Dispose it now, not at + // the end of the cleanup below: that is several awaits away (queue + // flush, session release), and until then a failing workflow would + // still disconnect the shared transport, dropping a connect the user + // starts meanwhile, and its frames would go out on that new link. + final stale = _meshCoreConnection; + if (stale != null) { + debugLog('[CONN] Disposing the abandoned reconnect\'s connection'); + _meshCoreConnection = null; + stale.dispose(); + } + } // Alert if auto-ping was running before disconnect. Dated to the BLE drop, // not to now: this runs off the 30 second timeout, which does not tick // while the OS has the process frozen. final droppedAt = _reconnectStartedAt ?? DateTime.now(); - if (_autoPingWasEnabled) { + if (alert && _autoPingWasEnabled) { _playDisconnectAlert(droppedAt); } @@ -6432,6 +8151,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _reconnectAttempt = 0; _reconnectStartedAt = null; _autoPingWasEnabled = false; + _reconnectFlapGuard.reset(); // Reset antenna and power settings so user must choose again on next connect _antennaRestoredFromDevice = false; @@ -6447,6 +8167,18 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Do full disconnect cleanup (releases API session, etc.) _fullDisconnectCleanup( releaseExtras: releaseExtras, flushQueue: flushQueue); + + // After the cleanup's synchronous start has marked the step disconnected, + // so the drop this causes on a half-open link reads as already handled. + // The cleanup leaves a BLE link up (it only disposes other transports), + // and the stale connect would otherwise finish onto it or keep it open. + if (inFlight != null && + _rememberedDevice?.transportType == TransportType.ble) { + debugLog('[CONN] Cancelling the in-flight reconnect connect'); + unawaited(_bluetoothService.cancelConnect().catchError((Object e) { + debugWarn('[CONN] Cancelling the in-flight reconnect failed: $e'); + })); + } notifyListeners(); } @@ -6466,236 +8198,308 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _abandonAutoReconnect(releaseExtras: info.extras, flushQueue: false); } - /// Disconnect from current device + /// Disconnect from current device. + /// + /// [flushQueue] uploads what is still queued before the session is + /// released: the user's own Disconnect and Close App set it. Teardowns the + /// server or a block forced (session error, maintenance, airborne) leave it + /// off, so their queue is dropped as before. Future disconnect({ bool closeApp = true, Map? releaseExtras, + bool flushQueue = false, }) async { - _finishLiveActivitySession(); - _invalidateLiveSessionRecovery(); - // Mark as user-requested so BLE disconnect listener doesn't trigger auto-reconnect - _userRequestedDisconnect = true; - - // Immediate UI feedback - _connectionStep = ConnectionStep.disconnecting; - notifyListeners(); - - // Release the sign gate before any teardown write (advert-name restore, - // path-hash restore, flood scope, channel deletion) is parked behind it. - // Ahead of the recovery wait below, not after it: the wait can take - // seconds, and a live sign holding the gate for all of them is exactly - // what aborting first is meant to prevent. - _meshCoreConnection?.abortPendingSign(); - _meshCoreConnection?.abortPendingAdmin(); - // awaitSessionRecoveryBounded swallows its own timeout but rethrows - // anything else, and a recovery that throws must never abandon the - // teardown with the radio still up: the user asked to disconnect. try { - await _waitForLiveSessionRecovery(); - } catch (e) { - debugWarn('[SESSION] recovery wait failed, continuing disconnect: $e'); - } - - await closeRepeaterAdminSession(); - - // Cancel idle disconnect timer - _cancelIdleDisconnectTimer(); + _finishLiveActivitySession(); + _invalidateLiveSessionRecovery(); + // Mark as user-requested so BLE disconnect listener doesn't trigger auto-reconnect + _userRequestedDisconnect = true; - // Cancel any active auto-reconnect - _reconnectTimer?.cancel(); - _reconnectTimer = null; - _reconnectTimeoutTimer?.cancel(); - _reconnectTimeoutTimer = null; - _cancelPendingAutoPingRestore(); - _isAutoReconnecting = false; - _reconnectAttempt = 0; - _reconnectStartedAt = null; - _autoPingWasEnabled = false; + // Immediate UI feedback + _connectionStep = ConnectionStep.disconnecting; + notifyListeners(); - // Cancel any active zone grace period - _cancelZoneGraceTimers(); - _isInZoneGracePeriod = false; - _zoneGraceSecondsRemaining = 0; - _autoPingWasEnabledBeforeGrace = false; + // Release the sign gate before any teardown write (advert-name restore, + // path-hash restore, flood scope, channel deletion) is parked behind it. + // Ahead of the recovery wait below, not after it: the wait can take + // seconds, and a live sign holding the gate for all of them is exactly + // what aborting first is meant to prevent. + _meshCoreConnection?.abortPendingSign(); + _meshCoreConnection?.abortPendingAdmin(); + _scopeLifecycle.onEvent(ScopeStopEvent.userDisconnect); + // awaitSessionRecoveryBounded swallows its own timeout but rethrows + // anything else, and a recovery that throws must never abandon the + // teardown with the radio still up: the user asked to disconnect. + try { + await _waitForLiveSessionRecovery(); + } catch (e) { + debugWarn('[SESSION] recovery wait failed, continuing disconnect: $e'); + } - // Disable heartbeat immediately on disconnect - _apiService.disableHeartbeat(); + await closeRepeaterAdminSession(); - // Stop zone refresh timer - _stopZoneRefreshTimer(); + // Cancel idle disconnect timer + _cancelIdleDisconnectTimer(); - // Stop auto-ping if running (before releasing session) - if (_autoPingEnabled) { - await _pingService?.forceDisableAutoPing(); - _autoPingEnabled = false; - _resetIdleAutoStop(); - } + // Cancel any active auto-reconnect + _reconnectTimer?.cancel(); + _reconnectTimer = null; + _reconnectTimeoutTimer?.cancel(); + _reconnectTimeoutTimer = null; + _cancelPendingAutoPingRestore(); + _isAutoReconnecting = false; + // An attempt still in flight may close what it connects, but not a + // connection the user starts after this (that bumps the generation). + _reconnectConnectInFlight?.abandonedAtGeneration ??= _connectGeneration; + _reconnectAttempt = 0; + _reconnectStartedAt = null; + _autoPingWasEnabled = false; + _reconnectFlapGuard.reset(); + + // Cancel any active zone grace period + _cancelZoneGraceTimers(); + _isInZoneGracePeriod = false; + _zoneGraceSecondsRemaining = 0; + _autoPingWasEnabledBeforeGrace = false; - // End noise floor session on disconnect - await _endNoiseFloorSession(); + // Disable heartbeat immediately on disconnect + _apiService.disableHeartbeat(); - // Stop background service - await BackgroundServiceManager.stopService(); + // Stop zone refresh timer + _stopZoneRefreshTimer(); - // Stop all countdown timers - _cooldownTimer.stop(); - _autoPingTimer.stop(); - _rxWindowTimer.stop(); + // Stop auto-ping if running (before releasing session) + if (_autoPingEnabled) { + await _pingService?.forceDisableAutoPing(); + _autoPingEnabled = false; + _resetIdleAutoStop(); + } - // Stop RX wardriving if active (flushes batches to queue) - _rxLogger?.stopWardriving(trigger: 'disconnect'); + // End noise floor session on disconnect + await _endNoiseFloorSession(); - // Save offline pings before clearing queue (no-op if not in offline mode or no pings) - await _saveOfflineSession(); + // Stop iOS's per-mode service. Android's session service stops once the + // session is over (below), after the upload and the session release, so + // the process is not frozen halfway through them. + if (!BackgroundServiceManager.followsConnection) { + await BackgroundServiceManager.stopService(); + } - // ALWAYS START FRESH - clear any queued data on disconnect - // Pings without a valid session cannot be uploaded later - await _apiQueueService.clearOnDisconnect(); + // Stop all countdown timers + _cooldownTimer.stop(); + _autoPingTimer.stop(); + _rxWindowTimer.stop(); - // Release API session (best effort - always cleanup locally) - if (_devicePublicKey != null && _apiService.hasSession) { - debugLog('[APP] Releasing API session'); + // Stop RX wardriving if active (flushes batches to queue). Awaited so the + // batches are queued before the upload below; a failed flush must not + // abandon the teardown. try { - await _apiService.requestAuth( - reason: 'disconnect', - publicKey: _devicePublicKey!, - extras: releaseExtras, - ); - debugLog('[APP] API session released successfully'); + await _rxLogger?.stopWardriving(trigger: 'disconnect'); } catch (e) { - debugError('[APP] Failed to release API session: $e'); - // Continue with disconnect anyway + debugError('[RX LOG] Final RX flush on disconnect failed: $e'); } - } - // Restore original device name if anonymous mode renamed it (BLE must still be connected) - if (_isAnonymousRenamed && _originalDeviceName != null) { - try { - await _meshCoreConnection?.setAdvertName(_originalDeviceName!); - debugLog( - '[CONN] Anonymous mode: restored name to "$_originalDeviceName"'); - if (_devicePublicKey != null) { - _clearPersistedRealName(_devicePublicKey!); + // Save offline pings before clearing queue (no-op if not in offline mode or no pings) + await _saveOfflineSession(); + + // Send what is still queued while the session is valid. The last TX + // waits 5 s for its upload and an RX batch up to 15 s, so a Disconnect + // tap inside that window used to drop them. Bounded so the tap stays + // quick on a bad network. + if (flushQueue && _apiService.hasSession && !_preferences.offlineMode) { + debugLog('[APP] Uploading queued pings before session release'); + final uploaded = await uploadQueueBounded(() async { + await _apiQueueService.waitForUploadToFinish( + limit: disconnectQueueUploadTimeout); + // A batch carries at most 50 items, and a queue that grew out of + // coverage needs several. Stop once a round leaves nothing or moves + // nothing (items still waiting out a retry). + var left = -1; + for (var round = 0; round < 5; round++) { + await _apiQueueService.forceUploadWithHoldWait(); + final now = _apiQueueService.queueSize; + if (now == 0 || now == left) break; + left = now; + } + }); + if (!uploaded) { + debugWarn('[APP] Queued pings not all uploaded before release'); } - } catch (e) { - debugError('[CONN] Anonymous mode: failed to restore name: $e'); - logError( - 'Anonymous Mode: Failed to restore device name. Device may still show as "Anonymous".', - severity: ErrorSeverity.warning, - autoSwitch: false); } - _isAnonymousRenamed = false; - _originalDeviceName = null; - } - // Restore original path hash mode before disconnect (while BLE still connected) - await _restorePathHashMode(); + // ALWAYS START FRESH - clear any queued data on disconnect + // Pings without a valid session cannot be uploaded later + await _apiQueueService.clearOnDisconnect(); - // Clear flood scope before disconnect (safety — BLE disconnect resets radio state anyway) - try { - await _meshCoreConnection?.clearFloodScope(); - } catch (e) { - debugLog('[CONN] Failed to clear flood scope: $e'); - } + // Release API session (best effort - always cleanup locally) + if (_devicePublicKey != null && _apiService.hasSession) { + debugLog('[APP] Releasing API session'); + try { + await _apiService.requestAuth( + reason: 'disconnect', + publicKey: _devicePublicKey!, + extras: releaseExtras, + ); + debugLog('[APP] API session released successfully'); + } catch (e) { + debugError('[APP] Failed to release API session: $e'); + // Continue with disconnect anyway + } + } - // Delete wardriving channel FIRST, while BLE connection is still active - // This prevents "GATT Server is disconnected" errors - if (_preferences.deleteChannelOnDisconnect) { - await _meshCoreConnection?.deleteWardrivingChannelEarly(); - } else { - debugLog('[CHANNEL] Skipping channel deletion (user preference)'); - } + // Restore original device name if anonymous mode renamed it (BLE must still be connected) + if (_isAnonymousRenamed && _originalDeviceName != null) { + try { + await _meshCoreConnection?.setAdvertName(_originalDeviceName!); + debugLog( + '[CONN] Anonymous mode: restored name to "$_originalDeviceName"'); + if (_devicePublicKey != null) { + _clearPersistedRealName(_devicePublicKey!); + } + } catch (e) { + debugError('[CONN] Anonymous mode: failed to restore name: $e'); + logError( + 'Anonymous Mode: Failed to restore device name. Device may still show as "Anonymous".', + severity: ErrorSeverity.warning, + autoSwitch: false); + } + _isAnonymousRenamed = false; + _originalDeviceName = null; + } - // Cleanup unified RX handler and TX tracker - _logRxDataSubscription?.cancel(); - _logRxDataSubscription = null; - _unifiedRxHandler?.dispose(); - _unifiedRxHandler = null; - _txTracker = null; // TxTracker is disposed by UnifiedRxHandler - _rxLogger = null; // RxLogger is disposed by UnifiedRxHandler + // Restore original path hash mode before disconnect (while BLE still connected) + await _restorePathHashMode(); - await _meshCoreConnection?.disconnect(); + // Clear flood scope before disconnect (safety — BLE disconnect resets radio state anyway) + try { + await _meshCoreConnection?.clearFloodScope(); + } catch (e) { + debugLog('[CONN] Failed to clear flood scope: $e'); + } - // Cancel stream subscriptions - await _noiseFloorSubscription?.cancel(); - _noiseFloorSubscription = null; - await _batterySubscription?.cancel(); - _batterySubscription = null; + // Delete wardriving channel FIRST, while BLE connection is still active + // This prevents "GATT Server is disconnected" errors + if (_preferences.deleteChannelOnDisconnect) { + await _meshCoreConnection?.deleteWardrivingChannelEarly(); + } else { + debugLog('[CHANNEL] Skipping channel deletion (user preference)'); + } - // Clean up non-BLE transport (TCP/USB instances are owned by us, not shared) - _transportConnectionSubscription?.cancel(); - _transportConnectionSubscription = null; - if (_activeTransport != null && _activeTransport != _bluetoothService) { - _activeTransport!.dispose(); - } - _activeTransport = null; + // Cleanup unified RX handler and TX tracker + _logRxDataSubscription?.cancel(); + _logRxDataSubscription = null; + _unifiedRxHandler?.dispose(); + _unifiedRxHandler = null; + _txTracker = null; // TxTracker is disposed by UnifiedRxHandler + _rxLogger = null; // RxLogger is disposed by UnifiedRxHandler - // Restore transport tab selection so connection screen shows the right tab - if (_rememberedDevice != null) { - _selectedTransport = _rememberedDevice!.transportType; - } + await _meshCoreConnection?.disconnect(); - _meshCoreConnection?.dispose(); - _meshCoreConnection = null; - _pingService?.dispose(); - _pingService = null; + // Cancel stream subscriptions + await _noiseFloorSubscription?.cancel(); + _noiseFloorSubscription = null; + await _batterySubscription?.cancel(); + _batterySubscription = null; - _connectionStep = ConnectionStep.disconnected; - _deviceModel = null; - _manufacturerString = null; - _firmwareVersionString = null; - _devicePublicKey = null; - _offlineContactUri = null; - _displayDeviceName = null; - _antennaRestoredFromDevice = false; - _powerRestoredFromDevice = false; - _preferences = _preferences.copyWith( - externalAntenna: false, externalAntennaSet: false); - _savePreferences(); - _currentNoiseFloor = null; - _currentBatteryPercent = null; - _authType = null; - _originalPathHashMode = null; - _userChangedPathMode = false; - _hopBytes = 1; - _traceHopBytes = 1; - - // Clear regional channels (keeps only Public) and scope - ChannelService.clearRegionalChannels(); - _regionalChannels = []; - _scope = null; - - // Clear user-original preference tracking - _userOriginalAutoPingInterval = null; - _userOriginalHybridMode = null; - _userOriginalDiscDrop = null; - _userOriginalFloodTraffic = null; - _syncRecentCoverage(sessionEnded: true); + // Clean up non-BLE transport (TCP/USB instances are owned by us, not shared) + _transportConnectionSubscription?.cancel(); + _transportConnectionSubscription = null; + if (_activeTransport != null && _activeTransport != _bluetoothService) { + _activeTransport!.dispose(); + } + _activeTransport = null; - // Clear zone transfer state - _sessionZoneCode = null; - _isZoneTransferInProgress = false; - _zoneTransferFrom = null; - _zoneTransferTo = null; + // Restore transport tab selection so connection screen shows the right tab + if (_rememberedDevice != null) { + _selectedTransport = _rememberedDevice!.transportType; + } - // Clear discovered devices so user must scan fresh - _discoveredDevices = []; + _meshCoreConnection?.dispose(); + _meshCoreConnection = null; + _pingService?.dispose(); + _pingService = null; + + _connectionStep = ConnectionStep.disconnected; + _deviceModel = null; + _manufacturerString = null; + _firmwareVersionString = null; + _devicePublicKey = null; + _offlineContactUri = null; + _displayDeviceName = null; + _antennaRestoredFromDevice = false; + _powerRestoredFromDevice = false; + _preferences = _preferences.copyWith( + externalAntenna: false, externalAntennaSet: false); + _savePreferences(); + _currentNoiseFloor = null; + _currentBatteryPercent = null; + _authType = null; + _originalPathHashMode = null; + _userChangedPathMode = false; + _hopBytes = 1; + _traceHopBytes = 1; - // Reset user-requested flag - _userRequestedDisconnect = false; + // Clear regional channels (keeps only Public) and scope + ChannelService.clearRegionalChannels(); + _regionalChannels = []; + _scope = null; - notifyListeners(); + // Clear user-original preference tracking + _userOriginalAutoPingInterval = null; + _userOriginalHybridMode = null; + _userOriginalDiscDrop = null; + _userOriginalFloodTraffic = null; + _syncRecentCoverage(sessionEnded: true); - // Auto-exit app if preference is enabled (Android only). The airborne - // block passes closeApp: false so its explanation stays on screen. - if (closeApp && - _preferences.closeAppAfterDisconnect && - Platform.isAndroid) { - debugLog('[APP] Auto-closing app after disconnect (preference enabled)'); - // Small delay to ensure cleanup completes - Future.delayed(const Duration(milliseconds: 500), () { - SystemNavigator.pop(); - }); + // Clear zone transfer state + _sessionZoneCode = null; + _sessionGroupCode = null; + _isZoneTransferInProgress = false; + _zoneTransferFrom = null; + _zoneTransferTo = null; + + // Clear discovered devices so user must scan fresh + _discoveredDevices = []; + + // Reset user-requested flag + _userRequestedDisconnect = false; + + notifyListeners(); + + // Auto-exit app if preference is enabled (Android only). The airborne + // block passes closeApp: false so its explanation stays on screen. + if (closeApp && + _preferences.closeAppAfterDisconnect && + Platform.isAndroid) { + debugLog('[APP] Auto-closing app after disconnect (preference enabled)'); + // Small delay to ensure cleanup completes. Same stop as exitApp(), for + // a session service still running with no radio session. + Future.delayed(const Duration(milliseconds: 500), () async { + await BackgroundServiceManager.stopLiveService( + 'close after disconnect'); + SystemNavigator.pop(); + }); + } + } finally { + // Android's session service stops once the session is over, after the + // upload and the session release above. In a finally, so a throw + // part-way cannot leave it running. That throw leaves the step at + // disconnecting, which still reads as a live session, so the guard only + // asks whether another session (a reconnect, a connect re-run) has + // taken over. Not awaited: the stop is sent at once. + if (BackgroundServiceManager.followsConnection && + shouldStopServiceAtCleanupEnd( + followsConnection: BackgroundServiceManager.followsConnection, + sessionActive: radioSessionActive( + step: _connectionStep == ConnectionStep.disconnecting + ? ConnectionStep.disconnected + : _connectionStep, + autoReconnecting: _isAutoReconnecting, + connectRerunPending: _connectRerunPending, + ), + )) { + unawaited(BackgroundServiceManager.stopService()); + } } } @@ -6796,7 +8600,24 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Returns true if session is valid, false if expired (triggers disconnect) Future _recoverExpiredLiveSession() { final inFlight = _liveSessionRecoveryInFlight; - if (inFlight != null) return inFlight; + switch (resolveSessionRecoveryJoin( + groupHandoffOwnsSlot: _groupHandoffOwnsRecoverySlot, + recoveryInFlight: inFlight != null, + )) { + case SessionRecoveryJoin.supersededByHandoff: + // The handoff's own drain is one of the lanes that can ask here, and + // the in-flight future is the handoff: joining it would deadlock + // both. Every lane reads superseded as "ended quietly" (the upload + // comes back held with no retry spent), and the handoff mints the + // replacement session itself. + debugLog('[SESSION] session_expired during a group handoff: the ' + 'handoff mints the replacement'); + return Future.value(SessionRecoveryResult.superseded); + case SessionRecoveryJoin.joinInFlight: + return inFlight!; + case SessionRecoveryJoin.startNew: + break; + } final generation = _sessionRecoveryGeneration; late final Future recovery; @@ -6863,104 +8684,138 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return SessionRecoveryResult.superseded; } - final deviceName = _isAnonymousRenamed - ? 'Anonymous' - : (connection.selfInfo?.name ?? - connectedDeviceName?.replaceFirst('MeshCore-', '')); - if (deviceName == null || deviceName.isEmpty) { - debugWarn( - '[SESSION] Refusing expired-session recovery without a device name'); - return SessionRecoveryResult.failed; - } + final result = await _mintAndApplyReplacementSession( + connection: connection, + publicKey: publicKey, + // The zone the session belongs to, not the zone the phone is in: a + // recovery that ran while a handoff was deferred behind it would + // otherwise mint in the new member with _sessionZoneCode still on the + // old one, and the next tick's handoff would release that fresh + // session and mint again. + iataCode: _sessionZoneCode ?? zoneCode ?? _preferences.iataCode, + owns: () => _ownsSessionRecovery(generation, connection, publicKey), + tag: '[SESSION]', + what: 'expired-session recovery', + ); + if (result == SessionRecoveryResult.recovered) notifyListeners(); + return result; + } finally { + pingService.setSessionRecoveryInProgress(false); + } + } - final position = _currentPosition!; - final model = connection.deviceModel?.manufacturer ?? - connection.deviceInfo?.manufacturer ?? - 'Unknown'; - debugLog( - '[SESSION] Re-authenticating live companion after session expiry'); - Map? result; - try { - result = await _apiService.requestAuth( - reason: 'connect', - publicKey: publicKey, - who: deviceName, - appVersion: _appVersion, - power: _preferences.powerLevel, - iataCode: zoneCode ?? _preferences.iataCode, - model: model, - radioFreq: connection.selfInfo?.radioConfigApi, - lat: position.latitude, - lon: position.longitude, - accuracyMeters: position.accuracy, - shouldStoreSession: () => - _ownsSessionRecovery(generation, connection, publicKey), - ); - } catch (e) { - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - debugLog('[SESSION] Stale re-authentication failure ignored'); - return SessionRecoveryResult.superseded; - } - debugError('[SESSION] Live re-authentication failed: $e'); - return SessionRecoveryResult.failed; + /// Mints a replacement session for the live companion in [iataCode] and + /// applies its answer (channels, validator, flood scope, zone policies, + /// path hash mode): the back half shared by an expired-session recovery + /// and a group handoff. [owns] is re-read after every await; once it reads + /// false the caller's successor owns the cleanup, and any session minted + /// here is released without being awaited (that release is a second /auth + /// POST that can sit for 30 s, and the successor is blocked on this + /// settling). `failed` never leaves a minted session behind. [tag] and + /// [what] name the caller in the logs. [fix] is the position to send; when + /// null it is picked here. + Future _mintAndApplyReplacementSession({ + required MeshCoreConnection connection, + required String publicKey, + required String? iataCode, + required bool Function() owns, + required String tag, + required String what, + Position? fix, + }) async { + final deviceName = _isAnonymousRenamed + ? 'Anonymous' + : (connection.selfInfo?.name ?? + connectedDeviceName?.replaceFirst('MeshCore-', '')); + if (deviceName == null || deviceName.isEmpty) { + debugWarn('$tag Refusing $what without a device name'); + return SessionRecoveryResult.failed; + } + // The fix the connect /auth picks ([fix] when the caller picked it + // already): a coarse current fix sent as-is is refused gps_inaccurate, + // and a refused recovery ends the drive. + final position = fix ?? await _pickAuthFix(); + if (!owns()) return SessionRecoveryResult.superseded; + if (position == null) { + debugWarn('$tag Refusing $what without a position'); + return SessionRecoveryResult.failed; + } + + final model = connection.deviceModel?.manufacturer ?? + connection.deviceInfo?.manufacturer ?? + 'Unknown'; + debugLog('$tag Re-authenticating live companion for $what'); + Map? result; + try { + result = await _apiService.requestAuth( + reason: 'connect', + publicKey: publicKey, + who: deviceName, + appVersion: _appVersion, + power: _preferences.powerLevel, + iataCode: iataCode, + model: model, + radioFreq: connection.selfInfo?.radioConfigApi, + lat: position.latitude, + lon: position.longitude, + accuracyMeters: position.accuracy, + shouldStoreSession: owns, + ); + } catch (e) { + if (!owns()) { + debugLog('$tag Stale re-authentication failure ignored'); + return SessionRecoveryResult.superseded; } - final replacementSessionId = result?['session_id'] as String?; - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - // Superseded: a disconnect or a reconnect took over and is blocked on - // this recovery settling. The release is a second /auth POST that can - // sit for 30 s, and nothing here depends on its answer, so it is fired - // and left to log its own failure. + debugError('$tag Live re-authentication failed: $e'); + return SessionRecoveryResult.failed; + } + final replacementSessionId = result?['session_id'] as String?; + if (!owns()) { + unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); + return SessionRecoveryResult.superseded; + } + if (result == null || result['success'] != true) { + debugWarn('$tag Live re-authentication was not accepted: ' + '${result?['reason'] ?? 'no answer'}'); + return SessionRecoveryResult.failed; + } + if (replacementSessionId == null || + _apiService.sessionId != replacementSessionId) { + // Ownership held through the POST (checked just above), so a success + // answer with no session id, or one the store did not take, is a + // malformed answer rather than a lost race: a failure, with any id the + // server did mint released. The lost-ownership case stays superseded. + debugWarn('$tag Re-authentication answered success without a usable ' + 'session id'); + unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); + return SessionRecoveryResult.failed; + } + + try { + if (result['type'] is String) _authType = result['type'] as String; + _syncZoneCapacityFromAuth(result); + final applied = + await _applyRecoveredSessionConfiguration(connection, owns); + if (!owns()) { unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); return SessionRecoveryResult.superseded; } - if (result == null || result['success'] != true) { - debugWarn('[SESSION] Live re-authentication was not accepted'); + if (!applied) { + await _releaseRecoveredSession(publicKey, replacementSessionId); + if (!owns()) return SessionRecoveryResult.superseded; return SessionRecoveryResult.failed; } - if (replacementSessionId == null || - _apiService.sessionId != replacementSessionId) { - // The session was minted but not stored, which only happens when - // ownership went away during the POST. Same superseded case, same - // unawaited release. + } catch (e) { + if (!owns()) { unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); return SessionRecoveryResult.superseded; } - - try { - if (result['type'] is String) _authType = result['type'] as String; - _syncZoneCapacityFromAuth(result); - final applied = await _applyRecoveredSessionConfiguration( - connection, - () => _ownsSessionRecovery(generation, connection, publicKey), - ); - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); - return SessionRecoveryResult.superseded; - } - if (!applied) { - await _releaseRecoveredSession(publicKey, replacementSessionId); - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - return SessionRecoveryResult.superseded; - } - return SessionRecoveryResult.failed; - } - } catch (e) { - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - unawaited(_releaseRecoveredSession(publicKey, replacementSessionId)); - return SessionRecoveryResult.superseded; - } - debugError('[SESSION] Failed to apply replacement session: $e'); - await _releaseRecoveredSession(publicKey, replacementSessionId); - if (!_ownsSessionRecovery(generation, connection, publicKey)) { - return SessionRecoveryResult.superseded; - } - return SessionRecoveryResult.failed; - } - notifyListeners(); - return SessionRecoveryResult.recovered; - } finally { - pingService.setSessionRecoveryInProgress(false); + debugError('$tag Failed to apply replacement session: $e'); + await _releaseRecoveredSession(publicKey, replacementSessionId); + if (!owns()) return SessionRecoveryResult.superseded; + return SessionRecoveryResult.failed; } + return SessionRecoveryResult.recovered; } Future _releaseRecoveredSession( @@ -7065,8 +8920,322 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return true; } + /// Runs a hidden handoff through the same single slot a session-expiry + /// recovery uses, so disconnect, auto-reconnect, Offline Mode and dispose + /// already supersede it and wait for it (bounded), and a session_expired + /// arriving meanwhile joins it instead of starting a second swap. + Future _startGroupHandoff( + String newZoneCode, String newZoneName) async { + final generation = _sessionRecoveryGeneration; + // Set before the handoff starts (its first statements run synchronously) + // and cleared with the slot, so no session_expired can join it. + _groupHandoffOwnsRecoverySlot = true; + late final Future handoff; + handoff = _handOffWithinGroup(generation, newZoneCode).whenComplete(() { + _groupHandoffOwnsRecoverySlot = false; + if (identical(_liveSessionRecoveryInFlight, handoff)) { + _liveSessionRecoveryInFlight = null; + } + }); + _liveSessionRecoveryInFlight = handoff; + SessionRecoveryResult result; + try { + result = await handoff; + } catch (e) { + // Nothing awaits this method (the status handler fires it and moves + // on), so a throw here would be an unhandled error. The TX hold is + // released by the handoff's own finally; treat it as a failure. + debugError('[ZONE] Group handoff threw: $e'); + result = SessionRecoveryResult.failed; + } + if (_isDisposed) return; + if (result == SessionRecoveryResult.recovered) { + await _remapAutoModeAfterHandoff(newZoneCode); + return; + } + // A failed handoff has released the old session, and the app must not + // stay connected without one: re-mint in the zone the phone is in NOW + // (a later tick may have moved it to a third member, or back into the + // old one; the visible transfer just auths in its target), or, with no + // zone to re-join, end the session the way a failed visible transfer + // does. + final fallbackZone = zoneCode; + switch (groupHandoffFollowUp( + failed: result == SessionRecoveryResult.failed, + connected: isConnected, + offlineMode: _preferences.offlineMode, + inZoneGracePeriod: _isInZoneGracePeriod, + zoneCode: fallbackZone, + )) { + case GroupHandoffFollowUp.transfer: + final fallbackName = _currentZone?['name'] as String? ?? 'Unknown'; + debugWarn('[ZONE] Group handoff failed, falling back to a full ' + 'zone transfer to $fallbackZone'); + await _handleZoneTransfer(fallbackZone!, fallbackName); + case GroupHandoffFollowUp.disconnect: + debugError('[ZONE] Group handoff failed with no zone to re-join: ' + 'ending the session'); + logError('Zone transfer failed: no zone to re-join', + severity: ErrorSeverity.error); + await disconnect(); + case GroupHandoffFollowUp.none: + break; + } + } + + /// A hidden handoff that lands in a member with no TX capacity cannot + /// leave Active or Hybrid transmitting into refusals. This is the one case + /// a handoff changes what is on screen: the mode is switched the way the + /// visible transfer's restore resolves it (`_resolveAutoModeForZone`, + /// Passive when the member allows RX), with a line in the error log that + /// says why. Runs once the handoff has settled, so the TX hold is released + /// and the recovery slot is free for the session check a start makes. + Future _remapAutoModeAfterHandoff(String newZoneCode) async { + if (_apiService.txAllowed || !_autoPingEnabled || _pingService == null) { + return; + } + final current = _autoMode; + if (current != AutoMode.active && current != AutoMode.hybrid) return; + // A stop the user already asked for outranks the remap (the external + // lanes' stillStopping rule): the switch below goes through the mode + // start, which force-disables the running mode and drops a parked + // disable, so the Stop would be lost and a fresh discovery would go out. + // Nothing is awaited between here and the switch, so one read suffices. + if (isPendingDisable) { + debugLog('[ZONE] $newZoneCode is at TX capacity, but a stop is ' + 'pending: leaving the mode to it'); + return; + } + final resolved = _resolveAutoModeForZone(current); + if (resolved == current) { + debugWarn('[ZONE] $newZoneCode allows neither TX nor RX; ' + '${current.name} mode left running'); + return; + } + final resolvedName = + '${resolved.name[0].toUpperCase()}${resolved.name.substring(1)}'; + debugLog('[ZONE] $newZoneCode is at TX capacity: switching ' + '${current.name} mode to ${resolved.name}'); + logError( + 'TX stopped: $newZoneCode, the region you drove into, is at Active ' + 'Wardrive capacity. Switched to $resolvedName mode.', + severity: ErrorSeverity.warning, + autoSwitch: false); + // The switch goes through the ordinary mode start, which the shared + // cooldown would refuse; the visible transfer's restore clears it the + // same way. + _cooldownTimer.stop(); + _pingService!.clearCooldown(); + final switched = await toggleAutoPing(resolved); + if (!switched) { + debugWarn('[ZONE] Mode switch to ${resolved.name} was refused'); + } + } + + /// Moves a live session to another member of its own region group without + /// the user seeing it: hold new TX, let an on-air TX queue its old wire + /// tag, upload everything queued under the old session, release it, open + /// a session in [newZoneCode], and apply that answer the way a session + /// recovery does. Auto-ping keeps its schedule; a send that comes due + /// meanwhile bows out and re-arms (the recovery hold). + /// + /// `failed` means the caller should fall back to the visible transfer. + /// `superseded` means something else (disconnect, reconnect, Offline Mode, + /// zone grace, dispose) took over and owns the cleanup. + Future _handOffWithinGroup( + int generation, String newZoneCode) async { + final connection = _meshCoreConnection; + final publicKey = _devicePublicKey; + final pingService = _pingService; + final oldZone = _sessionZoneCode; + if (connection == null || + publicKey == null || + pingService == null || + _currentPosition == null || + _isInZoneGracePeriod || + !_ownsSessionRecovery(generation, connection, publicKey)) { + debugWarn('[ZONE] Refusing group handoff outside a live session'); + return SessionRecoveryResult.superseded; + } + // Zone grace keeps the session, clears the queue and disables the + // heartbeat without bumping the recovery generation, and its re-entry + // runs the visible transfer, so a handoff still running then belongs + // to it. + bool owns() => + _ownsSessionRecovery(generation, connection, publicKey) && + !_isInZoneGracePeriod; + // Every exit past the keepPolicy release that does not end with a stored + // session forgets the kept zone policy, as a plain release would have: + // every superseding owner gates its own release on hasSession, so nothing + // else would. A successor that already minted its own session keeps it, + // and one still minting overwrites every field. + SessionRecoveryResult withoutSession(SessionRecoveryResult result) { + if (!_apiService.hasSession) _apiService.clearSession(); + return result; + } + + debugLog('[ZONE] Group handoff: $oldZone -> $newZoneCode ' + '(group $_sessionGroupCode)'); + // A scope runner holding the radio lease stops before the session + // changes, as it does for the visible transfer. + _scopeLifecycle.onEvent(ScopeStopEvent.zoneTransfer); + pingService.setSessionRecoveryInProgress(true); + // The queue's own timers must not start a batch under the session this + // is about to release: a batch that lands after the server closed it + // answers bad_session, which ends the connection. Explicit drains below + // still run. Resumed in the finally on every path. + _apiQueueService.pauseScheduledUploads(); + try { + // A TX already sent carries the old wire tag until its listening + // window queues it. Nothing below may run before it reaches the queue. + await pingService.waitForTxWindow(); + if (!owns()) return SessionRecoveryResult.superseded; + + // Everything queued so far belongs to the old session: TX items carry + // its wire tags, which the server only accepts under that session. + // Each round first waits for an upload already on the wire, since the + // queue silently skips a second one. If the old session has lapsed the + // drain comes back held (its session_expired is answered superseded, + // see _recoverExpiredLiveSession), nothing shrinks, and the loop moves + // on to release and mint, which is right for a lapsed session. + await _rxLogger?.flushAllBatches(trigger: 'zone_handoff'); + if (!owns()) return SessionRecoveryResult.superseded; + for (var round = 0; + round < 5 && _apiQueueService.queueSize > 0; + round++) { + await _apiQueueService.waitForUploadToFinish(); + if (!owns()) return SessionRecoveryResult.superseded; + final before = _apiQueueService.queueSize; + try { + await _apiQueueService.forceUploadWithHoldWait(); + } catch (e) { + debugError('[ZONE] Group handoff drain failed: $e'); + break; + } + if (!owns()) return SessionRecoveryResult.superseded; + if (_apiQueueService.queueSize >= before) break; + } + debugLog('[ZONE] Group handoff drained, ' + '${_apiQueueService.queueSize} item(s) left'); + // Nothing of ours is on the wire past this point: the timers are held + // and the drain was awaited. A batch another lane put out is waited + // for (bounded) so it is answered before the session closes. + if (!await _apiQueueService.waitForUploadToFinish()) { + debugWarn('[ZONE] Group handoff releasing with an upload still on ' + 'the wire'); + } + if (!owns()) return SessionRecoveryResult.superseded; + + // Picked before the release: a coarse fix can wait a few seconds for a + // better one, and that wait must not sit in the gap with no session. + final authFix = await _pickAuthFix(); + if (!owns()) return SessionRecoveryResult.superseded; + + if (_apiService.hasSession) { + // keepPolicy: the UI reads txAllowed, the channels and the enforce + // flags on every notify, and a plain release zeroes them for the two + // round trips until the mint stores its answer (the Active button + // vanished and the status bar read "at capacity"). The mint + // overwrites every kept field; a handoff that ends without a session + // clears them in full below. requestAuth never throws (a failed POST + // answers null), so the answer is checked rather than caught. + final released = await _apiService.requestAuth( + reason: 'disconnect', + publicKey: publicKey, + extras: const {'disconnect_cause': 'zone_transfer'}, + keepPolicy: true, + ); + if (released == null || released['success'] != true) { + debugWarn('[ZONE] Group handoff release not confirmed: ' + '${released?['reason'] ?? 'no answer'}'); + } + if (!owns()) return withoutSession(SessionRecoveryResult.superseded); + } + // The release cleared the held session id, so the connect below has + // no previous id to compare and never fires onSessionIdChanged. Run + // the session-replaced work here instead: the tagged TX the drain left + // behind only re-derive under the session just released, and the + // deferred squares reported under it are owed again under the new one. + await _onSessionReplaced(); + if (!owns()) return withoutSession(SessionRecoveryResult.superseded); + + final minted = await _mintAndApplyReplacementSession( + connection: connection, + publicKey: publicKey, + iataCode: newZoneCode, + owns: owns, + tag: '[ZONE]', + what: 'group handoff', + fix: authFix, + ); + if (minted != SessionRecoveryResult.recovered) return withoutSession(minted); + + // Only now does the session belong to the new member: a failure above + // leaves the old code in place, which is what lets the caller fall + // back to the visible transfer. + _sessionZoneCode = newZoneCode; + _sessionGroupCode = zoneGroupCode; + // The release cancelled the keepalive timers with the old session and + // a connect auth never schedules one itself, so re-arm the lane the way + // the visible transfer does; it schedules from the new expires_at. + _apiService.enableHeartbeat( + gpsProvider: () { + final pos = _gpsService.lastPosition; + if (pos == null) return null; + return (lat: pos.latitude, lon: pos.longitude); + }, + ); + // The scope stop above ended the periodic repeater refresh while the + // mode kept running. The new auth usually re-arms it through the gate + // change; this covers the case where the gate never flipped. + if (_isPassiveOrHybridModeRunning && + !_scopeLifecycle.repeaterRefreshTimerRunning) { + _startScopeRepeaterRefreshForRunningMode(); + } + debugLog('[ZONE] Group handoff complete: $oldZone -> $newZoneCode'); + notifyListeners(); + return SessionRecoveryResult.recovered; + } finally { + _apiQueueService.resumeScheduledUploads(); + pingService.setSessionRecoveryInProgress(false); + } + } + + /// Everything a new session id makes stale. One definition, two callers: + /// `onSessionIdChanged` (a connect auth that replaced a held id) and the + /// group handoff, whose keepPolicy release nulls the id first so that hook + /// never fires for it. A wire tag only re-derives under the session that + /// minted it, so the tagged TX still queued are dropped rather than + /// uploaded as claims the server would skip while reporting success; and + /// the server credits one deferred square per session id, so a square + /// reported under the old session is owed again under the new one. + Future _onSessionReplaced() async { + await _apiQueueService.dropStaleTaggedItems(); + _recentCoverage.clearDeferred(); + } + Future _checkSessionBeforeAction() async { _lastSessionCheckFailureReason = null; + // A group handoff has released the old session and not yet stored the + // new one for two round trips, and checkSessionValid answers no_session + // in that gap: a tap, a Start or a Siri/watch Start landing there was + // refused with "session has ended" for a session that was only moving. + // Wait for the handoff (bounded, as every other waiter on that slot is) + // and check the session it minted. The handoff never reaches this + // method while it holds the slot (its remap runs after the slot is + // cleared), so the wait cannot be on itself. + if (sessionCheckWaitsForHandoff( + groupHandoffOwnsSlot: _groupHandoffOwnsRecoverySlot, + recoveryInFlight: _liveSessionRecoveryInFlight != null, + )) { + debugLog('[SESSION] Session check waiting for the group handoff'); + try { + await _waitForLiveSessionRecovery(); + } catch (e) { + debugWarn('[SESSION] Handoff failed while the session check waited ' + 'for it, checking anyway: $e'); + } + } final pos = _gpsService.lastPosition; final result = await _apiService.checkSessionValid( lat: pos?.latitude, @@ -7185,6 +9354,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return const RepeaterAdminResult.failed(RepeaterAdminFailureKind.invalid, message: 'Something went wrong talking to the radio.'); } + final lapsed = await _repeaterAdminSessionCheck('claim'); + if (lapsed != null) return lapsed; final result = await _repeaterAdminApi.claim(session.target.hexId, proof); if (result.ok) { debugLog('[RADMIN] Claimed ${session.target.shortId}: ' @@ -7202,6 +9373,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return const RepeaterAdminResult.failed( RepeaterAdminFailureKind.noSession); } + final lapsed = await _repeaterAdminSessionCheck('unclaim'); + if (lapsed != null) return lapsed; final result = await RepeaterClaimUnclaim( request: _repeaterAdminApi.unclaim, companionPublicKey: () => _devicePublicKey, @@ -7239,6 +9412,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return const RepeaterAdminResult.failed(RepeaterAdminFailureKind.invalid, message: 'Something went wrong talking to the radio.'); } + final lapsed = await _repeaterAdminSessionCheck('neighbours'); + if (lapsed != null) return lapsed; final result = await _repeaterAdminApi.neighbours(session.target.hexId, table); if (result.ok) { @@ -7248,6 +9423,26 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return result; } + /// The /repeater door reports an expired session but never recovers it, + /// and an idle app's keepalive stops once the session lapses. So run the + /// same session check a Start or manual ping runs first + /// ([ApiService.checkSessionValid]), which recovers a lapsed session and + /// restarts its keepalive. Callers have already refused Offline Mode. + /// Returns null when the request may go ahead. + Future _repeaterAdminSessionCheck(String action) async { + final pos = _gpsService.lastPosition; + final check = await _apiService.checkSessionValid( + lat: pos?.latitude, + lon: pos?.longitude, + ); + if (check.isValid) return null; + debugWarn('[RADMIN] Session check failed before $action ' + '(${check.reason}), not sending'); + return RepeaterAdminResult.failed(check.reason == 'no_response' + ? RepeaterAdminFailureKind.network + : RepeaterAdminFailureKind.sessionExpired); + } + Future readRepeaterPassword(String hex) => _repeaterPasswordStore.readRepeaterPassword(hex); Future rememberRepeaterPassword(String hex, String password) => @@ -7454,6 +9649,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Before the first await: GPS ticks overlap and disconnect() is not // re-entrant. Cleared in finally because disconnect() can throw mid-way. _airborneEndInFlight = true; + _scopeLifecycle.onEvent(ScopeStopEvent.airborne); try { final info = _airborneReleaseInfo(); debugError('[GPS] Airborne detected (${info.detail}), ending session'); @@ -7497,6 +9693,79 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return true; } + /// Precise Location block at the front door. True when the connect must not + /// start. See `lib/services/precise_location_gate.dart`. + /// + /// Asks for precise location at most once per tap (iOS temporary full + /// accuracy, or the Android fine re-request through + /// [preciseLocationUpgradeRequester]) and only while the app is on screen. + /// A refusal raises [preciseLocationPromptDue] for the explanation dialog + /// and sets no connectionError, like the airborne block. Auto-reconnect + /// skips this: [_attemptReconnect] re-reads the accuracy itself, without a + /// prompt. Starts no GPS; an Android upgrade only restarts a stream that is + /// already running, so its fixes come in precise. + Future _refuseConnectIfImprecise(String entry) async { + if (_isAutoReconnecting) return false; + if (_preciseLocationCheckInFlight) { + debugLog('[CONN] Precise location check already in progress, ' + 'ignoring duplicate tap'); + return true; + } + _preciseLocationCheckInFlight = true; + _connectRefusedForPreciseLocation = false; + var upgradeRequested = false; + try { + final upgrade = preciseLocationUpgradeRequester; + final allowed = await _preciseLocationGate.allowsConnect( + platform: PreciseLocationGate.currentPlatform, + simulatorEnabled: _gpsService.isSimulatorEnabled, + canPrompt: WidgetsBinding.instance.lifecycleState == + AppLifecycleState.resumed, + requestFineLocation: upgrade == null + ? null + : () { + upgradeRequested = true; + return upgrade(); + }, + entry: entry, + ); + if (_isDisposed) return true; + if (!allowed) { + _connectRefusedForPreciseLocation = true; + _preciseLocationPromptDue = true; + notifyListeners(); + return true; + } + if (upgradeRequested && _gpsService.isWatching) { + debugLog('[GPS] Fine location granted, restarting the running ' + 'stream for precise fixes'); + await restartGpsAfterPermission(keepTracking: true); + } + if (_isConnecting) { + debugLog('[APP] Connection started during the precise location ' + 'check, ignoring this tap'); + return true; + } + return false; + } finally { + _preciseLocationCheckInFlight = false; + } + } + + /// Ends an auto-reconnect whose location accuracy dropped to approximate + /// while the radio was away. Same shape as the airborne abandon. + void _abandonAutoReconnectForImpreciseLocation() { + debugError('[GPS] Location accuracy is reduced, abandoning ' + 'auto-reconnect'); + if (!_autoPingWasEnabled) { + _playDisconnectAlert(_reconnectStartedAt ?? DateTime.now()); + } + logError('Session ended: Precise Location is off, so your position is ' + 'too rough to map coverage.'); + _preciseLocationPromptDue = true; + _abandonAutoReconnect(); + } + /// The finishing half of an auto-mode stop, with the radio still connected. /// /// Shared by the three paths that end a mode: the inline teardown in @@ -7524,12 +9793,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Stop RX wardriving (flushes batches). _rxLogger?.stopWardriving(trigger: rxTrigger); - await BackgroundServiceManager.stopService(); + // iOS's service runs per mode. Android's runs for the whole connection, + // and the next notify turns its notification back to Connected. + if (!BackgroundServiceManager.followsConnection) { + await BackgroundServiceManager.stopService(); + } // Stop the countdowns, or "Next ping in Xs" keeps running after the stop. _autoPingTimer.stop(); _rxWindowTimer.stop(); + // The mode is ending: the periodic scope-discovery repeater refresh + // (Passive or Hybrid only) has nothing left to run for. + _scopeLifecycle.stopRepeaterRefreshTimer(); + if (_preferences.offlineMode && !_modeSwitchOwnsOfflineSave) { await _saveOfflineSession(); } @@ -7671,12 +9948,19 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Stop TX echo tracking to prevent late timer callbacks _pingService!.stopEchoTracking(); _rxLogger?.stopWardriving(trigger: 'mode_switch'); - await BackgroundServiceManager.stopService(); + // iOS only: Android's session service stays up across the switch. + if (!BackgroundServiceManager.followsConnection) { + await BackgroundServiceManager.stopService(); + } // Stop countdown timers when switching modes _autoPingTimer.stop(); _rxWindowTimer.stop(); // Clear top-heard overlay on mode switch _clearOverlayState(); + // Stop the scope-discovery periodic repeater refresh (Passive or + // Hybrid may not be the mode ending here); restarted below if the + // new mode is Passive or Hybrid. + _scopeLifecycle.stopRepeaterRefreshTimer(); // Save offline session if offline mode is enabled if (_preferences.offlineMode) { await _saveOfflineSession(); @@ -7726,6 +10010,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _autoPingEnabled = true; _idleAutoStopReference = DateTime.now(); _startLiveActivitySession(startedAt: sessionStartedAt); + if (isPassive || isHybrid) { + _startScopeRepeaterRefreshForRunningMode(); + } // Start noise floor session for graph tracking. The label is the // enum's own name (active/passive/hybrid/targeted). @@ -7747,17 +10034,29 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[HEARTBEAT] Enabled for ${mode.name} Mode'); } - // Start background service for continuous operation + // Start iOS's per-mode service for continuous operation. Android's + // session service is already up for the connection (only + // _syncConnectionService starts it), so it only takes the mode's + // notification and wake lock. final n = androidNotificationContent( mode: mode, txCount: _pingStats.txCount, rxCount: _pingStats.rxCount, queueSize: _queueSize, ); - await BackgroundServiceManager.startService( - title: n.title, - body: n.body, - ); + if (BackgroundServiceManager.followsConnection) { + await BackgroundServiceManager.updateNotification( + title: n.title, + body: n.body, + keepAwake: _keepServiceAwake, + ); + } else { + await BackgroundServiceManager.startService( + title: n.title, + body: n.body, + keepAwake: _keepServiceAwake, + ); + } } finally { _startingDeferredHistory.clear(); // Clear starting state on every path (session/cooldown/blocked early @@ -7785,6 +10084,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _rxPings.clear(); _discLogEntries.clear(); _traceLogEntries.clear(); + _scopeLog.clear(); _deferredPingMarkers.clear(); _lastDeferredMarkerLat = null; _lastDeferredMarkerLon = null; @@ -7800,15 +10100,28 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _rxLogEntries.clear(); _discLogEntries.clear(); _traceLogEntries.clear(); + _scopeLog.clear(); _deferredPingMarkers.clear(); _lastDeferredMarkerLat = null; _lastDeferredMarkerLon = null; _siriObservationRevision++; _errorLogEntries.clear(); + _errorsSeen = _errorsLogged; _clearOverlayState(); _notifyMapNow(); } + /// Withdraw a discovery log entry whose request never went on the air + /// (the write failed after the entry was published). + void _removeDiscLogEntry(DiscLogEntry entry) { + final before = _discLogEntries.length; + _discLogEntries.removeWhere((e) => identical(e, entry)); + if (_discLogEntries.length == before) return; + _siriObservationRevision++; + debugLog('[APP] Discovery log entry withdrawn: request was not sent'); + _notifyMapNow(); + } + /// Add a discovery log entry (from Passive Mode) void _addDiscLogEntry(DiscLogEntry entry) { _discLogEntries.insert(0, entry); @@ -7836,6 +10149,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _notifyMapNow(); } + /// Add a scope request log entry (from a Passive/Hybrid Mode sweep). + /// Nothing here is on the map (Critical Rule 9), so this stays a plain + /// notify, never `_notifyMapNow`. + void _addScopeLogEntry(ScopeLogEntry entry) { + _scopeLog.add(entry); + debugLog('[SCOPES] Log entry added: outcome=${entry.outcome.name}'); + // The status bar's Scopes chip: one per repeater that answered. + if (entry.outcome == ScopeLogOutcome.answered || + entry.outcome == ScopeLogOutcome.withheldHourlyCap) { + _pingService?.recordScopeAnswer(); + } + notifyListeners(); + } + /// Log a user-facing error message /// Set [autoSwitch] to false to log without navigating to error log tab void logError(String message, @@ -7848,6 +10175,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (_errorLogEntries.length > _maxErrorEntries) { _errorLogEntries.removeAt(0); } + _errorsLogged++; + // Already looking at the Errors tab: it is seen as it arrives. + if (_errorLogOnScreen) _errorsSeen = _errorsLogged; if (autoSwitch) { _requestErrorLogSwitch = true; // Auto-switch to error log } @@ -7917,7 +10247,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _nearestZone = null; _lastZoneCheckPosition = null; _regionBorders = []; - _bordersLoadedForZone = null; + _borderLoader.forget(); debugLog('[GEOFENCE] Cleared zone data for offline mode'); } else { // Stop auto-save timer when leaving offline mode @@ -7937,6 +10267,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Switch from online to offline mode while connected Future<({bool success, String? error})> _switchToOfflineMode() async { debugLog('[APP] Hot-switching to offline mode while connected'); + // Before the first await: the gate still reads open until Offline Mode + // is set at the end, so no new scope runner may start in between. + _scopeLifecycle.beginModeSwitch(ScopeStopEvent.offlineSwitch); + try { + return await _switchToOfflineModeSteps(); + } finally { + _scopeLifecycle.endModeSwitch(); + } + } + + Future<({bool success, String? error})> _switchToOfflineModeSteps() async { _invalidateLiveSessionRecovery(); await _waitForLiveSessionRecovery(); _isSwitchingMode = true; @@ -7991,7 +10332,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _nearestZone = null; _lastZoneCheckPosition = null; _regionBorders = []; - _bordersLoadedForZone = null; + _borderLoader.forget(); debugLog('[GEOFENCE] Cleared zone data for offline mode'); // Smart Pinging has no server to ask in Offline Mode. @@ -8012,21 +10353,62 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Switch from offline to online mode while connected Future<({bool success, String? error})> _switchToOnlineMode() async { debugLog('[APP] Hot-switching to online mode while connected'); + // No scope runner starts while the switch runs; the new session's gate + // decides once it is over. + _scopeLifecycle.beginModeSwitch(ScopeStopEvent.onlineSwitch); + try { + return await _switchToOnlineModeSteps(); + } finally { + _scopeLifecycle.endModeSwitch(); + } + } + + /// Asks the server whether this spot is in a zone without touching any + /// state, so a Go Online the zone check would refuse is refused before it + /// stops wardriving. Null means go ahead; otherwise the error to show. Only + /// a definite refusal blocks: an in-zone answer still goes through the full + /// zone check and auth below. + Future _goOnlineZonePreflight() async { + final position = await _pickAuthFix(); + if (position == null) return null; + final result = await _apiService.checkZoneStatus( + lat: position.latitude, + lon: position.longitude, + accuracyMeters: position.accuracy, + appVersion: _appVersion, + radioFreq: liveRadioConfig ?? _lastRadioConfig, + ); + if (result == null) { + debugError('[APP] Cannot switch to online mode: zone check got no ' + 'answer'); + return _getErrorMessage('network_error', null); + } + if (result['success'] != true) { + final reason = result['reason'] as String?; + debugError('[APP] Cannot switch to online mode: zone check refused ' + '($reason)'); + return _getErrorMessage(reason, result['message'] as String?); + } + if (result['in_zone'] == false) { + debugError('[APP] Cannot switch to online mode: not in a zone'); + return goOnlineOutsideZoneMessage( + result['nearest_zone'] as Map?, + isImperial: _preferences.isImperial); + } + return null; + } + + Future<({bool success, String? error})> _switchToOnlineModeSteps() async { _isSwitchingMode = true; _modeSwitchError = null; var switchSucceeded = false; notifyListeners(); try { - // 1. Gracefully stop auto-ping if running (waits for RX window to complete) - await _stopAutoPingGracefully(); - - // 2. Save accumulated offline pings as session file. The only save on - // this path: the stop above holds its own back so the file is written - // once, here, after everything it flushed has landed in the queue. - await _saveOfflineSession(); - - // 4. Request new auth session + // Every check that can refuse the switch runs before anything stops. + // A refusal used to land after wardriving had stopped and the offline + // session had been closed, so each failed tap ended the drive and split + // it into another file. // Use "Anonymous" if renamed, otherwise real name final deviceName = _isAnonymousRenamed ? 'Anonymous' @@ -8053,6 +10435,20 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { return (success: false, error: _modeSwitchError); } + final zoneRefusal = await _goOnlineZonePreflight(); + if (zoneRefusal != null) { + _modeSwitchError = zoneRefusal; + return (success: false, error: _modeSwitchError); + } + + // 1. Gracefully stop auto-ping if running (waits for RX window to complete) + await _stopAutoPingGracefully(); + + // 2. Save accumulated offline pings as session file. The only save on + // this path: the stop above holds its own back so the file is written + // once, here, after everything it flushed has landed in the queue. + await _saveOfflineSession(); + // Clear offline mode before zone check so checkZoneStatus() doesn't skip the API call _preferences = _preferences.copyWith(offlineMode: false); _apiQueueService.offlineMode = false; @@ -8062,8 +10458,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (zoneCode == null) { debugError('[APP] Cannot switch to online mode: not in a zone'); - _modeSwitchError = - 'Could not determine your zone. Check GPS and internet connection.'; + _modeSwitchError = _inZone == false + ? goOnlineOutsideZoneMessage(_nearestZone, + isImperial: _preferences.isImperial) + : 'Could not determine your zone. Check GPS and internet connection.'; return (success: false, error: _modeSwitchError); } @@ -8077,6 +10475,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _meshCoreConnection?.deviceInfo?.manufacturer ?? 'Unknown'; + // The connect /auth's fix choice: the raw current fix is refused + // gps_inaccurate when it is coarse, and by now wardriving has stopped. + final authFix = await _pickAuthFix() ?? _currentPosition!; + var result = await _apiService.requestAuth( reason: 'connect', publicKey: _devicePublicKey!, @@ -8086,9 +10488,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { iataCode: zoneCode ?? _preferences.iataCode, model: modelString, radioFreq: _meshCoreConnection?.selfInfo?.radioConfigApi, - lat: _currentPosition!.latitude, - lon: _currentPosition!.longitude, - accuracyMeters: _currentPosition!.accuracy, + lat: authFix.latitude, + lon: authFix.longitude, + accuracyMeters: authFix.accuracy, ); // Check for maintenance mode @@ -8159,9 +10561,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { iataCode: zoneCode ?? _preferences.iataCode, model: modelString, radioFreq: _meshCoreConnection?.selfInfo?.radioConfigApi, - lat: _currentPosition!.latitude, - lon: _currentPosition!.longitude, - accuracyMeters: _currentPosition!.accuracy, + lat: authFix.latitude, + lon: authFix.longitude, + accuracyMeters: authFix.accuracy, ); if (registerResult == null) { @@ -8194,6 +10596,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // 5. Auth successful - update state switchSucceeded = true; + // Offline Mode is off for good now (the finally only rolls back a + // failed switch), so its auto-save stops here. + _stopOfflineAutoSaveTimer(); // 6. Update regional channels from auth response final channels = result['channels']; @@ -8207,6 +10612,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Track session zone for zone-to-zone transfer detection _sessionZoneCode = zoneCode; + _sessionGroupCode = zoneGroupCode; // Smart Pinging follows the new session and zone. _syncRecentCoverage(); @@ -8307,7 +10713,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { String? get _offlineDeviceName => _isAnonymousRenamed ? 'Anonymous' : (_meshCoreConnection?.selfInfo?.name ?? - connectedDeviceName?.replaceFirst('MeshCore-', '')); + connectedDeviceName?.replaceFirst('MeshCore-', '') ?? + // A reconnect that gave up has already dropped the connection. + _displayDeviceName); /// Save accumulated offline pings to a session file Future _saveOfflineSession() async { @@ -8333,7 +10741,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { devicePublicKey: _devicePublicKey, deviceName: offlineDeviceName, contactUri: _offlineContactUri, - radioConfig: _meshCoreConnection?.selfInfo?.radioConfigApi, + // The remembered config covers a reconnect that gave up, which has + // already dropped the connection. + radioConfig: liveRadioConfig ?? _lastRadioConfig, deviceModel: _meshCoreConnection?.deviceModel?.manufacturer ?? _meshCoreConnection?.deviceInfo?.manufacturer ?? _manufacturerString, @@ -8342,7 +10752,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ); _offlineSessionService.finalizeCurrentSession(); debugLog('[APP] Saved offline session with ${pings.length} pings'); - _stopOfflineAutoSaveTimer(); + // The auto-save keeps running: Offline Mode is still on, and the next + // connect or mode start in this stint needs it. It stops when Offline + // Mode is turned off. notifyListeners(); } @@ -8397,9 +10809,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } try { - final pings = (sessionData['pings'] as List) - .map((p) => Map.from(p as Map)) - .toList(); + final pings = withoutUnlabelledAltitude( + (sessionData['pings'] as List) + .map((p) => Map.from(p as Map)) + .toList()); if (pings.isEmpty) { debugLog('[APP] Session has no pings: $filename'); @@ -8616,11 +11029,6 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // lands the session is valid for the rest. await Future.delayed(const Duration(seconds: 2)); - // 4. Upload pings in batches of 50, retrying session/transient errors. - const batchSize = 50; - var uploadedCount = 0; - final totalBatches = (pings.length + batchSize - 1) ~/ batchSize; - // Accumulate the server's per-region placement summary across all batches so the uploaded // session can show where its pings landed (e.g. "DSA 88 · EMA 157 · too far 3"). Offline // uploads route each ping to its own region server-side; these come back per batch. @@ -8649,58 +11057,87 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { const firstBatchBackoff = [2, 3, 4, 5, 6, 8, 10]; const laterBatchBackoff = [2, 4]; - for (var i = 0; i < pings.length; i += batchSize) { - final batchNum = (i ~/ batchSize) + 1; - onProgress?.call('Batch $batchNum/$totalBatches'); - - final batch = pings.skip(i).take(batchSize).toList(); - final backoff = i == 0 ? firstBatchBackoff : laterBatchBackoff; - - var result = await _apiService.uploadBatchWithSessionId( - batch, offlineSessionId, - onResponse: accumulatePlacement); - - // Retry only session-propagation / transient errors. nonRetryable - // (data/zone/key) errors are NOT retried — we stop and preserve instead. - for (var retry = 0; - retry < backoff.length && - (result == UploadResult.sessionError || - result == UploadResult.retryable); - retry++) { - final delay = backoff[retry]; - final kind = - result == UploadResult.sessionError ? 'session' : 'transient'; - debugLog( - '[OFFLINE] Batch $batchNum $kind error, retry ${retry + 1}/${backoff.length} after ${delay}s'); - onProgress?.call('Batch $batchNum/$totalBatches (retry ${retry + 1})'); - await Future.delayed(Duration(seconds: delay)); - result = await _apiService.uploadBatchWithSessionId( - batch, offlineSessionId, + // 4. Strip SCOPES rows the upload auth cannot accept (ruling 6: the + // door only closes when the key itself is absent, never on + // `scope_discovery: false`, since the server accepts a verified + // answer whatever the flag says), move every remaining SCOPES row + // after every other row (DISC before SCOPES: the server records a + // chunk's DISC-heard keys before it checks any SCOPES in it, but + // refuses a SCOPES whose DISC only arrives in a LATER chunk), persist + // that order BEFORE the first chunk is built, then upload in chunks + // of 50, stopping at the first that does not succeed. Persisting + // before chunking (not after, and not only when something was + // stripped) is the point of `runOfflineChunkedUpload`: the + // partial-upload cleanup below removes a PREFIX of the STORED rows + // by uploaded count, so that prefix only lines up with what was + // actually sent when the file already holds the same order that was + // chunked. + final chunkedResult = await runOfflineChunkedUpload( + pings, + scopeDiscoveryOffered: effectiveAuth.containsKey('scope_discovery'), + batchSize: 50, + persistRows: (orderedRows) => + _offlineSessionService.replacePings(filename, orderedRows), + uploadChunk: (chunk, chunkNumber, totalChunks) async { + onProgress?.call('Batch $chunkNumber/$totalChunks'); + + final backoff = + chunkNumber == 1 ? firstBatchBackoff : laterBatchBackoff; + var result = await _apiService.uploadBatchWithSessionId( + chunk, offlineSessionId, onResponse: accumulatePlacement); - } - if (result == UploadResult.success) { - uploadedCount += batch.length; - debugLog('[OFFLINE] Uploaded batch $batchNum: ${batch.length} pings'); - _forwardOfflineBatchToCustomApi( - batch, - batchNum: batchNum, - publicKey: uploadPublicKey, - auth: effectiveAuth, - ); - continue; - } + // Retry only session-propagation / transient errors. nonRetryable + // (data/zone/key) errors are NOT retried: we stop and preserve instead. + for (var retry = 0; + retry < backoff.length && + (result == UploadResult.sessionError || + result == UploadResult.retryable); + retry++) { + final delay = backoff[retry]; + final kind = + result == UploadResult.sessionError ? 'session' : 'transient'; + debugLog( + '[OFFLINE] Batch $chunkNumber $kind error, retry ${retry + 1}/${backoff.length} after ${delay}s'); + onProgress + ?.call('Batch $chunkNumber/$totalChunks (retry ${retry + 1})'); + await Future.delayed(Duration(seconds: delay)); + result = await _apiService.uploadBatchWithSessionId( + chunk, offlineSessionId, + onResponse: accumulatePlacement); + } - // Any non-success after retries: STOP and preserve the remaining pings. - // We never discard un-uploaded data — it stays in the file for a later retry. - final stopReason = result == UploadResult.sessionError - ? 'session error' - : result == UploadResult.nonRetryable - ? 'data/zone error' - : 'network error'; - debugWarn( - '[OFFLINE] Batch $batchNum stopped ($stopReason) — preserving remaining pings'); - break; + if (result == UploadResult.success) { + debugLog( + '[OFFLINE] Uploaded batch $chunkNumber: ${chunk.length} pings'); + return true; + } + + // Any non-success after retries: STOP and preserve the remaining pings. + // We never discard un-uploaded data, it stays in the file for a later retry. + final stopReason = result == UploadResult.sessionError + ? 'session error' + : result == UploadResult.nonRetryable + ? 'data/zone error' + : 'network error'; + debugWarn( + '[OFFLINE] Batch $chunkNumber stopped ($stopReason), preserving remaining pings'); + return false; + }, + forwardChunk: (chunk, chunkNumber) => _forwardOfflineBatchToCustomApi( + chunk, + batchNum: chunkNumber, + publicKey: uploadPublicKey, + auth: effectiveAuth!, + ), + ); + + final orderedPings = chunkedResult.orderedRows; + final uploadedCount = chunkedResult.uploadedCount; + if (chunkedResult.removedScopesCount > 0) { + debugLog( + '[OFFLINE] Stripped ${chunkedResult.removedScopesCount} SCOPES ' + 'item(s): the upload auth did not offer scope discovery'); } // Delay after posting before disconnect @@ -8717,7 +11154,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // 6. Clean up session based on results — prune ONLY successfully-uploaded // pings; everything not uploaded is preserved in the file for a later retry. - final remainingPings = pings.length - uploadedCount; + final remainingPings = orderedPings.length - uploadedCount; if (remainingPings <= 0) { await _offlineSessionService.markAsUploaded( @@ -8796,6 +11233,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { 'externalAntenna=${preferences.externalAntenna}, autoPowerSet=${preferences.autoPowerSet}'); _preferences = preferences; + _scopeLifecycle.onGateChanged(_scopeGateInputs, + passiveOrHybridRunning: _isPassiveOrHybridModeRunning, + startRepeaterRefresh: _startScopeRepeaterRefreshForRunningMode); // Update user-original baseline when user changes zone-overridable settings if (_userOriginalAutoPingInterval != null) { @@ -8925,13 +11365,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// forever, and the release call can fail, leaving hasApiSession stale. void _syncRecentCoverage({bool sessionEnded = false}) { _recentCoverage.configure( - zone: zoneCode, + // The region's site, or the group's: the same tiles the overlay paints. + zone: coverageHostCode, gridSize: _preferences.coverageGridSize, days: smartPingDays, radioKey: radioFilterKey, + floodOnly: smartPingFloodOnly, + // A group handoff has no session for its two round trips; the lookup + // keeps its tiles, marks and banked ping through that gap. enabled: !sessionEnded && smartPingEnabled && - hasApiSession && + (hasApiSession || _groupHandoffOwnsRecoverySlot) && !_preferences.offlineMode, ); final p = _currentPosition; @@ -9004,6 +11448,19 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _savePreferences(); } + /// Show or hide the dashed lines from a selected repeater to the coverage + /// squares that heard it, and persist. Like the opacity above this must NOT + /// bump mapRevision: nothing in MapWidget.build() reads it. MapWidget redraws + /// or clears the lines of the selected repeater from its direct provider + /// listener (`_onRepeaterCoverageLinesNotify`), so the change shows straight + /// away, even while the Settings tab is in front of the map. + void setShowRepeaterCoverageLines(bool value) { + _preferences = _preferences.copyWith(showRepeaterCoverageLines: value); + debugLog('[MAP] Repeater coverage lines set to $value'); + notifyListeners(); + _savePreferences(); + } + /// Set app theme mode (dark/light) and persist void setThemeMode(String mode) { _preferences = _preferences.copyWith(themeMode: mode); @@ -9217,7 +11674,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { case 'bad_session': return 'Invalid session. Please reconnect.'; case 'outofdate': - return 'App version outdated. Please update to the latest version.'; + return 'This version of the app is out of date, update the MeshMapper ' + 'app on your phone to keep wardriving.'; case 'session_invalid': return 'Session is invalid. Please reconnect.'; case 'session_revoked': @@ -9244,6 +11702,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// This may trigger auto-disconnect Future handleSessionError(String? reason, String? message, {String? subReason}) async { + // A teardown is already running. Its last upload can be answered with a + // session error, and acting on that answer would start a second + // disconnect inside the first and pop the error tab over it. + if (_userRequestedDisconnect && + _connectionStep == ConnectionStep.disconnecting) { + debugLog('[SESSION] $reason during disconnect, already tearing down'); + return; + } + final userMessage = _getErrorMessage(reason, message, subReason: subReason); final isStationaryRevoke = reason == 'session_revoked' && subReason == 'stationary'; @@ -9421,6 +11888,39 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _maintenanceCheckTimer = null; } + /// How long the connect /auth waits for a fix the server will accept. + static const Duration _authFixWait = Duration(seconds: 4); + + /// The fix the connect /auth sends. The current one when it is accurate + /// enough (50 m), else the newest accurate fix from the last 60 s, else + /// the first accurate one within [_authFixWait]. Falls back to the current + /// fix, so the server answers exactly as it did before this check existed. + Future _pickAuthFix() async { + final current = _currentPosition; + if (current != null && GpsService.isAccurateForZoneCheck(current)) { + return current; + } + final currentText = current == null + ? 'no fix' + : '${current.accuracy.toStringAsFixed(0)}m fix'; + final recent = _gpsService.bestRecentZoneCheckFix(); + if (recent != null) { + debugLog('[GPS] [AUTH] Current $currentText too coarse, using a recent ' + '${recent.accuracy.toStringAsFixed(1)}m fix'); + return recent; + } + debugLog('[GPS] [AUTH] Current $currentText too coarse, waiting up to ' + '${_authFixWait.inSeconds}s for a more accurate one'); + final waited = await _gpsService.waitForZoneCheckFix(_authFixWait); + if (waited != null) { + debugLog('[GPS] [AUTH] Got a ${waited.accuracy.toStringAsFixed(1)}m fix'); + return waited; + } + debugWarn('[GPS] [AUTH] No accurate fix within ' + '${_authFixWait.inSeconds}s, sending the current $currentText'); + return current; + } + // ============================================ // GPS Validation // ============================================ @@ -9511,6 +12011,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Single timer: ticks every 1s, retries at 0 _zoneCheckCountdownTimer = Timer.periodic(const Duration(seconds: 1), (_) { + // Held while GPS is off in the background with no radio: the retry + // would read location. The countdown picks up where it was once the app + // is back on screen and GPS runs again. + if (_gpsStoppedByPolicy) return; _zoneCheckRetryCountdown--; notifyListeners(); if (_zoneCheckRetryCountdown <= 0) { @@ -9533,9 +12037,38 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _zoneCheckError = null; _zoneCheckErrorReason = null; _zoneCheckRetryCountdown = 0; + _zoneCheckNetworkFailures = 0; // Don't notifyListeners here — caller will do it or checkZoneStatus will } + /// A zone check was held back because no fix is accurate enough yet. + /// Before the first zone result this shows the existing Weak GPS Signal + /// state and arms its 10 s retry (whose fresh read is what finds a better + /// fix on a phone standing still). Once a zone result is known it stays, + /// and nothing is surfaced. Re-arming is skipped while that wait is + /// already counting down, so a stream of coarse fixes cannot reset it. + void _noteZoneCheckWaitingForGps(Position position) { + if (_inZone != null) return; + // A no-answer retry keeps its backed-off slot: replacing it with this + // 10 s wait made a coarse fix cut the backoff short. + if (_zoneCheckCountdownTimer != null && + (_zoneCheckErrorReason == 'gps_inaccurate' || + _zoneCheckErrorReason == 'network')) { + return; + } + final accuracy = position.accuracy.toStringAsFixed(0); + final max = GpsService.maxAccuracyMetersForZoneCheck.toStringAsFixed(0); + debugLog('[GPS] Waiting for a more accurate fix before the zone check ' + '(${accuracy}m, max ${max}m)'); + unawaited(_refreshLocationAccuracyReduced()); + _scheduleZoneCheckRetry( + seconds: 10, + error: 'GPS accuracy is ${accuracy}m (max ${max}m). ' + 'Waiting for a more accurate fix.', + reason: 'gps_inaccurate', + ); + } + /// Check zone status via API /// Should be called on app launch and every 100m of GPS movement while disconnected Future checkZoneStatus() async { @@ -9569,15 +12102,51 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // or overwritten by _scheduleZoneCheckRetry on failure. try { + // Never send a fix the server will refuse for accuracy. Use the current + // fix when it is good enough, else the newest good one from the last + // 60 s, else one fresh hardware read (the stream is quiet while the + // phone stands still, which is how a retry finds a better fix). + final current = _currentPosition!; + var position = GpsService.isAccurateForZoneCheck(current) + ? current + : _gpsService.bestRecentZoneCheckFix(); + if (position == null) { + if (_gpsStoppedByPolicy) { + // GPS is off in the background with no radio, and a fresh read + // would use location anyway. Once GPS runs again, its restart and + // its fixes recheck the zone. + debugLog('[GPS] Zone check skipped: GPS is off in the background'); + return; + } + final fresh = await _gpsService.getFreshPosition(); + if (fresh != null && GpsService.isAccurateForZoneCheck(fresh)) { + position = fresh; + } + } + if (position == null) { + debugLog('[GPS] Zone check held: fix accuracy ' + '${current.accuracy.toStringAsFixed(0)}m (max ' + '${GpsService.maxAccuracyMetersForZoneCheck.toStringAsFixed(0)}m), ' + 'waiting for a more accurate fix'); + _noteZoneCheckWaitingForGps(current); + return; + } + if (!identical(position, current)) { + debugLog('[GPS] Zone check using a recent accurate fix ' + '(${position.accuracy.toStringAsFixed(1)}m) instead of the current ' + '${current.accuracy.toStringAsFixed(0)}m one'); + } + debugLog( - '[GEOFENCE] Making API call to check zone at ${_currentPosition!.latitude.toStringAsFixed(5)}, ' - '${_currentPosition!.longitude.toStringAsFixed(5)} (accuracy: ${_currentPosition!.accuracy.toStringAsFixed(1)}m)'); + '[GEOFENCE] Making API call to check zone at ${position.latitude.toStringAsFixed(5)}, ' + '${position.longitude.toStringAsFixed(5)} (accuracy: ${position.accuracy.toStringAsFixed(1)}m)'); final result = await _apiService.checkZoneStatus( - lat: _currentPosition!.latitude, - lon: _currentPosition!.longitude, - accuracyMeters: _currentPosition!.accuracy, + lat: position.latitude, + lon: position.longitude, + accuracyMeters: position.accuracy, appVersion: _appVersion, + radioFreq: liveRadioConfig ?? _lastRadioConfig, ); debugLog( @@ -9586,10 +12155,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (result == null) { // Update position even on failure to prevent zone check flooding // (without this, every GPS update re-triggers a zone check while driving) - _lastZoneCheckPosition = _currentPosition; - debugError('[GEOFENCE] Zone status check failed: no response from API'); + _lastZoneCheckPosition = position; + final retrySeconds = + zoneCheckNetworkRetrySeconds(++_zoneCheckNetworkFailures); + debugError('[GEOFENCE] Zone status check failed: no response from API ' + '(retry in ${retrySeconds}s)'); _scheduleZoneCheckRetry( - seconds: 5, + seconds: retrySeconds, error: 'Verify your internet connection', reason: 'network', ); @@ -9617,7 +12189,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Clear maintenance if normal response _clearMaintenanceMode(); - _lastZoneCheckPosition = _currentPosition; + _lastZoneCheckPosition = position; final success = result['success'] == true; if (!success) { @@ -9627,7 +12199,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugError( '[GEOFENCE] Zone status check failed: reason=$reason, message=$message'); - if (reason == 'gps_inaccurate') { + if (reason == 'gps_inaccurate' && _inZone != null) { + // A zone result is already known and stands. A refused weak fix + // says nothing about the zone, so it must not replace that result + // with "GPS Unavailable"; the next accurate fix rechecks. + debugWarn('[GEOFENCE] gps_inaccurate on a recheck, keeping the ' + 'last zone result (inZone=$_inZone)'); + } else if (reason == 'gps_inaccurate') { logError('Weak GPS Signal\n$message', autoSwitch: false); // Schedule a retry so we don't depend solely on the GPS stream firing // again — on first launch the stream may stall on a low-accuracy fix @@ -9669,22 +12247,46 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final newZoneCode = newZone?['code'] as String? ?? ''; final newZoneName = newZone?['name'] ?? 'Unknown'; - // Detect zone-to-zone transition during active session + // Detect zone-to-zone transition during active session. A move to + // another member of the session's own region group is handed off + // without the user seeing it; anything else is the visible transfer. + final move = classifyZoneMove( + sessionZone: _sessionZoneCode, + sessionGroup: _sessionGroupCode, + newZone: newZoneCode, + newGroup: parseZoneGroup(newZone)?.code, + ); if (isConnected && !_preferences.offlineMode && - _sessionZoneCode != null && - newZoneCode.isNotEmpty && - newZoneCode != _sessionZoneCode && + move != ZoneMove.none && !_isInZoneGracePeriod && !_isZoneTransferInProgress) { + final previousGroup = zoneGroupCode; _currentZone = newZone; + _noteZoneGroupChange(previousGroup); + _invalidateRepeatersForContext(); _nearestZone = null; _syncRecentCoverage(); + if (move == ZoneMove.hiddenHandoff) { + // A later tick while the handoff runs still reads the old + // session zone, so it lands here again and must not start a + // second swap; the running one owns the move. + if (_liveSessionRecoveryInFlight != null) { + debugLog('[ZONE] Group handoff deferred: a session swap is ' + 'already running'); + return; + } + unawaited(_startGroupHandoff(newZoneCode, newZoneName)); + return; + } await _handleZoneTransfer(newZoneCode, newZoneName); return; } + final previousGroup = zoneGroupCode; _currentZone = newZone; + _noteZoneGroupChange(previousGroup); + _invalidateRepeatersForContext(); _nearestZone = null; // The lookup is keyed on the zone, so re-sync whenever it moves. _syncRecentCoverage(); @@ -9703,11 +12305,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { if (newZoneCode.isNotEmpty) { _fetchRepeatersForZone( newZoneCode); // fire-and-forget — don't block zone check - _fetchBorderPolygons(newZoneCode); // fire-and-forget + _fetchBorderPolygons(newZoneCode, + fix: position); // fire-and-forget } } else { _regionBorders = []; - _bordersLoadedForZone = null; + _borderLoader.forget(); _currentZone = null; _syncRecentCoverage(); _nearestZone = result['nearest_zone'] as Map?; @@ -9718,11 +12321,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { '[GEOFENCE] Outside zone. Nearest: $nearestName (${distanceKm}km away)'); // Clear repeaters when exiting zone - _repeaters = []; - _repeaterConflictHexIds = const {}; - _siriRepeaterCatalogRevision++; - _repeatersLoaded = false; - _repeatersLoadedForIata = null; + _invalidateRepeatersForContext(); } } catch (e) { debugError('[GEOFENCE] Zone status check error: $e'); @@ -9753,6 +12352,13 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog( '[CAPACITY] Updated slots_max from auth: ${authResult['slots_max']}'); } + // /auth resolves flood for the live radio preset, so it outranks a + // /status answer that may have used a stale cached preset. + if (authResult.containsKey('flood_disabled')) { + _currentZone!['flood_disabled'] = authResult['flood_disabled'] == true; + debugLog('[CAPACITY] Updated flood_disabled from auth: ' + '${authResult['flood_disabled']}'); + } // Sync at_capacity with tx_allowed final authTxAllowed = authResult['tx_allowed'] == true; @@ -9766,8 +12372,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } // If auth says TX allowed and we have slot data but server didn't provide updated count, - // decrement by 1 (we just took a slot) - if (authTxAllowed && !authResult.containsKey('slots_available')) { + // decrement by 1 (we just took a slot). A reused session took none. + if (authTookNewSlot(authResult)) { final available = _currentZone!['slots_available'] as int?; if (available != null && available > 0) { _currentZone!['slots_available'] = available - 1; @@ -9838,6 +12444,10 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _autoPingEnabled = false; _resetIdleAutoStop(); await _pingService?.forceDisableAutoPing(); + // This disables the mode without going through the normal stop + // (_finishAutoPingStop), so the periodic scope-discovery repeater + // refresh timer needs its own stop here too. + _scopeLifecycle.stopRepeaterRefreshTimer(); debugLog('[ZONE GRACE] Auto-ping paused'); } @@ -9853,8 +12463,11 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // Cancel idle disconnect timer _cancelIdleDisconnectTimer(); - // Stop background service - await BackgroundServiceManager.stopService(); + // Stop iOS's per-mode service. Android's session service stays up: the + // radio is still connected, and its notification reads Outside zone. + if (!BackgroundServiceManager.followsConnection) { + await BackgroundServiceManager.stopService(); + } // Clear API queue — items have gap-GPS coords that would be rejected again await _apiQueueService.clearOnDisconnect(); @@ -10060,6 +12673,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final oldZoneCode = _sessionZoneCode ?? 'unknown'; _isZoneTransferInProgress = true; + _scopeLifecycle.onEvent(ScopeStopEvent.zoneTransfer); _zoneTransferFrom = oldZoneCode; _zoneTransferTo = newZoneCode; _invalidateLiveSessionRecovery(); @@ -10106,6 +12720,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await _apiService.requestAuth( reason: 'disconnect', publicKey: _devicePublicKey!, + extras: const {'disconnect_cause': 'zone_transfer'}, ); debugLog('[ZONE] Old session released'); } catch (e) { @@ -10235,6 +12850,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // 11. Auth succeeded — update session zone code _sessionZoneCode = newZoneCode; + _sessionGroupCode = zoneGroupCode; debugLog('[ZONE] Auth succeeded for zone $newZoneCode'); if (result['type'] != null) { @@ -10346,13 +12962,12 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } // 17. Fetch repeaters for the new zone - _repeatersLoaded = false; - _repeatersLoadedForIata = null; + _invalidateRepeatersForContext(); await _fetchRepeatersForZone(newZoneCode); - // Fetch updated boundary polygons for the new zone - _bordersLoadedForZone = null; - _regionBorders = []; + // Boundary polygons for the new zone. A context or hash the loader + // already holds keeps its borders (or comes from the cache); anything + // else clears them just before the request. _fetchBorderPolygons(newZoneCode); // fire-and-forget // 18. Re-enable heartbeat @@ -10418,101 +13033,366 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { await disconnect(); } - /// Fetch repeaters for a zone (called when zone is discovered) - /// Only fetches once per IATA code to avoid redundant network requests - Future _fetchRepeatersForZone(String iata) async { - // Skip if already loaded for this IATA - if (_repeatersLoaded && _repeatersLoadedForIata == iata) { - debugLog('[MAP] Repeaters already loaded for zone: $iata'); + /// Ruling 10: the connect-time, mode-start and periodic repeater refresh + /// for scope discovery. A list that lands after the context (the zone, or + /// its group) or the radio preset moved is dropped. Only one refresh runs + /// at a time; a call while one is already in flight is a no-op. + /// + /// The fetch goes to the member's site ([iata]); the list is keyed on + /// [_repeaterContextKey], so a move between members of one group neither + /// discards an in-flight answer nor reads as a new zone for the map. + Future _refreshRepeatersForScopes(String iata) async { + final key = _repeaterContextKey; + if (key == null) return; + if (_scopeRepeaterRefreshInFlight) { + debugLog('[SCOPES] Repeater list refresh for zone $iata skipped: ' + 'one is already in flight'); return; } + _scopeRepeaterRefreshInFlight = true; + try { + debugLog('[SCOPES] Refreshing the repeater list for zone $iata'); + final preset = radioFilterKey; + final fetched = await _scopeLifecycle.resultIfStillCurrent( + fetch: _apiService.fetchRepeaters(iata), + zone: key, + preset: preset, + currentZone: () => _repeaterContextKey, + currentPreset: () => radioFilterKey, + ); + if (_isDisposed) return; + final refreshedState = _repeaterListState.afterFetch( + fetched: fetched, + requestedZone: key, + requestedPreset: preset, + currentZone: _repeaterContextKey, + currentPreset: radioFilterKey, + now: DateTime.now(), + ); + if (identical(refreshedState, _repeaterListState)) return; + final refreshed = refreshedState.repeaters; + // Wanted for its scope stamps: when nothing the map draws moved, the + // map is not rebuilt for it (Rule 9). + final mapChanged = !_repeatersLoaded || + _repeatersLoadedForIata != key || + scopeRefreshChangesMap(_repeaters, refreshed); + _repeaterListState = refreshedState; + _repeaterConflictHexIds = rcConflictHexIds(_repeaters); + _siriRepeaterCatalogRevision++; + debugLog('[SCOPES] Repeater list refreshed (${_repeaters.length}' + '${mapChanged ? '' : ', nothing on the map changed'})'); + if (mapChanged) { + _notifyMapNow(); + } else { + notifyListeners(); + } + } finally { + _scopeRepeaterRefreshInFlight = false; + } + } + + /// Passive or Hybrid mode just started: refreshes the repeater list at + /// once when it is already older than [scopeListRefreshOnStartAge] + /// (rather than waiting for the connect-time refresh or the first + /// periodic tick to catch it), then arms the periodic refresh + /// ([scopeListRefreshPeriod]) for as long as the mode keeps running. + /// Both are gated on [scopeDiscoveryActive] (gate open, not offline, + /// firmware at or above the floor), so a user without scope discovery + /// sees no change in traffic. The timer itself is stopped wherever the + /// mode stops or the connection goes (`toggleAutoPing`'s mode switch, + /// `_finishAutoPingStop`, and every `ScopeLifecycle` stop event). + void _startScopeRepeaterRefreshForRunningMode() { + final plan = scopeModeStartRefreshPlan( + active: scopeDiscoveryActive, + zone: zoneCode, + loadedAt: _repeatersLoadedAt, + now: DateTime.now()); + if (!plan.armTimer) return; + if (plan.refreshNow) { + debugLog('[SCOPES] Repeater list refresh on mode start (older than ' + '${scopeListRefreshOnStartAge.inMinutes}m)'); + unawaited(_refreshRepeatersForScopes(zoneCode!)); + } + _scopeLifecycle.startRepeaterRefreshTimer(scopeListRefreshPeriod, () { + if (!scopePeriodicRefreshShouldRun( + active: scopeDiscoveryActive, + passiveOrHybridRunning: _isPassiveOrHybridModeRunning, + zone: zoneCode)) { + return; + } + debugLog('[SCOPES] Periodic repeater list refresh ' + '(${scopeListRefreshPeriod.inMinutes}m)'); + unawaited(_refreshRepeatersForScopes(zoneCode!)); + }); + } + + /// Whether Passive or Hybrid is the mode currently running: the two modes + /// the scope-discovery repeater refresh (mode-start check, periodic + /// timer, gate-reopen re-arm) exists for. + bool get _isPassiveOrHybridModeRunning => + _autoPingEnabled && + (_autoMode == AutoMode.passive || _autoMode == AutoMode.hybrid); + + /// Builds one sweep's scope runner, or null when scope discovery is not + /// active. Handed to PingService as its factory. + ScopeRunner? _buildScopeRunner( + {required DateTime hardStop, required ScopeCancelToken cancel}) { + final connection = _meshCoreConnection; + return _scopeLifecycle.buildRunner( + gate: _scopeGateInputs, + connection: connection, + deviceKey: _devicePublicKey ?? _apiService.sessionId, + create: (deviceKey, pendingRestores, knownNonContacts) => ScopeRunner( + radio: MeshCoreScopeRadio(connection!), + cancel: cancel, + hardStop: hardStop, + refreshDays: () => scopeRefreshDays, + deviceKey: () => + _devicePublicKey ?? _apiService.sessionId ?? deviceKey, + sessionId: () => _apiService.sessionId, + queueGeneration: () => _apiQueueService.generation, + serverInfo: _scopeServerInfoFor, + cache: _scopeQueryCache, + budget: _scopeHourlyBudget, + enqueue: (answer, ctx) => _apiQueueService.enqueueScopes( + publicKeyHex: answer.keyHex, + scopes: answer.scopes, + lat: answer.lat, + lon: answer.lon, + timestamp: answer.timestampSec, + expectedGeneration: ctx.queueGeneration, + radioFreq: liveRadioConfig, + ), + onCacheStamped: () => unawaited(_scopeCacheWriter.schedule()), + nowSec: () => DateTime.now().millisecondsSinceEpoch ~/ 1000, + currentPosition: () { + final p = _currentPosition; + return p == null ? null : (lat: p.latitude, lon: p.longitude); + }, + stillWanted: _scopeStillWanted, + onActiveChanged: _scopeLifecycle.setRequestActive, + onLogged: _addScopeLogEntry, + pendingRestores: pendingRestores, + knownNonContacts: knownNonContacts, + cannotAskNonContacts: () => connection.scopeCannotAskNonContacts, + ), + ); + } + + /// Mode on, gate active, not airborne, not mid mode switch, zone transfer + /// or reconnect. + bool _scopeStillWanted() { + final ping = _pingService; + return ping != null && + isConnected && + ping.autoPingEnabled && + (ping.isPassiveMode || ping.isHybridMode) && + scopeDiscoveryActive && + !_gpsService.isAirborne && + !_scopeLifecycle.modeSwitching && + !_isZoneTransferInProgress && + !_isAutoReconnecting; + } + + ({bool onList, int? checkedAt}) _scopeServerInfoFor(String keyHex) { + if (!identical(_scopeServerInfoSource, _repeaters)) { + _scopeServerInfo = scopeServerInfoMap(_repeaters); + _scopeServerInfoSource = _repeaters; + } + return scopeServerInfoFor(_scopeServerInfo, keyHex); + } + + Future _loadScopeDiscoveryState() async { + final nowSec = DateTime.now().millisecondsSinceEpoch ~/ 1000; + Map? cacheJson; + Map? budgetJson; + final box = await _openBoxSafely(_preferencesBoxName); + if (box != null) { + try { + cacheJson = decodeScopeJsonMap(box.get(_scopeQueryCacheKey)); + budgetJson = decodeScopeJsonMap(box.get(_scopeHourBudgetKey)); + } catch (e) { + debugError('[SCOPES] Failed to load scope state: $e'); + } + } + _scopeQueryCache = ScopeQueryCache.fromJson(cacheJson) + ..prune(nowSec: nowSec, refreshDays: scopeRefreshDays); + _scopeHourlyBudget = ScopeHourlyBudget.fromJson(budgetJson, + save: _saveScopeHourBudget, nowSec: nowSec); + } + + /// The budget's writer. Throws on failure, so the reservation reads as + /// not saved and its answer is dropped. + Future _saveScopeHourBudget(Map json) async { + final box = await _openBoxSafely(_preferencesBoxName); + if (box == null) throw StateError('preferences box unavailable'); + await box.put(_scopeHourBudgetKey, jsonEncode(json)); + await box.flush(); + } + + Future _saveScopeQueryCache() async { + final box = await _openBoxSafely(_preferencesBoxName); + if (box == null) throw StateError('preferences box unavailable'); + await box.put(_scopeQueryCacheKey, jsonEncode(_scopeQueryCache.toJson())); + await box.flush(); + } + + /// Drop a list as soon as its context (the region, or its group) or preset + /// ceases to be valid. Same-context failures leave the existing list + /// untouched. + void _invalidateRepeatersForContext() { + final retained = + _repeaterListState.forContext(_repeaterContextKey, radioFilterKey); + if (identical(retained, _repeaterListState)) return; + _repeaterListState = retained; + _repeaterConflictHexIds = const {}; + _siriRepeaterCatalogRevision++; + _notifyMapNow(); + } + + /// Fetch repeaters when a zone is discovered, including before connection. + /// + /// The fetch goes to the member's site ([iata], which already answers for + /// the whole group); the list is keyed on [_repeaterContextKey], so a move + /// between members of one group finds the list already loaded. + Future _fetchRepeatersForZone(String iata) async { + if (_isDisposed || zoneCode != iata) return; + final key = _repeaterContextKey; + if (key == null) return; + _invalidateRepeatersForContext(); + if (_repeatersLoaded && _repeatersLoadedForIata == key) return; + final preset = radioFilterKey; + final request = (key, preset); + if (!_repeaterLoadsInFlight.add(request)) return; debugLog('[MAP] Fetching repeaters for zone: $iata'); try { final fetchedRepeaters = await _apiService.fetchRepeaters(iata); - if (fetchedRepeaters.isNotEmpty) { - _repeaters = rcComputeExclusions(fetchedRepeaters); + if (_isDisposed) return; + final refreshed = _repeaterListState.afterFetch( + fetched: fetchedRepeaters, + requestedZone: key, + requestedPreset: preset, + currentZone: _repeaterContextKey, + currentPreset: radioFilterKey, + now: DateTime.now(), + ); + if (!identical(refreshed, _repeaterListState)) { + _repeaterListState = refreshed; _repeaterConflictHexIds = rcConflictHexIds(_repeaters); _siriRepeaterCatalogRevision++; - _repeatersLoaded = true; - _repeatersLoadedForIata = iata; debugLog('[MAP] Loaded ${_repeaters.length} repeaters for zone $iata'); _notifyMapNow(); - } else { - debugWarn( - '[MAP] No repeaters returned for zone $iata — will retry on next zone check'); + } else if (fetchedRepeaters.isEmpty) { + debugWarn('[MAP] No repeaters returned for zone $iata; ' + 'will retry on next zone check'); } } catch (e) { debugError('[MAP] Failed to fetch repeaters: $e'); + } finally { + _repeaterLoadsInFlight.remove(request); } } /// Fetch regional boundary polygons for the current zone. - /// Called after a successful zone check; idempotent per IATA so the - /// /border endpoint is only hit once per zone transition. - Future _fetchBorderPolygons(String iata) async { - if (_bordersLoadedForZone == iata) return; - if (_bordersFetchInProgress) return; - if (_currentPosition == null) return; - - _bordersFetchInProgress = true; - try { - final result = await _apiService.fetchBorderPolygons( - lat: _currentPosition!.latitude, - lon: _currentPosition!.longitude, - appVersion: _appVersion, - ); - if (result != null && result.isNotEmpty) { - _regionBorders = result; - _bordersLoadedForZone = iata; - debugLog('[BORDER] Loaded ${result.length} polygon(s) for $iata'); + /// Called after every successful zone check; [BorderLoader] decides + /// whether `/border` is actually asked (once per context and + /// `border_hash`, never two at a time, backing off after a failure). The + /// context is the zone or its group (see [_repeaterContextKey]); `/border` + /// already returns every member of a group, so a move between members + /// keeps the polygons. + /// + /// `/border` is sent [fix], the fix `/status` placed the phone with + /// (default [_lastZoneCheckPosition]), never the live one, which may have + /// moved on; an answer that does not fit the zone is discarded anyway. + Future _fetchBorderPolygons(String iata, {Position? fix}) async { + final key = _repeaterContextKey; + final position = fix ?? _lastZoneCheckPosition ?? _currentPosition; + final zone = zoneCode; + if (key == null || position == null || zone == null) return; + final members = zoneGroup?.members; + final hash = _currentZone?['border_hash']; + + var asked = false; + final result = await _borderLoader.ensure( + contextKey: key, + borderHash: hash is String && hash.isNotEmpty ? hash : null, + onStale: () { + if (_regionBorders.isEmpty) return; + _regionBorders = []; + notifyListeners(); + }, + accept: (polygons) => + bordersFitZone(polygons, zoneCode: zone, groupMembers: members), + fetch: () { + asked = true; + return _apiService.fetchBorderPolygons( + lat: position.latitude, + lon: position.longitude, + appVersion: _appVersion, + ); + }, + ); + if (_isDisposed) return; + if (_repeaterContextKey != key) { + if (result == null && !asked) return; + // The zone moved on while this ran. Whatever is shown belongs to the + // old context, so clear it and load the new one now rather than on + // the next zone tick. + _borderLoader.forget(); + if (_regionBorders.isNotEmpty) { + _regionBorders = []; notifyListeners(); - } else { - debugWarn( - '[BORDER] No polygons returned for zone $iata — will retry on next zone check'); } - } finally { - _bordersFetchInProgress = false; + final next = zoneCode; + if (next != null && _inZone == true) unawaited(_fetchBorderPolygons(next)); + return; } + if (result == null) return; + _regionBorders = result; + debugLog('[BORDER] Loaded ${result.length} polygon(s) for $iata'); + notifyListeners(); } // ============================================ // Debug File Logging (Mobile Only) // ============================================ - /// Initialize debug file logging, respecting persisted user preference. - /// Enabled by default on all builds. If the user previously disabled it, - /// that preference is restored. + /// Reconcile debug file logging with the persisted user preference. + /// Enabled by default on all builds. `main.dart` already read the + /// preference and opened (or did not open) the file, so in the normal case + /// nothing changes here; the two branches only matter when the two reads + /// disagreed (a transient Hive timeout in main). The flag mirrors what the + /// logger is really doing, never the preference alone, so the switch can + /// not read OFF while a file keeps growing. Future _initDebugLogs() async { if (kIsWeb) return; // File logging not available on web try { final box = await _openBoxSafely(_preferencesBoxName); - if (box == null) { - // Can't read preference — keep default (enabled, already started in main.dart) - _debugLogsEnabled = true; - await _refreshDebugLogFiles(); - return; - } - - final userDisabled = box.get('debug_logs_enabled') == false; - - if (userDisabled) { - debugLog('[INIT] Debug logs disabled by user preference, turning off'); + final wanted = + DebugFileLogger.wantsFileLogging(box?.get('debug_logs_enabled')); + if (wanted && !DebugFileLogger.isEnabled) { + await DebugFileLogger.enable(); + } else if (!wanted && DebugFileLogger.isEnabled) { + debugLog('[INIT] File logging stopped: preference is off'); await DebugFileLogger.disable(); - _debugLogsEnabled = false; - DebugLogger.setEnabled(false); - } else { - debugLog('[INIT] Debug logging enabled (${AppConstants.appVersion})'); - // DebugFileLogger already enabled in main.dart - _debugLogsEnabled = true; - await _refreshDebugLogFiles(); } } catch (e) { debugError('[INIT] Failed to init debug logs: $e'); - // Fallback: keep enabled (already started in main.dart) - _debugLogsEnabled = true; } + _debugLogsEnabled = DebugFileLogger.isEnabled; + DebugLogger.setEnabled(_debugLogsEnabled); + if (_debugLogsEnabled) { + debugLog('[INIT] Debug logging enabled (${AppConstants.appVersion})'); + } + final stubs = await DebugFileLogger.deleteStartupStubs(); + if (stubs > 0) { + debugLog('[INIT] Deleted $stubs startup stub log file(s)'); + } + // Files from earlier sessions are listed whether or not logging is on, + // so they can still be viewed, uploaded and deleted. + await _refreshDebugLogFiles(); } /// Enable debug file logging @@ -10571,6 +13451,16 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } } + /// List the debug log files without touching the live log. + /// + /// The upload sheet and the feedback dialog list from this; the one + /// rotation an upload needs happens at submit, in + /// [prepareDebugLogsForUpload], never on opening a sheet. + Future> listDebugLogFiles() async { + await _refreshDebugLogFiles(); + return _debugLogFiles; + } + /// Prepare debug logs for upload by rotating the current log file /// /// This ensures the files being uploaded are complete and not actively being written to. @@ -10616,12 +13506,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Share a debug log file /// /// Uses the native share sheet to allow users to share logs via email, messaging, etc. - Future shareDebugLog(File file) async { + /// [sharePositionOrigin] is the tapped button's global rect, which iPad needs + /// (see [shareOfflineSession]). + Future shareDebugLog(File file, {Rect? sharePositionOrigin}) async { try { final result = await SharePlus.instance.share( ShareParams( files: [XFile(file.path)], subject: 'MeshMapper Debug Log', + sharePositionOrigin: sharePositionOrigin, ), ); debugLog('[DEBUG] Shared log: ${file.path}, status: ${result.status}'); @@ -10634,12 +13527,17 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// to Files, Drive, email, …) — the mobile equivalent of the web JSON /// download. Mirrors [shareDebugLog]; writes the same pretty JSON the web /// path produces. Throws on failure so the caller can surface an error. - Future shareOfflineSession(String filename) async { + /// + /// [sharePositionOrigin] is the global rect of the tapped button. iPad + /// anchors the share popover there, and share_plus refuses to open the + /// sheet on iPad without one. + Future shareOfflineSession(String filename, + {Rect? sharePositionOrigin}) async { final data = _offlineSessionService.getSessionData(filename); if (data == null) { throw Exception('Session "$filename" not found'); } - final jsonString = const JsonEncoder.withIndent(' ').convert(data); + final jsonString = offlineSessionJson(data); final dir = await getTemporaryDirectory(); final file = File('${dir.path}/$filename'); await file.writeAsString(jsonString); @@ -10647,11 +13545,61 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { ShareParams( files: [XFile(file.path)], subject: 'MeshMapper Offline Session', + sharePositionOrigin: sharePositionOrigin, ), ); debugLog('[OFFLINE] Shared session: $filename, status: ${result.status}'); } + bool _isExportingOfflineSessions = false; + + /// True while Export all is writing its files or its share sheet is open. + bool get isExportingOfflineSessions => _isExportingOfflineSessions; + + /// Export every stored offline session in one share sheet (#560): one file + /// per session, the same name and JSON as [shareOfflineSession]. + /// + /// Only reads the sessions. Nothing is deleted or marked uploaded, whatever + /// the share sheet's outcome. A dismissed sheet is not an error. Throws on + /// failure so the caller can surface it; does nothing when there are no + /// sessions or an export is already running. + /// [sharePositionOrigin] is the tapped button's global rect (iPad anchor). + Future shareAllOfflineSessions({Rect? sharePositionOrigin}) async { + if (_isExportingOfflineSessions) return; + // Snapshot: an auto-save during the export must not change what is sent. + final sessions = List.of(_offlineSessionService.sessions); + if (sessions.isEmpty) return; + _isExportingOfflineSessions = true; + notifyListeners(); + try { + debugLog('[OFFLINE] Exporting all ${sessions.length} sessions'); + // Its own folder, emptied first: the last export's copies are gone by + // now, and a single session share in the temp root is not overwritten. + // Not deleted after the share, which can return before the receiving + // app has read the files. + final temp = await getTemporaryDirectory(); + final dir = Directory('${temp.path}/offline_export'); + if (await dir.exists()) await dir.delete(recursive: true); + await dir.create(recursive: true); + final files = await writeOfflineSessionExports(sessions, dir); + final result = await SharePlus.instance.share( + ShareParams( + files: files.map((f) => XFile(f.path)).toList(), + subject: 'MeshMapper Offline Sessions', + sharePositionOrigin: sharePositionOrigin, + ), + ); + debugLog( + '[OFFLINE] Shared all ${files.length} sessions, status: ${result.status}'); + } catch (e) { + debugError('[OFFLINE] Failed to export all sessions: $e'); + rethrow; + } finally { + _isExportingOfflineSessions = false; + notifyListeners(); + } + } + /// View a debug log file in-app /// /// Reads the file contents and stores them for display in a dialog. @@ -10829,6 +13777,59 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { bool _carpeaterReentryPromptDue = false; bool get carpeaterReentryPromptDue => _carpeaterReentryPromptDue; + /// Runs the Precise Location check at Connect. + final PreciseLocationGate _preciseLocationGate = PreciseLocationGate(); + + /// Location is granted but only approximate, as last read while a zone + /// check was held for a coarse fix. The zone check screen then says + /// Precise Location is off instead of blaming the GPS signal. + bool _locationAccuracyReduced = false; + bool get locationAccuracyReduced => _locationAccuracyReduced; + + Future _refreshLocationAccuracyReduced() async { + final reduced = await _preciseLocationGate.isApproximateOnly( + platform: PreciseLocationGate.currentPlatform, + simulatorEnabled: _gpsService.isSimulatorEnabled, + ); + if (_isDisposed || reduced == _locationAccuracyReduced) return; + _locationAccuracyReduced = reduced; + debugLog('[GPS] Location accuracy is ' + '${reduced ? 'approximate only' : 'no longer approximate'}'); + notifyListeners(); + } + + /// Back from the settings with Precise Location turned on: restart a + /// running stream so its fixes come in precise, as the connect check does. + Future _recheckLocationAccuracyAfterResume() async { + if (!_locationAccuracyReduced) return; + await _refreshLocationAccuracyReduced(); + if (_isDisposed || _locationAccuracyReduced) return; + if (_gpsService.isWatching) { + await restartGpsAfterPermission(keepTracking: true); + } + } + bool _preciseLocationCheckInFlight = false; + + /// Set when the last connect tap was refused for approximate location. + /// Read by the Siri connect answer; reset at the next check. + bool _connectRefusedForPreciseLocation = false; + bool _preciseLocationPromptDue = false; + + /// True when a connect was refused (or an auto-reconnect ended) for + /// approximate location. MainScaffold shows "Precise Location needed". + bool get preciseLocationPromptDue => _preciseLocationPromptDue; + + void acknowledgePreciseLocationPrompt() { + _preciseLocationPromptDue = false; + } + + /// Android: shows the location disclosure and re-requests fine location, + /// which Android 12+ answers with its "precise" upgrade dialog when only + /// approximate is granted. Registered by MainScaffold, which owns the + /// disclosure; null while no screen can show it. Returns true when the + /// system request was made. + Future Function()? preciseLocationUpgradeRequester; + void acknowledgeCarpeaterReentryPrompt() { _carpeaterReentryPromptDue = false; } @@ -11001,6 +14002,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { final json = box.get('preferences'); _onboardingGuideProgress = OnboardingGuideProgress.fromStored(box.get(_onboardingGuideVersionKey)); + _mapViewState = MapViewState.fromStored(box.get(_mapViewStateKey)); + debugLog('[MAP] Loaded map view: $_mapViewState'); if (json != null) { // The pre-share 6-hex prefix is wiped, not migrated: the filter needs // the full key now, and the user is asked for it after the next @@ -11042,7 +14045,71 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { debugLog('[APP] Failed to load preferences: $e'); } _preferencesLoaded = true; - notifyListeners(); + // A map revision bump, not a plain notify: the map sits behind the + // mapRevision Selector and applies its saved toggles and the remembered + // map view on its next build. + _notifyMapNow(); + } + + // ============================================ + // Map view (zoom, folded panels) persistence + // ============================================ + + static const String _mapViewStateKey = 'map_view_state'; + MapViewState _mapViewState = const MapViewState(); + + /// Writes wait until the map has been still for this long, so a pinch (and + /// the auto-follow camera's idles) ends in one write. + final Debouncer _mapViewStateSaver = + Debouncer(const Duration(milliseconds: 1500)); + + /// Fold or unfold the control panel (both orientations). + void setMapControlsMinimized(bool value) => + _updateMapViewState(_mapViewState.copyWith(controlsMinimized: value)); + + /// Landscape: show or close the control panel. + void setMapControlPanelShown(bool value) => + _updateMapViewState(_mapViewState.copyWith(controlPanelShown: value)); + + /// Landscape: open or close the map's control column. + void setLandscapeMapControlsExpanded(bool value) => _updateMapViewState( + _mapViewState.copyWith(landscapeMapControlsExpanded: value)); + + /// Portrait: open or close the map's control column. No notify: only the + /// map reads it, and it rebuilds itself on the tap. + void setMapControlsColumnExpanded(bool value) => _updateMapViewState( + _mapViewState.copyWith(mapControlsExpanded: value), + notify: false); + + /// Remember the zoom the camera settled at. Called by the map on camera + /// idle outside transient views; repeats at the same zoom are dropped. + void rememberMapZoom(double zoom) { + if (!MapViewState.zoomWorthSaving(_mapViewState.zoom, zoom)) return; + final clamped = MapViewState.clampZoom(zoom); + if (clamped == null) return; + _updateMapViewState(_mapViewState.copyWith(zoom: clamped), notify: false); + } + + void _updateMapViewState(MapViewState next, {bool notify = true}) { + if (next == _mapViewState) return; + _mapViewState = next; + if (notify) notifyListeners(); + // Before the stored value has been read, a write would replace it with + // the defaults; the change still applies in memory. + if (!_preferencesLoaded) return; + _mapViewStateSaver.schedule(() => unawaited(_saveMapViewState())); + } + + Future _saveMapViewState() async { + if (_isDisposed) return; + final box = await _openBoxSafely(_preferencesBoxName); + if (box == null) return; + try { + await box.put(_mapViewStateKey, _mapViewState.toStorage()); + debugLog('[MAP] Saved map view: $_mapViewState'); + } catch (e) { + debugError('[MAP] Failed to save map view: $e'); + } } Future completeOnboardingGuide() async { @@ -11079,6 +14146,36 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _syncCarpeaterFilter(); } + Future _loadRepeaterNicknames() async { + final box = await _openBoxSafely(_preferencesBoxName); + if (box == null) return; + try { + _repeaterNicknames = + RepeaterNicknames.sanitize(box.get(_repeaterNicknamesKey)); + debugLog('[APP] Loaded ${_repeaterNicknames.length} repeater nicknames'); + } catch (e) { + debugError('[APP] Failed to load repeater nicknames: $e'); + _repeaterNicknames = const {}; + } + } + + Future _saveRepeaterNicknames() async { + final box = await _openBoxSafely(_preferencesBoxName); + if (box == null) { + debugError('[APP] Repeater nicknames not saved: preferences unavailable'); + return; + } + try { + await box.put( + _repeaterNicknamesKey, + RepeaterNicknames.toStorage(_repeaterNicknames), + ); + await box.flush(); + } catch (e) { + debugError('[APP] Failed to save repeater nicknames: $e'); + } + } + Future _loadLastRadioConfig() async { final box = await _openBoxSafely(_preferencesBoxName); if (box == null) return; @@ -11571,7 +14668,15 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { // The radio signs the RAW 32 bytes, never their hex text. signature = await connection.sign(nonceBytes); } on SignException catch (e) { - if (e.code == 'unsupported') { + final action = signFailureAction(e.code); + if (action == SignFailureAction.backoff) { + // Scope discovery held the radio for the whole wait. That says + // nothing about the firmware, so no strike: retry on the ladder. + debugLog('[ACCOUNT] Radio busy with scope discovery for ' + '${_pkPrefix(pubkey)}, backing off'); + return _recordLinkFailure(pubkey, 'sign_busy'); + } + if (action == SignFailureAction.strike) { // Two strikes before this is written down. A stats/battery ERR that // was already in flight when the sign started is misattributed as // 'unsupported' (see the ERR branch in connection.dart) — one stray @@ -11591,7 +14696,8 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } else { debugWarn('[ACCOUNT] Sign failed (${e.code}) — staying silent'); } - return const PortalLinkOutcome(PortalLinkStatus.failed); + return PortalLinkOutcome(PortalLinkStatus.failed, + radioCouldNotSign: signFailureNeedsRadioReboot(e.code)); } catch (e) { debugWarn('[ACCOUNT] Sign failed (${e.runtimeType}) — staying silent'); return const PortalLinkOutcome(PortalLinkStatus.failed); @@ -11849,16 +14955,35 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { /// Exit the app completely (Android only) /// Uses SystemNavigator.pop() which is the recommended way to exit on Android Future exitApp() async { + // The upload before the release can take a few seconds, and a second tap + // in that window saw isConnected false and closed the app before the + // session was released and the radio's name and channel restored. + if (_exitInProgress) { + debugLog('[APP] Exit already in progress'); + return; + } + _exitInProgress = true; debugLog('[APP] Exit app requested'); - // Disconnect first if connected - if (isConnected) { - await disconnect(); - } + try { + // Disconnect first if connected. closeApp: false because the exit below + // already stops the service and closes the app. + if (isConnected) { + await disconnect(closeApp: false, flushQueue: true); + } - // Exit the app (Android only - iOS doesn't allow programmatic app exit) - if (Platform.isAndroid) { - SystemNavigator.pop(); + // disconnect() stops Android's session service when the session ends. + // This stop also covers one still running with no radio session, and + // does not wait for MainActivity's own stop when it is destroyed + // (Android only, a no-op elsewhere). + await BackgroundServiceManager.stopLiveService('exit app'); + + // Exit the app (Android only - iOS doesn't allow programmatic app exit) + if (Platform.isAndroid) { + SystemNavigator.pop(); + } + } finally { + _exitInProgress = false; } } @@ -11927,8 +15052,9 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { } try { - _storedNoiseFloorSessions = _noiseFloorSessionBox!.values.toList() - ..sort((a, b) => b.startTime.compareTo(a.startTime)); // Newest first + // Newest first. A session the app was killed during is closed here. + _storedNoiseFloorSessions = + await loadStoredNoiseFloorSessions(_noiseFloorSessionBox!); debugLog( '[GRAPH] Loaded ${_storedNoiseFloorSessions.length} stored noise floor sessions'); } catch (e) { @@ -11953,10 +15079,30 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { markers: List.of(_startingDeferredHistory), ); _startingDeferredHistory.clear(); + _noiseFloorCheckpointTimer?.cancel(); + _noiseFloorCheckpointTimer = Timer.periodic( + _noiseFloorCheckpointInterval, + (_) => unawaited(_checkpointNoiseFloorSession('periodic'))); debugLog('[GRAPH] Started $mode noise floor session'); notifyListeners(); } + /// Writes the running session to Hive (see [NoiseFloorCheckpoint]). A + /// launch closes a checkpoint the app never ended. + Future _checkpointNoiseFloorSession(String why) async { + final session = _currentNoiseFloorSession; + if (session == null) return; + try { + if (await _noiseFloorCheckpoint.write(_noiseFloorSessionBox, session)) { + debugLog('[GRAPH] Checkpointed session ($why): ' + '${session.samples.length} samples, ' + '${session.markers.length} markers'); + } + } catch (e) { + debugError('[GRAPH] Failed to checkpoint noise floor session: $e'); + } + } + /// Record a noise floor sample to the current session void _recordNoiseFloorSample(int noiseFloor) { if (_currentNoiseFloorSession != null) { @@ -12003,28 +15149,18 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { Future _endNoiseFloorSession() async { if (_currentNoiseFloorSession == null) return; + _noiseFloorCheckpointTimer?.cancel(); + _noiseFloorCheckpointTimer = null; _currentNoiseFloorSession!.endTime = DateTime.now(); debugLog( '[GRAPH] Ended session: ${_currentNoiseFloorSession!.durationDisplay}, ' '${_currentNoiseFloorSession!.samples.length} samples, ' '${_currentNoiseFloorSession!.markers.length} markers'); - // Save to Hive + // Save to Hive (over its checkpoint, if any) and keep the last 10 try { - await _noiseFloorSessionBox?.put( - _currentNoiseFloorSession!.id, - _currentNoiseFloorSession!, - ); - - // Update stored list - _storedNoiseFloorSessions.insert(0, _currentNoiseFloorSession!); - - // Keep only last 10 sessions - while (_storedNoiseFloorSessions.length > 10) { - final oldest = _storedNoiseFloorSessions.removeLast(); - await _noiseFloorSessionBox?.delete(oldest.id); - debugLog('[GRAPH] Deleted oldest session: ${oldest.id}'); - } + await saveEndedNoiseFloorSession(_noiseFloorSessionBox, + _storedNoiseFloorSessions, _currentNoiseFloorSession!); } catch (e) { debugError('[GRAPH] Failed to save noise floor session: $e'); } @@ -12109,6 +15245,56 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { notifyListeners(); } + /// Debug-only store capture mode: waits up to 10 s for the repeater list so + /// the sample drive hears real repeaters, then loads it. Never awaited by + /// init. + Future _seedStoreCapture() async { + for (var waited = 0; + _repeaters.isEmpty && waited < 20 && !_isDisposed; + waited++) { + await Future.delayed(const Duration(milliseconds: 500)); + } + if (_isDisposed) return; + final now = DateTime.now(); + applyStoreCaptureSample(buildStoreCaptureSample( + newest: DateTime(now.year, now.month, now.day, 9, 40), + repeaters: + _repeaters.map((r) => (id: r.id, lat: r.lat, lon: r.lon)).toList(), + )); + debugLog('[CAPTURE] seeded ${_txPings.length} TX, ${_rxPings.length} RX, ' + 'repeaters=${_repeaters.length}'); + } + + /// Debug-only store capture mode: puts the sample drive into the in-memory + /// lists the Map, Log and History screens read. Writes no Hive box and no + /// preference, and leaves [connectedDeviceName] alone. + void applyStoreCaptureSample(StoreCaptureSample s) { + _txPings + ..clear() + ..addAll(s.txPings); + _rxPings + ..clear() + ..addAll(s.rxPings); + _txLogEntries + ..clear() + ..addAll(s.txLog); + _rxLogEntries + ..clear() + ..addAll(s.rxLog); + _discLogEntries + ..clear() + ..addAll(s.disc); + _traceLogEntries + ..clear() + ..addAll(s.trace); + _storedNoiseFloorSessions.insertAll(0, s.sessions); + _pingStats = s.stats; + _currentNoiseFloor = s.noiseFloor; + _currentBatteryPercent = s.batteryPercent; + _storeCaptureRadioName = storeCaptureRadioName; + _notifyMapNow(); + } + /// Bump the map revision but coalesce notifications to ~4/sec. Use for /// high-frequency map-relevant changes (passive RX pins, echo bursts) so a /// dense mesh cannot force the map to rebuild 10-20x/sec. The pin data is @@ -12134,12 +15320,16 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { void notifyListeners() { if (_isDisposed) return; super.notifyListeners(); + _syncGpsWithPolicy('state change'); + _syncConnectionService(); _scheduleLiveActivitySync(); } @override void dispose() { _isDisposed = true; + _mapViewStateSaver.cancel(); + _scopeLifecycle.onEvent(ScopeStopEvent.dispose); _invalidateLiveSessionRecovery(); // No notify in dispose: the session just has to let the radio go. _repeaterAdminSession?.close(); @@ -12167,6 +15357,7 @@ class AppStateProvider extends ChangeNotifier with WidgetsBindingObserver { _restoreAutoPingTimer?.cancel(); _idleDisconnectTimer?.cancel(); _offlineAutoSaveTimer?.cancel(); + _noiseFloorCheckpointTimer?.cancel(); _zoneRefreshTimer?.cancel(); _cancelZoneGraceTimers(); _vectorFreshTimer?.cancel(); diff --git a/lib/providers/repeater_list_state.dart b/lib/providers/repeater_list_state.dart new file mode 100644 index 00000000..33001b2f --- /dev/null +++ b/lib/providers/repeater_list_state.dart @@ -0,0 +1,48 @@ +import '../models/repeater.dart'; +import '../utils/repeater_collision.dart'; + +/// Immutable repeater cache value. AppStateProvider owns every replacement. +class RepeaterListState { + final List repeaters; + final String? zone; + final String? preset; + final DateTime? loadedAt; + + const RepeaterListState() + : repeaters = const [], + zone = null, + preset = null, + loadedAt = null; + + RepeaterListState._( + List fetched, this.zone, this.preset, this.loadedAt) + : repeaters = rcComputeExclusions(fetched); + + /// Clear incompatible markers immediately, before the next read completes. + RepeaterListState forContext(String? currentZone, String? currentPreset) { + if (loadedAt == null || (zone == currentZone && preset == currentPreset)) { + return this; + } + return const RepeaterListState(); + } + + /// Failures and stale replies cannot replace a valid cache or revive an old + /// region. Empty successful reads retain the existing refresh behavior. + RepeaterListState afterFetch({ + required List? fetched, + required String requestedZone, + required String? requestedPreset, + required String? currentZone, + required String? currentPreset, + required DateTime now, + }) { + final retained = forContext(currentZone, currentPreset); + if (fetched == null || + fetched.isEmpty || + requestedZone != currentZone || + requestedPreset != currentPreset) { + return retained; + } + return RepeaterListState._(fetched, requestedZone, requestedPreset, now); + } +} diff --git a/lib/screens/connection_screen.dart b/lib/screens/connection_screen.dart index d728cc48..1bad556b 100644 --- a/lib/screens/connection_screen.dart +++ b/lib/screens/connection_screen.dart @@ -11,13 +11,20 @@ import '../models/connection_state.dart'; import '../models/remembered_device.dart'; import '../models/user_preferences.dart'; import '../providers/app_state_provider.dart'; +import '../services/precise_location_gate.dart'; +import '../utils/debug_logger_io.dart'; import '../utils/distance_formatter.dart'; +import '../utils/slots_chip.dart'; +import '../utils/store_links.dart'; import '../services/bluetooth/bluetooth_service.dart'; +import '../services/location_consent.dart'; +import '../services/permission_disclosure_service.dart'; import '../services/transport/android_serial_service.dart'; import '../services/transport/tcp_service.dart'; import '../services/transport/web_serial_factory.dart'; import '../widgets/offline_mode_toggle.dart'; import '../widgets/regional_config_card.dart'; +import '../widgets/update_required_panel.dart'; import 'onboarding/onboarding_prompt_gate.dart'; /// BLE device selection and connection screen @@ -71,18 +78,48 @@ class _ConnectionScreenState extends State } } - /// Request location permission - tries to request first, opens settings if permanently denied + /// Request location permission. Tries the system prompt first and opens the + /// app settings when it is permanently denied, or when the request came back + /// denied without a dialog ever being shown (Android stops prompting after + /// two refusals but can still report plain `denied`). Future _requestLocationPermission(AppStateProvider appState) async { // Check current permission status LocationPermission permission = await Geolocator.checkPermission(); + // The disclosure comes before every system prompt and until it is agreed + // to, even with location granted (Google Play), except on web. + if (!kIsWeb && + LocationConsent.needsDisclosure( + agreed: await LocationConsent.hasAgreed(), + aboutToRequest: permission == LocationPermission.denied, + )) { + if (!mounted) return; + final agreed = + await PermissionDisclosureService.showLocationDisclosure(context); + if (!agreed) return; + } + // If denied (not permanently), try requesting again if (permission == LocationPermission.denied) { + final stopwatch = Stopwatch()..start(); permission = await Geolocator.requestPermission(); + stopwatch.stop(); + debugLog('[GPS] Location permission request returned $permission ' + 'after ${stopwatch.elapsedMilliseconds}ms'); + if (permission == LocationPermission.denied && + PermissionDisclosureService.deniedWithoutDialog(stopwatch.elapsed)) { + // No dialog was shown, so a person cannot have just refused. Without + // this the button silently did nothing on every tap. + debugLog('[GPS] Location denied without a system dialog, ' + 'opening app settings'); + await Geolocator.openAppSettings(); + return; + } } // If permanently denied, open app settings if (permission == LocationPermission.deniedForever) { + debugLog('[GPS] Location permanently denied, opening app settings'); await Geolocator.openAppSettings(); return; } @@ -191,6 +228,16 @@ class _ConnectionScreenState extends State return _buildDeviceList(context, appState); } + // The server refused this build: an update panel, not an error card + final updateRequirement = appState.appUpdateRequirement; + if (updateRequirement != null) { + return UpdateRequiredPanel( + requirement: updateRequirement, + onUpdate: _openStoreLink, + onBack: () => appState.startScan(), + ); + } + // Show error if (appState.connectionError != null) { return _buildError(context, appState); @@ -266,7 +313,7 @@ class _ConnectionScreenState extends State icon: Icons.link_off, label: 'Disconnect', color: Colors.red, - onPressed: () async => await appState.disconnect(), + onPressed: () async => await appState.disconnect(flushQueue: true), ); } @@ -402,6 +449,20 @@ class _ConnectionScreenState extends State 'Step ${step.stepNumber} of $totalSteps', style: Theme.of(context).textTheme.bodySmall, ), + // Only the wait for the radio can be cancelled. Past it the + // handshake has its own cleanup and finishes on its own. + if (appState.canCancelConnect || + appState.isCancellingConnect) ...[ + SizedBox(height: isLandscape ? 16 : 24), + OutlinedButton( + onPressed: appState.isCancellingConnect + ? null + : () => appState.cancelConnect(), + child: Text(appState.isCancellingConnect + ? 'Cancelling' + : 'Cancel'), + ), + ], ], ), ), @@ -738,6 +799,7 @@ class _ConnectionScreenState extends State final channelsCard = RegionalConfigCard( zoneName: appState.offlineMode ? null : appState.zoneName, zoneCode: appState.offlineMode ? null : appState.zoneCode, + groupCode: appState.offlineMode ? null : appState.zoneGroupCode, channels: appState.offlineMode ? [] : appState.regionalChannels, scope: appState.offlineMode ? null : appState.scope, isOfflineMode: appState.offlineMode, @@ -1417,6 +1479,18 @@ class _ConnectionScreenState extends State ); } + /// Opens the store (or release page) the update panel picked. + Future _openStoreLink(StoreLink link) async { + debugLog('[UI] Opening update link ${link.uri}'); + try { + final opened = + await launchUrl(link.uri, mode: LaunchMode.externalApplication); + if (!opened) debugWarn('[UI] Could not open update link ${link.uri}'); + } catch (e) { + debugWarn('[UI] Opening update link failed: $e'); + } + } + Widget _buildError(BuildContext context, AppStateProvider appState) { final isLandscape = MediaQuery.of(context).orientation == Orientation.landscape; @@ -1472,12 +1546,21 @@ class _ConnectionScreenState extends State String locationText; String? iataCode; Color locationColor; + VoidCallback? locationTap; // Airborne block applies in every mode, so it comes first if (appState.isAirborne) { locationIcon = Icons.airplanemode_active; locationText = 'Airborne'; locationColor = Colors.red; + // Location off (Not Now on the disclosure, or not granted). This bar is + // on every tab, so tapping it is the way back to the disclosure and the + // system prompt; Offline Mode needs location too. + } else if (appState.gpsStatus == GpsStatus.permissionDenied) { + locationIcon = Icons.location_disabled; + locationText = 'Location Off'; + locationColor = Colors.orange; + locationTap = () => _requestLocationPermission(appState); // Offline mode: show greyed out with "-" } else if (appState.offlineMode) { locationIcon = Icons.gps_off; @@ -1511,8 +1594,8 @@ class _ConnectionScreenState extends State locationColor = Colors.blue; } else if (appState.inZone == true) { locationIcon = Icons.location_on; - locationText = appState.zoneName ?? 'Unknown'; - iataCode = appState.zoneCode; + locationText = appState.displayZoneName ?? 'Unknown'; + iataCode = appState.shortZoneCode; locationColor = Colors.green; } else if (appState.inZone == false) { locationIcon = Icons.location_off; @@ -1524,30 +1607,14 @@ class _ConnectionScreenState extends State locationColor = Colors.grey; } - // Slots info - final slotsAvailable = appState.zoneSlotsAvailable; - final slotsMax = appState.zoneSlotsMax; - final hasSlots = slotsAvailable != null && slotsMax != null; - - // A flood-disabled region hands out no TX slots at all. Before connecting - // the auth flag isn't known yet, so fall back to the shape of the zone: a - // 0-max zone isn't FULL, it simply offers no TX slots. Either way it's a - // regional setting, so show info blue and drop the misleading 0/0 count. - final passiveOnly = appState.floodDisabled || slotsMax == 0; - - // Slots color based on availability - Color slotsColor; - if (passiveOnly) { - slotsColor = Colors.blue; - } else if (!hasSlots) { - slotsColor = Colors.grey; - } else if (slotsAvailable == 0) { - slotsColor = Colors.red; - } else if (slotsAvailable <= 2) { - slotsColor = Colors.orange; - } else { - slotsColor = Colors.green; - } + // Slots info. Flood is per radio preset and independent of the slot + // count, so a 0-slot preset with flood on reads "0 Slots", not "Flood Off". + final slotsChip = slotsChipState( + authFloodDisabled: appState.floodDisabled, + zoneFloodDisabled: appState.zoneFloodDisabled, + slotsAvailable: appState.zoneSlotsAvailable, + slotsMax: appState.zoneSlotsMax, + ); return Container( width: double.infinity, @@ -1578,6 +1645,7 @@ class _ConnectionScreenState extends State icon: locationIcon, text: locationText, color: locationColor, + onTap: locationTap, ), ), @@ -1598,14 +1666,12 @@ class _ConnectionScreenState extends State // Slots chip _buildChip( - icon: passiveOnly ? Icons.waves : Icons.people_outline, - text: passiveOnly - ? 'Flood Off' - : hasSlots - ? '$slotsAvailable/$slotsMax Open' - : '--', - color: slotsColor, - onTap: passiveOnly ? () => _showFloodDisabledInfo(context) : null, + icon: slotsChip.icon, + text: slotsChip.label, + color: slotsChip.color, + onTap: slotsChip.tappable + ? () => _showFloodDisabledInfo(context) + : null, ), ], ), @@ -1653,12 +1719,11 @@ class _ConnectionScreenState extends State ); } - /// Explains a flood-disabled region. + /// Explains a flood veto for the radio's current preset. /// /// The chip has room for eight characters, which cannot say that Trace Mode /// still works, so the detail lives here. Layout mirrors - /// [_showAuthMethodInfo]; wording matches the region-veto dialog in - /// MainScaffold so users see one consistent explanation. + /// [_showAuthMethodInfo]. void _showFloodDisabledInfo(BuildContext context) { final bodyStyle = TextStyle( fontSize: 14, @@ -1720,9 +1785,10 @@ class _ConnectionScreenState extends State Text( 'This region has grown large enough that flood traffic ' 'started hurting the mesh, so the regional mesh chose ' - 'to turn it off. Active and Hybrid modes are ' - 'unavailable across the whole MeshMapper region you ' - 'are in. It is not a capacity limit.', + 'to turn it off for your radio\'s settings (frequency, ' + 'bandwidth and spreading factor). Active and Hybrid ' + 'modes are unavailable on these settings. It is not a ' + 'capacity limit.', style: bodyStyle, ), const SizedBox(height: 12), @@ -1915,6 +1981,24 @@ class _ConnectionScreenState extends State ); } + // Location not granted: no zone check can run, and Offline Mode needs + // location too. + if (appState.gpsStatus == GpsStatus.permissionDenied) { + return _buildMessageContent( + context: context, + icon: Icons.location_off, + iconColor: Colors.orange.withValues(alpha: 0.7), + title: 'Location Permission Required', + message: 'MeshMapper needs your location to check your zone and map ' + 'coverage.', + action: FilledButton.icon( + onPressed: () => _requestLocationPermission(appState), + icon: const Icon(Icons.location_on), + label: const Text('Enable Location'), + ), + ); + } + // Show onboarding message when outside zone (but NOT when offline mode is enabled) if (appState.inZone == false && !appState.offlineMode) { // Build message with nearest zone info if available @@ -1982,7 +2066,7 @@ class _ConnectionScreenState extends State ), const SizedBox(height: 8), Text( - countdown > 0 + countdown > 0 && !appState.isCheckingZone ? 'Retrying in ${countdown}s...' : 'Retrying...', textAlign: TextAlign.center, @@ -1991,7 +2075,16 @@ class _ConnectionScreenState extends State color: Colors.grey.shade500, ), ), - const SizedBox(height: 32), + // The automatic retry backs off to once a minute, so a + // connection that comes back can be tried straight away. + TextButton.icon( + onPressed: appState.isCheckingZone + ? null + : () => appState.checkZoneStatus(), + icon: const Icon(Icons.refresh, size: 18), + label: const Text('Retry Now'), + ), + const SizedBox(height: 24), FilledButton.icon( onPressed: () => appState.setOfflineMode(true), icon: const Icon(Icons.cloud_off), @@ -2039,6 +2132,26 @@ class _ConnectionScreenState extends State if (appState.zoneCheckErrorReason == 'gps_inaccurate' || appState.zoneCheckErrorReason == 'gps_stale') { final isStale = appState.zoneCheckErrorReason == 'gps_stale'; + // Approximate-only location never gets under the accuracy limit, + // so moving somewhere else would not help: point at the setting. + if (!isStale && appState.locationAccuracyReduced) { + return _buildMessageContent( + context: context, + icon: Icons.location_disabled, + iconColor: Colors.orange.withValues(alpha: 0.7), + title: preciseLocationOffTitle, + message: preciseLocationOffBody, + action: FilledButton.icon( + onPressed: Geolocator.openAppSettings, + icon: const Icon(Icons.settings), + label: const Text('Open Settings'), + style: FilledButton.styleFrom( + padding: + const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + ), + ), + ); + } return _buildMessageContent( context: context, icon: isStale ? Icons.schedule : Icons.gps_off, @@ -2225,22 +2338,6 @@ class _ConnectionScreenState extends State ); } - if (appState.gpsStatus == GpsStatus.permissionDenied) { - return _buildMessageContent( - context: context, - icon: Icons.location_off, - iconColor: Colors.orange.withValues(alpha: 0.7), - title: 'GPS Permission Required', - message: - 'Location access is needed to verify you\'re in an allowed zone.', - action: ElevatedButton.icon( - onPressed: () => _requestLocationPermission(appState), - icon: const Icon(Icons.location_on), - label: const Text('Enable Location'), - ), - ); - } - return _buildMessageContent( context: context, icon: Icons.bluetooth_searching, diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index b8046fc1..66eb71c1 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -1,6 +1,8 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../debug/store_capture.dart'; import '../models/connection_state.dart'; import '../providers/app_state_provider.dart'; import '../utils/distance_formatter.dart'; @@ -20,11 +22,36 @@ class HomeScreen extends StatefulWidget { } class _HomeScreenState extends State { - bool _showControlPanel = true; - bool _isControlsMinimized = false; + // The panel fold state lives in AppStateProvider.mapViewState so it survives + // a relaunch; these getters read it live (build watches the provider). + AppStateProvider get _appState => context.read(); + + /// Landscape: the control panel is shown (closed = a small Controls button). + bool get _showControlPanel => _appState.mapViewState.controlPanelShown; + set _showControlPanel(bool value) => _appState.setMapControlPanelShown(value); + + // Store capture mode (debug builds) starts with the controls out of the way + // and keeps its fold state local, so a capture run never rewrites the + // user's saved layout. + bool? _storeCaptureControlsMinimized = + kDebugMode && StoreCaptureConfig.active != null ? true : null; + + bool get _isControlsMinimized => + _storeCaptureControlsMinimized ?? + _appState.mapViewState.controlsMinimized; + set _isControlsMinimized(bool value) { + if (_storeCaptureControlsMinimized != null) { + _storeCaptureControlsMinimized = value; + } else { + _appState.setMapControlsMinimized(value); + } + } /// Landscape mode: map controls expanded state (mutually exclusive with control panel) - bool _mapControlsExpanded = false; + bool get _mapControlsExpanded => + _appState.mapViewState.landscapeMapControlsExpanded; + set _mapControlsExpanded(bool value) => + _appState.setLandscapeMapControlsExpanded(value); /// Landscape side panel width (220px gives more room for controls) static const double _landscapePanelWidth = 220.0; @@ -182,12 +209,10 @@ class _HomeScreenState extends State { style: TextStyle(fontSize: 18), ), Text( - appState.connectedDeviceName != null - ? _buildSubtitle(appState) - : 'Disconnected', + appState.headerRadioName ?? 'Disconnected', style: TextStyle( fontSize: 12, - color: appState.connectedDeviceName != null + color: appState.headerRadioName != null ? Theme.of(context).colorScheme.onSurfaceVariant : Colors.grey, ), @@ -370,7 +395,7 @@ class _HomeScreenState extends State { if (appState.inZone == true && appState.zoneCode != null) { if (!appState.isConnected) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an authorized zone. Connect to a device to start wardriving.', Icons.flight, Colors.grey @@ -381,7 +406,7 @@ class _HomeScreenState extends State { // deliberate regional setting (blue). if (appState.floodDisabled) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'Your regional admin has turned off flood traffic here, so Active and Hybrid modes are unavailable. The zone is not full. Passive and Trace modes still work.', Icons.flight, Colors.blue @@ -389,14 +414,14 @@ class _HomeScreenState extends State { } if (!appState.txAllowed) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an authorized zone. However, the zone is at Active Wardrive capacity. You can still wardrive, but only Passive mode works.', Icons.flight, Colors.red ); } return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an active zone with ${appState.zoneSlotsAvailable ?? "?"} TX slots available. Ready to wardrive!', Icons.flight, Colors.green @@ -615,11 +640,11 @@ class _HomeScreenState extends State { children: [ // Device name Text( - appState.displayDeviceName ?? 'Disconnected', + appState.headerRadioName ?? 'Disconnected', style: TextStyle( fontSize: 12, fontWeight: FontWeight.w500, - color: appState.connectedDeviceName != null + color: appState.headerRadioName != null ? Colors.white : Colors.grey.shade400, ), @@ -854,7 +879,7 @@ class _HomeScreenState extends State { ? Colors.green : Colors.red) : Colors.grey; - text = appState.zoneCode!; + text = appState.shortZoneCode!; } else if (appState.inZone == false) { icon = Icons.flight; color = Colors.orange; @@ -1284,13 +1309,13 @@ class _HomeScreenState extends State { ), const Divider(height: 24), - // External Antenna + // Antenna _buildHelpItem( icon: Icons.settings_input_antenna, color: Colors.orange, - title: 'External Antenna', + title: 'Antenna', description: - 'Enable if using an external antenna (ex: mag mount on roof of car). We store this along with pings as external antennas can make a big difference in reception.', + 'Choose External when the antenna isn\'t enclosed by metal or anything that blocks radio, for example a roof mount, a handheld, or the radio in your pocket while walking. Choose Internal when it\'s inside a car cabin, a metal box or another enclosure. We store this with every ping because it makes a big difference to reception.', ), // Send Ping button @@ -1389,12 +1414,6 @@ class _HomeScreenState extends State { ); } - /// Build subtitle with device name only - /// Uses displayDeviceName which prefers SelfInfo name over BLE advertisement name - String _buildSubtitle(AppStateProvider appState) { - return appState.displayDeviceName ?? 'Unknown'; - } - /// Build compact stat indicator for app bar Widget _buildStatIndicator({ required IconData icon, diff --git a/lib/screens/log_screen.dart b/lib/screens/log_screen.dart index 3f1ba8ae..e86bbfb0 100644 --- a/lib/screens/log_screen.dart +++ b/lib/screens/log_screen.dart @@ -4,6 +4,7 @@ import 'package:provider/provider.dart'; import '../models/log_entry.dart'; import '../models/repeater.dart'; +import '../models/scope_log_entry.dart'; import '../providers/app_state_provider.dart'; import '../utils/ping_colors.dart'; import '../widgets/log_table_cell_fit.dart'; @@ -12,7 +13,10 @@ import '../widgets/rx_path_chain.dart'; /// Log screen with two tabs: All Pings (unified TX+RX+DISC+TRC) and Errors class LogScreen extends StatefulWidget { - const LogScreen({super.key}); + /// True while the Log tab is the one on screen. + final bool active; + + const LogScreen({super.key, this.active = false}); @override State createState() => _LogScreenState(); @@ -27,14 +31,35 @@ class _LogScreenState extends State void initState() { super.initState(); _tabController = TabController(length: 2, vsync: this); + _tabController.addListener(_reportErrorTabOnScreen); + _reportErrorTabOnScreen(); + } + + @override + void didUpdateWidget(LogScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.active != widget.active) _reportErrorTabOnScreen(); } @override void dispose() { + _tabController.removeListener(_reportErrorTabOnScreen); _tabController.dispose(); super.dispose(); } + /// Tells the provider whether the Errors tab is on screen, which is what + /// clears the Log tab's dot. After the frame, because the scaffold's tab + /// change reaches here during a build. + void _reportErrorTabOnScreen() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context + .read() + .setErrorLogOnScreen(widget.active && _tabController.index == 1); + }); + } + @override Widget build(BuildContext context) { final appState = context.watch(); @@ -53,7 +78,8 @@ class _LogScreenState extends State final totalPings = appState.txLogEntries.length + appState.rxLogEntries.length + appState.discLogEntries.length + - appState.traceLogEntries.length; + appState.traceLogEntries.length + + appState.scopeLogEntries.length; final errorCount = appState.errorLogEntries.length; @@ -97,7 +123,7 @@ class _LogScreenState extends State body: TabBarView( controller: _tabController, children: [ - _AllPingsTab( + AllPingsTab( key: _allPingsKey, allEntries: appState.unifiedPingLogEntries, repeaters: appState.repeaters, @@ -105,6 +131,7 @@ class _LogScreenState extends State rxCount: appState.rxLogEntries.length, discCount: appState.discLogEntries.length, traceCount: appState.traceLogEntries.length, + scopeCount: appState.scopeLogEntries.length, ), _ErrorLogTab(entries: appState.errorLogEntries), ], @@ -153,8 +180,13 @@ class _LogScreenState extends State final rx = appState.rxLogEntries; final disc = appState.discLogEntries; final trace = appState.traceLogEntries; + final scopes = appState.scopeLogEntries; - if (tx.isEmpty && rx.isEmpty && disc.isEmpty && trace.isEmpty) { + if (tx.isEmpty && + rx.isEmpty && + disc.isEmpty && + trace.isEmpty && + scopes.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('No ping log entries to copy'), @@ -163,47 +195,9 @@ class _LogScreenState extends State return; } - final buffer = StringBuffer(); - - if (tx.isNotEmpty) { - buffer.writeln('--- TX Log ---'); - buffer.writeln('timestamp,latitude,longitude,power,events'); - for (final entry in tx) { - buffer.writeln(entry.toCsv()); - } - buffer.writeln(); - } - - if (rx.isNotEmpty) { - buffer.writeln('--- RX Log ---'); - buffer.writeln( - 'timestamp,repeater_id,snr,rssi,path_length,header,latitude,longitude,path_hops'); - for (final entry in rx) { - buffer.writeln(entry.toCsv()); - } - buffer.writeln(); - } - - if (disc.isNotEmpty) { - buffer.writeln('--- DISC Log ---'); - buffer - .writeln('timestamp,latitude,longitude,noisefloor,node_count,nodes'); - for (final entry in disc) { - buffer.writeln(entry.toCsv()); - } - buffer.writeln(); - } - - if (trace.isNotEmpty) { - buffer.writeln('--- TRC Log ---'); - buffer.writeln( - 'timestamp,target_repeater,local_snr,local_rssi,remote_snr,latitude,longitude,noisefloor,success'); - for (final entry in trace) { - buffer.writeln(entry.toCsv()); - } - } - - Clipboard.setData(ClipboardData(text: buffer.toString())); + final csv = buildAllPingsCsv( + tx: tx, rx: rx, disc: disc, trace: trace, scopes: scopes); + Clipboard.setData(ClipboardData(text: csv)); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('All ping logs copied to clipboard'), @@ -239,8 +233,8 @@ class _LogScreenState extends State context: context, builder: (context) => AlertDialog( title: const Text('Clear All Logs?'), - content: - const Text('This will clear TX, RX, DISC, TRC, and error logs.'), + content: const Text( + 'This will clear TX, RX, DISC, TRC, SCP, and error logs.'), actions: [ TextButton( onPressed: () => Navigator.pop(context), @@ -263,15 +257,24 @@ class _LogScreenState extends State // All Pings Tab — unified chronological view with type filters // ============================================================================= -class _AllPingsTab extends StatefulWidget { +/// The unified TX/RX/DISC/TRC/SCP list, its type filters and its search +/// field. Public (unlike its sibling `_ErrorLogTab`) so a test can pump it +/// directly with a fixed `allEntries`/`repeaters`/counts, without going +/// through `LogScreen` (which needs a live `AppStateProvider` just to reach +/// this widget). Per-type card rendering may still need a `Provider` +/// ancestor for its tap-to-map action (see `_buildScopeCard`'s lazy read), so +/// a test that only ever taps the filter row or the search field, and never a +/// card body, needs no provider at all. +class AllPingsTab extends StatefulWidget { final List allEntries; final List repeaters; final int txCount; final int rxCount; final int discCount; final int traceCount; + final int scopeCount; - const _AllPingsTab({ + const AllPingsTab({ super.key, required this.allEntries, required this.repeaters, @@ -279,29 +282,36 @@ class _AllPingsTab extends StatefulWidget { required this.rxCount, required this.discCount, required this.traceCount, + required this.scopeCount, }); @override - State<_AllPingsTab> createState() => _AllPingsTabState(); + State createState() => _AllPingsTabState(); } -class _AllPingsTabState extends State<_AllPingsTab> { +class _AllPingsTabState extends State { final Set _activeFilters = { PingLogType.tx, PingLogType.rx, PingLogType.disc, PingLogType.trace, + PingLogType.scopes, }; String _searchQuery = ''; final TextEditingController _searchController = TextEditingController(); + /// Its own controller, not the inherited primary one: both log tabs sit in + /// one TabBarView and would share it, which a Scrollbar refuses. + final ScrollController _scrollController = ScrollController(); + /// Current filtered entries (used by CSV export) List _filteredEntries = []; @override void dispose() { _searchController.dispose(); + _scrollController.dispose(); super.dispose(); } @@ -389,6 +399,8 @@ class _AllPingsTabState extends State<_AllPingsTab> { final resolved = _resolveRepeaterNames(trace.targetRepeaterId, repeaters); return resolved.names.any((n) => n.toLowerCase().contains(query)); + case PingLogType.scopes: + return scopeEntryMatchesSearch(entry.asScopes, _searchQuery); } } @@ -409,13 +421,14 @@ class _AllPingsTabState extends State<_AllPingsTab> { .any((n) => _isAmbiguousId(n.repeaterId, repeaters)); case PingLogType.trace: return _isAmbiguousId(entry.asTrace.targetRepeaterId, repeaters); + case PingLogType.scopes: + return false; } } @override Widget build(BuildContext context) { - final filtered = widget.allEntries - .where((e) => _activeFilters.contains(e.type)) + final filtered = filterUnifiedPingLog(widget.allEntries, _activeFilters) .where((e) => _matchesSearch(e, widget.repeaters)) .toList(); _filteredEntries = filtered; @@ -498,7 +511,11 @@ class _AllPingsTabState extends State<_AllPingsTab> { widget.discCount, PingColors.discSuccess), _segmentDivider(context), _buildFilterSegment(PingLogType.trace, 'TRC', - widget.traceCount, PingColors.traceSuccess, + widget.traceCount, PingColors.traceSuccess), + _segmentDivider(context), + _buildFilterSegment(PingLogType.scopes, 'SCP', + widget.scopeCount, + PingColors.scopesFor(Theme.of(context).brightness), isLast: true), ], ), @@ -529,26 +546,34 @@ class _AllPingsTabState extends State<_AllPingsTab> { ], ), ) - : ListView.builder( - padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), - itemCount: filtered.length, - itemBuilder: (context, index) { - final unified = filtered[index]; - final showAmbiguity = - _shouldShowAmbiguity(unified, widget.repeaters); - return switch (unified.type) { - PingLogType.tx => _buildTxCard(context, unified.asTx, - showAmbiguity: showAmbiguity), - PingLogType.rx => _buildRxCard(context, unified.asRx, - showAmbiguity: showAmbiguity), - PingLogType.disc => _buildDiscCard( - context, unified.asDisc, - showAmbiguity: showAmbiguity), - PingLogType.trace => _buildTraceCard( - context, unified.asTrace, - showAmbiguity: showAmbiguity), - }; - }, + : Scrollbar( + controller: _scrollController, + interactive: true, + child: ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), + itemCount: filtered.length, + itemBuilder: (context, index) { + final unified = filtered[index]; + final showAmbiguity = + _shouldShowAmbiguity(unified, widget.repeaters); + return switch (unified.type) { + PingLogType.tx => _buildTxCard(context, unified.asTx, + showAmbiguity: showAmbiguity), + PingLogType.rx => _buildRxCard(context, unified.asRx, + showAmbiguity: showAmbiguity), + PingLogType.disc => _buildDiscCard( + context, unified.asDisc, + showAmbiguity: showAmbiguity), + PingLogType.trace => _buildTraceCard( + context, unified.asTrace, + showAmbiguity: showAmbiguity), + PingLogType.scopes => _buildScopeCard( + context, unified.asScopes, + showAmbiguity: showAmbiguity), + }; + }, + ), ), ), ], @@ -558,61 +583,15 @@ class _AllPingsTabState extends State<_AllPingsTab> { Widget _buildFilterSegment( PingLogType type, String label, int count, Color color, {bool isFirst = false, bool isLast = false}) { - final active = _activeFilters.contains(type); - return Expanded( - child: GestureDetector( - onTap: () => _toggleFilter(type), - child: Container( - padding: const EdgeInsets.symmetric(vertical: 7), - color: active ? color.withValues(alpha: 0.12) : Colors.transparent, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - label, - style: TextStyle( - fontSize: 13, - fontWeight: active ? FontWeight.w600 : FontWeight.w500, - color: active - ? color - : Theme.of(context) - .colorScheme - .onSurfaceVariant - .withValues(alpha: 0.6), - ), - ), - if (count > 0) ...[ - const SizedBox(width: 4), - Container( - constraints: - const BoxConstraints(minWidth: 18, minHeight: 16), - padding: - const EdgeInsets.symmetric(horizontal: 5, vertical: 2), - decoration: BoxDecoration( - color: active - ? color - : Theme.of(context) - .colorScheme - .onSurfaceVariant - .withValues(alpha: 0.3), - borderRadius: BorderRadius.circular(8), - ), - alignment: Alignment.center, - child: Text( - count > 99 ? '99+' : count.toString(), - style: const TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: Colors.white, - height: 1.0, - ), - ), - ), - ], - ], - ), - ), - ), + return LogFilterSegment( + type: type, + label: label, + count: count, + color: color, + active: _activeFilters.contains(type), + onTap: () => _toggleFilter(type), + isFirst: isFirst, + isLast: isLast, ); } @@ -628,12 +607,13 @@ class _AllPingsTabState extends State<_AllPingsTab> { // Type badge // --------------------------------------------------------------------------- - static Widget _buildTypeBadge(PingLogType type) { + static Widget _buildTypeBadge(PingLogType type, Brightness brightness) { final (label, color) = switch (type) { PingLogType.tx => ('TX', PingColors.txSuccess), PingLogType.rx => ('RX', PingColors.rx), PingLogType.disc => ('DISC', PingColors.discSuccess), PingLogType.trace => ('TRC', PingColors.traceSuccess), + PingLogType.scopes => ('SCP', PingColors.scopesFor(brightness)), }; return Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), @@ -1328,6 +1308,25 @@ class _AllPingsTabState extends State<_AllPingsTab> { ); } + // --------------------------------------------------------------------------- + // SCP Card + // --------------------------------------------------------------------------- + + // The AppStateProvider read is deferred into the onTap closure (unlike the + // other card builders' eager `context.read` at the top of the method) so a + // widget test that renders only scope entries and never taps a card body + // needs no Provider ancestor at all. + Widget _buildScopeCard(BuildContext context, ScopeLogEntry entry, + {bool showAmbiguity = false}) { + return ScopeLogCard( + entry: entry, + showAmbiguity: showAmbiguity, + onTap: () => context + .read() + .navigateToMapCoordinates(entry.latitude, entry.longitude), + ); + } + // --------------------------------------------------------------------------- // Shared helpers // --------------------------------------------------------------------------- @@ -1337,7 +1336,7 @@ class _AllPingsTabState extends State<_AllPingsTab> { {bool showAmbiguity = false}) { return Row( children: [ - _buildTypeBadge(type), + _buildTypeBadge(type, Theme.of(context).brightness), if (showAmbiguity) ...[ const SizedBox(width: 2), Tooltip( @@ -1407,17 +1406,291 @@ class _AllPingsTabState extends State<_AllPingsTab> { } } +// ============================================================================= +// Filter/search helpers usable without a live AppStateProvider +// ============================================================================= + +/// The entries in [entries] whose type is in [activeFilters], in the same +/// order. What toggling a segment on the filter row does to the list. +List filterUnifiedPingLog( + List entries, Set activeFilters) => + entries.where((e) => activeFilters.contains(e.type)).toList(); + +/// Whether a logged scope request matches [query]: the repeater id and the +/// outcome words case-insensitively, a scope name case-sensitively (scope +/// names are case-sensitive on the mesh). An empty query always matches. +bool scopeEntryMatchesSearch(ScopeLogEntry entry, String query) { + if (query.isEmpty) return true; + final lower = query.toLowerCase(); + if (entry.repeaterId.toLowerCase().startsWith(lower)) return true; + if ((entry.scopes ?? const []).any((name) => name.contains(query))) { + return true; + } + return entry.outcome.label.toLowerCase().contains(lower); +} + +/// Assembles the full "Copy CSV" export (the unfiltered path taken when no +/// search is active): one `--- X Log ---` section per non-empty list, +/// blank-line separated. TX/RX/DISC/TRC rows are the bare `LogEntry.toCsv()` +/// (the section header already names the type); SCP rows carry the `SCOPES,` +/// prefix so they read identically to what the searched/filtered export +/// produces through `UnifiedPingLogEntry.toCsv()` for the same entry. Pure +/// and Provider-free so the export format is unit-testable without a live +/// AppStateProvider. +String buildAllPingsCsv({ + required List tx, + required List rx, + required List disc, + required List trace, + required List scopes, +}) { + final buffer = StringBuffer(); + + if (tx.isNotEmpty) { + buffer.writeln('--- TX Log ---'); + buffer.writeln('timestamp,latitude,longitude,power,events'); + for (final entry in tx) { + buffer.writeln(entry.toCsv()); + } + buffer.writeln(); + } + + if (rx.isNotEmpty) { + buffer.writeln('--- RX Log ---'); + buffer.writeln( + 'timestamp,repeater_id,snr,rssi,path_length,header,latitude,longitude,path_hops'); + for (final entry in rx) { + buffer.writeln(entry.toCsv()); + } + buffer.writeln(); + } + + if (disc.isNotEmpty) { + buffer.writeln('--- DISC Log ---'); + buffer.writeln('timestamp,latitude,longitude,noisefloor,node_count,nodes'); + for (final entry in disc) { + buffer.writeln(entry.toCsv()); + } + buffer.writeln(); + } + + if (trace.isNotEmpty) { + buffer.writeln('--- TRC Log ---'); + buffer.writeln( + 'timestamp,target_repeater,local_snr,local_rssi,remote_snr,latitude,longitude,noisefloor,success'); + for (final entry in trace) { + buffer.writeln(entry.toCsv()); + } + buffer.writeln(); + } + + if (scopes.isNotEmpty) { + buffer.writeln('--- SCP Log ---'); + buffer.writeln( + 'type,timestamp,latitude,longitude,repeater_id,outcome,scopes'); + for (final entry in scopes) { + buffer.writeln('SCOPES,${entry.toCsv()}'); + } + } + + return buffer.toString(); +} + +// ============================================================================= +// SCP filter segment and card, Provider-free +// ============================================================================= + +/// One segment of the TX/RX/DISC/TRC/SCP filter row. Presentational only: +/// [active] and [onTap] are owned by `_AllPingsTabState`, so this renders (and +/// is testable) without a live `AppStateProvider`. +class LogFilterSegment extends StatelessWidget { + final PingLogType type; + final String label; + final int count; + final Color color; + final bool active; + final VoidCallback onTap; + final bool isFirst; + final bool isLast; + + const LogFilterSegment({ + super.key, + required this.type, + required this.label, + required this.count, + required this.color, + required this.active, + required this.onTap, + this.isFirst = false, + this.isLast = false, + }); + + @override + Widget build(BuildContext context) { + return Expanded( + child: GestureDetector( + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 7), + color: active ? color.withValues(alpha: 0.12) : Colors.transparent, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + label, + style: TextStyle( + fontSize: 13, + fontWeight: active ? FontWeight.w600 : FontWeight.w500, + color: active + ? color + : Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.6), + ), + ), + if (count > 0) ...[ + const SizedBox(width: 4), + Container( + constraints: + const BoxConstraints(minWidth: 18, minHeight: 16), + padding: + const EdgeInsets.symmetric(horizontal: 5, vertical: 2), + decoration: BoxDecoration( + color: active + ? color + : Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.3), + borderRadius: BorderRadius.circular(8), + ), + alignment: Alignment.center, + child: Text( + count > 99 ? '99+' : count.toString(), + style: const TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: Colors.white, + height: 1.0, + ), + ), + ), + ], + ], + ), + ), + ), + ); + } +} + +/// The SCP card for one logged scope request. Provider-free (unlike the other +/// per-type card builders, which are private methods on `_AllPingsTabState` +/// that read `context.read()` themselves): the whole-card +/// tap is handed in as [onTap] so this renders in a widget test without a +/// live `AppStateProvider`. `_AllPingsTabState._buildScopeCard` supplies the +/// same `navigateToMapCoordinates` tap every other card uses. +class ScopeLogCard extends StatelessWidget { + final ScopeLogEntry entry; + final bool showAmbiguity; + final VoidCallback onTap; + + const ScopeLogCard({ + super.key, + required this.entry, + this.showAmbiguity = false, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final scopes = entry.scopes; + final colorScheme = Theme.of(context).colorScheme; + return Card( + margin: const EdgeInsets.only(bottom: 8), + color: colorScheme.surfaceContainerHigh, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _AllPingsTabState._buildCardHeader(context, PingLogType.scopes, + entry.timeString, entry.locationString, + showAmbiguity: showAmbiguity), + const SizedBox(height: 10), + InkWell( + onTap: () => RepeaterIdChip.showRepeaterPopup( + context, entry.repeaterId, + fullHexId: entry.pubkeyHex), + child: + RepeaterIdChip(repeaterId: entry.repeaterId, fontSize: 14), + ), + const SizedBox(height: 8), + Text( + entry.outcome.label, + style: TextStyle( + fontSize: 12, + color: colorScheme.onSurfaceVariant, + ), + ), + if (scopes != null) ...[ + const SizedBox(height: 8), + if (scopes.isEmpty) + Text( + 'Carries no scopes', + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: colorScheme.onSurfaceVariant, + ), + ) + else + Wrap( + spacing: 6, + runSpacing: 6, + children: scopes + .map((name) => _AllPingsTabState._buildChip(name, + PingColors.scopesFor(Theme.of(context).brightness))) + .toList(), + ), + ], + ], + ), + ), + ), + ); + } +} + // ============================================================================= // Error Log Tab (unchanged) // ============================================================================= -class _ErrorLogTab extends StatelessWidget { +class _ErrorLogTab extends StatefulWidget { final List entries; const _ErrorLogTab({required this.entries}); + @override + State<_ErrorLogTab> createState() => _ErrorLogTabState(); +} + +class _ErrorLogTabState extends State<_ErrorLogTab> { + /// See [_AllPingsTabState._scrollController]. + final ScrollController _scrollController = ScrollController(); + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { + final entries = widget.entries; if (entries.isEmpty) { return Center( child: Column( @@ -1434,14 +1707,19 @@ class _ErrorLogTab extends StatelessWidget { ); } - return ListView.builder( - padding: const EdgeInsets.all(16), - itemCount: entries.length, - itemBuilder: (context, index) { - // Most recent first - final entry = entries[entries.length - 1 - index]; - return _buildErrorEntry(context, entry); - }, + return Scrollbar( + controller: _scrollController, + interactive: true, + child: ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(16), + itemCount: entries.length, + itemBuilder: (context, index) { + // Most recent first + final entry = entries[entries.length - 1 - index]; + return _buildErrorEntry(context, entry); + }, + ), ); } diff --git a/lib/screens/main_scaffold.dart b/lib/screens/main_scaffold.dart index 518edfdd..49df602e 100644 --- a/lib/screens/main_scaffold.dart +++ b/lib/screens/main_scaffold.dart @@ -6,10 +6,13 @@ import 'package:geolocator/geolocator.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; +import '../debug/store_capture.dart'; import '../models/connection_state.dart'; import '../providers/app_state_provider.dart'; +import '../services/location_consent.dart'; import '../services/permission_disclosure_service.dart'; import '../services/portal_account_service.dart'; +import '../services/precise_location_gate.dart'; import '../utils/debug_logger_io.dart'; import '../widgets/app_toast.dart'; import 'home_screen.dart'; @@ -31,29 +34,45 @@ class MainScaffold extends StatefulWidget { class _MainScaffoldState extends State { int _selectedIndex = 0; bool _hasCheckedDisclosure = false; - bool _hasShownLocationSettingsPrompt = false; bool _carpeaterPromptOpen = false; bool _carpeaterNoticeOpen = false; bool _linkPromptDialogOpen = false; + bool _preciseLocationDialogOpen = false; + AppStateProvider? _appStateForUpgrade; bool _signInErrorToastOpen = false; final _onboardingGate = OnboardingPromptGate(); final _onboardingGuidePresenter = OnboardingGuidePresenter(); bool _startupPromptsSettled = false; bool _onboardingGuideOpen = false; - final List _screens = [ - const HomeScreen(), - const LogScreen(), - const GraphScreen(), - const ConnectionScreen(), - const SettingsScreen(), - ]; + /// Debug-only store capture mode: opens on a chosen tab and skips the + /// startup prompts so screenshots show the screen, not a dialog. + bool get _capturing => kDebugMode && StoreCaptureConfig.active != null; + + // Built per frame so the Log screen knows when it is the tab on screen: + // the IndexedStack keeps every tab alive, so being built says nothing. + List get _screens => [ + const HomeScreen(), + LogScreen(active: _selectedIndex == 1), + const GraphScreen(), + const ConnectionScreen(), + const SettingsScreen(), + ]; @override void initState() { super.initState(); + if (kDebugMode && StoreCaptureConfig.active != null) { + _selectedIndex = StoreCaptureConfig.active!.screen.tabIndex; + } _onboardingGuidePresenter.coordinator .addListener(_onOnboardingReservationChanged); + // Android's Precise Location upgrade at Connect goes through the same + // disclosure as every other location prompt, which needs this context. + if (!kIsWeb && Platform.isAndroid) { + _appStateForUpgrade = context.read() + ..preciseLocationUpgradeRequester = _requestPreciseLocationUpgrade; + } // Check disclosure after first frame (needs context) WidgetsBinding.instance.addPostFrameCallback((_) { _checkAndShowDisclosure(); @@ -62,6 +81,7 @@ class _MainScaffoldState extends State { @override void dispose() { + _appStateForUpgrade?.preciseLocationUpgradeRequester = null; _onboardingGuidePresenter.coordinator .removeListener(_onOnboardingReservationChanged); super.dispose(); @@ -71,7 +91,8 @@ class _MainScaffoldState extends State { if (mounted) setState(() {}); } - /// Check if location disclosure has been shown, show it if not, then request permissions + /// Ensure location permission at startup. The disclosure comes up inside + /// [_ensureLocationPermission]. Future _checkAndShowDisclosure() async { if (_hasCheckedDisclosure) return; _hasCheckedDisclosure = true; @@ -86,16 +107,7 @@ class _MainScaffoldState extends State { return; } - // Check if disclosure was already shown - final hasShown = await PermissionDisclosureService.hasShownDisclosure(); - if (!hasShown) { - // Show the disclosure dialog - if (!mounted) return; - debugLog('[DISCLOSURE] Showing location disclosure dialog'); - await PermissionDisclosureService.showLocationDisclosure(context); - } - - debugLog('[DISCLOSURE] Ensuring location permission after disclosure'); + debugLog('[DISCLOSURE] Ensuring location permission'); await _ensureLocationPermission(); } finally { if (mounted) { @@ -140,34 +152,74 @@ class _MainScaffoldState extends State { } } - /// Ensure location permission after disclosure has been shown. - /// Requests when possible, restarts GPS when granted, and surfaces a settings CTA - /// when the permission has been permanently denied. + /// Show the location disclosure. False means Not Now: skip the request and + /// leave GPS off. + Future _discloseLocation() async { + if (_capturing) { + await LocationConsent.markAgreed(); + return true; + } + if (!mounted) return false; + debugLog('[DISCLOSURE] Showing location disclosure dialog'); + final agreed = await PermissionDisclosureService.showLocationDisclosure( + context, + ); + if (!agreed) debugLog('[DISCLOSURE] Location disclosure declined'); + return agreed; + } + + /// Ensure location permission. Shows the disclosure until it is agreed to + /// and again before every system prompt (Google Play), requests when the + /// prompt can still appear, restarts GPS when granted, and surfaces a + /// settings CTA when the permission has been permanently denied. Future _ensureLocationPermission() async { bool granted = false; + // Until it is agreed to, the disclosure comes up even when location is + // already granted: review devices can install with it granted. + var disclosed = false; + if (!await LocationConsent.hasAgreed()) { + if (!await _discloseLocation()) return; + disclosed = true; + } + if (Platform.isIOS) { // iOS: Request location via Geolocator LocationPermission permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { + if (!disclosed && !await _discloseLocation()) return; permission = await Geolocator.requestPermission(); } debugLog('[DISCLOSURE] iOS location permission: $permission'); - if (permission == LocationPermission.deniedForever) { - _showLocationSettingsPrompt(); - return; - } + // Denied for good: the Connect tab says so and offers the settings. + if (permission == LocationPermission.deniedForever) return; granted = permission == LocationPermission.always || permission == LocationPermission.whileInUse; } else { // Android: only request if needed so previously granted permission just restarts GPS. var status = await Permission.locationWhenInUse.status; + var deniedSilently = false; if (status.isDenied) { + if (!disclosed && !await _discloseLocation()) return; + final stopwatch = Stopwatch()..start(); status = await Permission.locationWhenInUse.request(); + stopwatch.stop(); + // Android stops showing the dialog after two refusals but can still + // report plain `denied`, answered in a few milliseconds. Treat that + // like a permanent denial so the user is offered the settings. + deniedSilently = status.isDenied && + PermissionDisclosureService.deniedWithoutDialog(stopwatch.elapsed); + debugLog('[DISCLOSURE] Android location request took ' + '${stopwatch.elapsedMilliseconds}ms'); } debugLog('[DISCLOSURE] Android location permission: $status'); - if (status.isPermanentlyDenied) { - _showLocationSettingsPrompt(); + if (status.isPermanentlyDenied || deniedSilently) { + if (deniedSilently) { + debugLog('[DISCLOSURE] Location denied without a system dialog, ' + 'offering app settings'); + } + // Denied for good, or approximate only once the precise upgrade + // was refused: the Connect tab says so and offers the settings. return; } granted = status.isGranted; @@ -181,6 +233,52 @@ class _MainScaffoldState extends State { } } + /// Android: re-request fine location while only approximate is granted, + /// after the usual disclosure (Google Play wants it before every system + /// location prompt). Android 12+ answers with its "precise" upgrade dialog. + /// True when the request was made. Starts no GPS. + Future _requestPreciseLocationUpgrade() async { + if (!mounted) return false; + final status = await Permission.locationWhenInUse.status; + if (status.isPermanentlyDenied) { + debugLog('[GPS] Fine location permanently denied, no re-request'); + return false; + } + if (!await _discloseLocation()) return false; + final result = await Permission.locationWhenInUse.request(); + debugLog('[GPS] Fine location re-request returned $result'); + return true; + } + + /// Explains a connect refused for approximate location. + void _showPreciseLocationDialog() { + debugLog('[GPS] Showing the Precise Location needed dialog'); + showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text(preciseLocationDialogTitle), + content: const Text(preciseLocationDialogBody), + actions: [ + TextButton( + onPressed: () { + debugLog('[GPS] Precise Location dialog: cancelled'); + Navigator.pop(dialogContext); + }, + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + debugLog('[GPS] Precise Location dialog: opening app settings'); + Navigator.pop(dialogContext); + Geolocator.openAppSettings(); + }, + child: const Text('Open settings'), + ), + ], + ), + ); + } + /// One-tap offer to bind the connected radio to the signed-in account. /// /// Mirrors the flood-disabled alert: a postFrameCallback plus a local @@ -202,7 +300,9 @@ class _MainScaffoldState extends State { title: const Text('Link This Device?'), content: Text( "Link '$deviceName' to your MeshMapper account ($accountName)? " - 'Wardriving data from this device will count toward your account.', + 'Wardriving data from this device will count toward your account. ' + 'Its points move onto your account the next time the leaderboard ' + 'updates, which can take up to 24 hours.', ), actions: [ TextButton( @@ -237,11 +337,14 @@ class _MainScaffoldState extends State { switch (outcome.status) { case PortalLinkStatus.linked: final account = outcome.accountName ?? 'your MeshMapper account'; + final linked = outcome.adoptedCount > 1 + ? 'Linked to $account and claimed ${outcome.adoptedCount} radios' + : 'Linked to $account'; AppToast.success( context, - outcome.adoptedCount > 1 - ? 'Linked to $account and claimed ${outcome.adoptedCount} radios' - : 'Linked to $account', + '$linked. Points move over at the next leaderboard update, within ' + '24 hours.', + duration: const Duration(seconds: 6), ); case PortalLinkStatus.adoptionRequired: await showDialog( @@ -288,21 +391,6 @@ class _MainScaffoldState extends State { } } - void _showLocationSettingsPrompt() { - if (!mounted || _hasShownLocationSettingsPrompt) return; - _hasShownLocationSettingsPrompt = true; - - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Location permission is disabled in system settings.'), - action: SnackBarAction( - label: 'Settings', - onPressed: Geolocator.openAppSettings, - ), - ), - ); - } - /// Report a failed sign-in. /// /// The codes are the bounded set `PortalAccountService` emits (the portal's @@ -375,7 +463,7 @@ class _MainScaffoldState extends State { final onboardingModalLaneReserved = _onboardingGate.reservesModalLane( isMobile: !kIsWeb, stateLoaded: appState.onboardingGuideStateLoaded, - isDue: appState.shouldShowOnboardingGuide, + isDue: appState.shouldShowOnboardingGuide && !_capturing, ); final onboardingPresentationReserved = _onboardingGuidePresenter.coordinator.isReserved; @@ -409,7 +497,7 @@ class _MainScaffoldState extends State { isMobile: !kIsWeb, startupPromptsSettled: _startupPromptsSettled, stateLoaded: appState.onboardingGuideStateLoaded, - isDue: appState.shouldShowOnboardingGuide, + isDue: appState.shouldShowOnboardingGuide && !_capturing, )) { _onboardingGate.markScheduled(); _onboardingGuideOpen = true; @@ -460,6 +548,24 @@ class _MainScaffoldState extends State { }); } + // A connect refused for approximate location is explained here, whichever + // tab the tap came from (the Connection screen, the remembered companion, + // Siri). + if (appState.preciseLocationPromptDue && + !onboardingModalLaneReserved && + !onboardingPresentationReserved && + !_onboardingGuideOpen && + !_preciseLocationDialogOpen) { + _preciseLocationDialogOpen = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _preciseLocationDialogOpen = false; + if (!mounted) return; + if (!appState.preciseLocationPromptDue) return; + appState.acknowledgePreciseLocationPrompt(); + _showPreciseLocationDialog(); + }); + } + // The CARpeater re-entry prompt is raised by the provider at the end of a // connect and shown here, whichever tab the user is on. if (appState.carpeaterReentryPromptDue && @@ -622,7 +728,7 @@ class _MainScaffoldState extends State { icon: Icons.list_alt_outlined, activeIcon: Icons.list_alt, index: 1, - showBadge: appState.errorLogEntries.isNotEmpty, + showBadge: appState.hasUnseenErrors, ), _buildCompactNavItem( icon: Icons.history_outlined, @@ -706,11 +812,11 @@ class _MainScaffoldState extends State { ), BottomNavigationBarItem( icon: Badge( - isLabelVisible: appState.errorLogEntries.isNotEmpty, + isLabelVisible: appState.hasUnseenErrors, child: const Icon(Icons.list_alt_outlined), ), activeIcon: Badge( - isLabelVisible: appState.errorLogEntries.isNotEmpty, + isLabelVisible: appState.hasUnseenErrors, child: const Icon(Icons.list_alt), ), label: 'Log', diff --git a/lib/screens/onboarding/onboarding_guide_pages.dart b/lib/screens/onboarding/onboarding_guide_pages.dart index 64de66e5..3e185357 100644 --- a/lib/screens/onboarding/onboarding_guide_pages.dart +++ b/lib/screens/onboarding/onboarding_guide_pages.dart @@ -472,11 +472,11 @@ Widget buildAntennaPage(BuildContext context) { accent: accent, children: [ GuideParagraph( - 'Set the required External Antenna: Yes / No control on the Map screen for the setup used on that drive.', + 'Set the required Antenna: Internal / External control on the Map screen for the setup used on that drive.', ), GuideComparison( left: _CompactCard( - title: 'Choose No', + title: 'Choose Internal', icon: Icons.directions_car, color: Colors.blueGrey, child: Column( @@ -490,7 +490,7 @@ Widget buildAntennaPage(BuildContext context) { ), ), right: _CompactCard( - title: 'Choose Yes', + title: 'Choose External', icon: Icons.cell_tower, color: accent, child: Column( @@ -511,7 +511,7 @@ Widget buildAntennaPage(BuildContext context) { color: accent, ), GuideCallout( - text: 'Choose Yes or No on the Map screen before starting a mode.', + text: 'Choose Internal or External on the Map screen before starting a mode.', icon: Icons.touch_app, color: accent, ), @@ -671,7 +671,7 @@ Widget buildSmartPingingPage(BuildContext context) { icon: Icons.pending_outlined, title: 'Deferred is normal', text: - 'The app holds one ping and sends it as soon as you enter a square without recent two-way or discovery coverage.', + 'The app holds one flood ping and sends it as soon as you enter a square without recent two-way coverage. Discovery requests are not held unless you turn off Delay only flood pings.', color: Colors.orange, ), GuideIconRow( @@ -877,7 +877,7 @@ Widget buildBackgroundPage(BuildContext context) { icon: Icons.notifications_active, title: 'Android setup', text: - 'No additional background location permission is required. Allow MeshMapper notifications so you can see when the active mode keeps Bluetooth and GPS running.', + 'No additional background location permission is required. Allow MeshMapper notifications so you can see while your radio is connected and MeshMapper keeps Bluetooth and GPS running.', color: accent, ), const GuideCallout( @@ -1329,7 +1329,7 @@ Widget buildHelpPage(BuildContext context) { GuideSectionLabel('Before you start'), GuideBullet('Connect your radio and choose Online or Offline.'), GuideBullet( - 'Set External Antenna to Yes or No. Configure a CARpeater if one travels with you.'), + 'Set Antenna to Internal or External. Configure a CARpeater if one travels with you.'), GuideBullet( 'On the Map, start Passive Mode for general mapping. Tap the running mode again to stop.'), GuideSectionLabel('Need help?'), diff --git a/lib/screens/settings/about_settings_page.dart b/lib/screens/settings/about_settings_page.dart index 465d2d8c..7ff5cb41 100644 --- a/lib/screens/settings/about_settings_page.dart +++ b/lib/screens/settings/about_settings_page.dart @@ -12,6 +12,7 @@ import 'package:intl/intl.dart'; import '../../providers/app_state_provider.dart'; import '../../services/debug_file_logger.dart'; import '../../utils/constants.dart'; +import '../../utils/share_origin.dart'; import '../../widgets/app_toast.dart'; import '../../widgets/bug_report_dialog.dart'; import '../../widgets/upload_logs_dialog.dart'; @@ -157,8 +158,10 @@ class _AboutSettingsPageState extends State { subtitle: const Text('Report bugs or request features'), onTap: () => _showBugReportDialog(context, appState), ), - // Debug logs are mobile only. The web build keeps no log files. - if (!kIsWeb) ...[ + ]), + // Debug logs are mobile only. The web build keeps no log files. + if (!kIsWeb) + SettingsSectionCard(title: 'Debug Logs', children: [ SwitchListTile( secondary: Icon( Icons.bug_report, @@ -166,7 +169,7 @@ class _AboutSettingsPageState extends State { ), title: Row( children: [ - const Text('Debug Logs'), + const Text('Write logs to file'), if (appState.debugLogsEnabled) ...[ const SizedBox(width: 8), Container( @@ -242,12 +245,11 @@ class _AboutSettingsPageState extends State { ), ) else - ...appState.debugLogFiles.asMap().entries.map((entry) { - final index = entry.key; - final file = entry.value; + ...appState.debugLogFiles.map((file) { final filename = file.path.split('/').last; final sizeBytes = file.lengthSync(); - final isCurrentLog = index == 0; + final isCurrentLog = + file.path == DebugFileLogger.currentLogPath; final timestampMatch = RegExp(r'meshmapper-debug-(\d+)\.txt') .firstMatch(filename); @@ -291,18 +293,21 @@ class _AboutSettingsPageState extends State { _showLogViewer(context, appState, file), tooltip: 'View', ), - IconButton( - icon: const Icon(Icons.share, size: 20), - onPressed: () => appState.shareDebugLog(file), - tooltip: 'Share', + Builder( + builder: (buttonContext) => IconButton( + icon: const Icon(Icons.share, size: 20), + onPressed: () => appState.shareDebugLog(file, + sharePositionOrigin: + globalRectOf(buttonContext)), + tooltip: 'Share', + ), ), ], ), ); }), ], - ], - ]), + ]), ], ), ); diff --git a/lib/screens/settings/account_settings_page.dart b/lib/screens/settings/account_settings_page.dart index 3197c768..2e676b57 100644 --- a/lib/screens/settings/account_settings_page.dart +++ b/lib/screens/settings/account_settings_page.dart @@ -152,6 +152,18 @@ class _AccountSettingsPageState extends State { companion: companion, isConnected: companion.pubkey == connectedPubkey, ), + // Linked points follow the region leaderboard, which can lag up + // to 24 hours, so a fresh link looks empty for a while. + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: Text( + 'Points from a newly linked radio move onto your account ' + 'the next time the leaderboard updates, which can take up ' + 'to 24 hours.', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), if (appState.hasPortalLinkResets) ListTile( leading: const Icon(Icons.replay), @@ -234,8 +246,13 @@ class _AccountSettingsPageState extends State { if (!context.mounted) return; switch (outcome.status) { case PortalLinkStatus.linked: - AppToast.success(context, - 'Linked to ${outcome.accountName ?? 'your MeshMapper account'}'); + AppToast.success( + context, + 'Linked to ${outcome.accountName ?? 'your MeshMapper account'}. ' + 'Its points move over at the next leaderboard update, within 24 ' + 'hours.', + duration: const Duration(seconds: 6), + ); case PortalLinkStatus.adoptionRequired: AppToast.warning( context, @@ -256,6 +273,15 @@ class _AccountSettingsPageState extends State { if (wait != null) { AppToast.warning( context, 'Too many attempts. Try again in ${_waitLabel(wait)}.'); + } else if (outcome.radioCouldNotSign) { + // Waiting never helps here: some fork firmware can only sign + // again after a reboot. + AppToast.error( + context, + 'Your radio could not sign the link request. Reboot the radio ' + 'and try again.', + duration: const Duration(seconds: 6), + ); } else { AppToast.error(context, 'Could not link right now. Try again later'); } @@ -273,7 +299,12 @@ class _AccountSettingsPageState extends State { final ok = await appState.unlinkCurrentDevice(); if (!context.mounted) return; if (ok) { - AppToast.success(context, 'Device unlinked'); + AppToast.success( + context, + 'Device unlinked. Its points leave your account the next time the ' + 'leaderboard updates, which can take up to 24 hours.', + duration: const Duration(seconds: 6), + ); } else { AppToast.error(context, 'Could not unlink right now'); } diff --git a/lib/screens/settings/close_app_tile.dart b/lib/screens/settings/close_app_tile.dart new file mode 100644 index 00000000..4ef795e4 --- /dev/null +++ b/lib/screens/settings/close_app_tile.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../providers/app_state_provider.dart'; + +/// Close App row on the Settings tab (Android only; the caller gates it). +/// +/// Lives on the tab itself rather than in General so it is one tap away. +class CloseAppTile extends StatelessWidget { + const CloseAppTile({super.key}); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: const Icon(Icons.power_settings_new, color: Colors.red), + title: const Text('Close App'), + subtitle: const Text('Exit the app completely'), + onTap: () => _showCloseAppConfirmation(context), + ); + } + + void _showCloseAppConfirmation(BuildContext context) { + final appState = context.read(); + final isConnected = appState.isConnected; + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Close App'), + content: Text( + isConnected + ? 'This will disconnect from the device and close the app. Continue?' + : 'This will close the app. Continue?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () { + Navigator.pop(context); + appState.exitApp(); + }, + style: TextButton.styleFrom(foregroundColor: Colors.red), + child: const Text('Close App'), + ), + ], + ), + ); + } +} diff --git a/lib/screens/settings/data_settings_page.dart b/lib/screens/settings/data_settings_page.dart index e60ea4fe..272989b1 100644 --- a/lib/screens/settings/data_settings_page.dart +++ b/lib/screens/settings/data_settings_page.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -9,7 +7,10 @@ import '../../utils/web_file_helpers_stub.dart' if (dart.library.html) '../../utils/web_file_helpers.dart'; import '../../providers/app_state_provider.dart'; +import '../../services/offline_session_export.dart'; import '../../services/offline_session_service.dart'; +import '../../utils/debug_logger_io.dart'; +import '../../utils/share_origin.dart'; import 'settings_section_card.dart'; /// Settings folder: Data. @@ -83,9 +84,35 @@ class DataSettingsPage extends StatelessWidget { context, appState, session.filename), onDelete: () => _confirmDeleteOfflineSession( context, appState, session.filename), - onDownload: () => _downloadOfflineSession( - context, appState, session.filename), + onDownload: (origin) => _downloadOfflineSession( + context, appState, session.filename, origin), )), + // Export all: only with sessions to export (the empty state above + // says there are none). Never deletes or marks them uploaded. + if (appState.offlineSessions.isNotEmpty) + Builder( + builder: (tileContext) { + final exporting = appState.isExportingOfflineSessions; + final count = appState.offlineSessions.length; + return ListTile( + leading: const Icon(Icons.download, color: Colors.blue), + title: const Text('Export all'), + subtitle: Text(count == 1 + ? '1 session as a JSON file' + : '$count sessions as JSON files'), + trailing: exporting + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : null, + enabled: !exporting, + onTap: () => _exportAllOfflineSessions( + context, appState, globalRectOf(tileContext)), + ); + }, + ), ]), ], ), @@ -278,8 +305,8 @@ class DataSettingsPage extends StatelessWidget { ); } - Future _downloadOfflineSession( - BuildContext context, AppStateProvider appState, String filename) async { + Future _downloadOfflineSession(BuildContext context, + AppStateProvider appState, String filename, Rect? origin) async { try { final sessionData = appState.offlineSessionService.getSessionData(filename); @@ -294,8 +321,7 @@ class DataSettingsPage extends StatelessWidget { } // Convert to pretty JSON - final jsonString = - const JsonEncoder.withIndent(' ').convert(sessionData); + final jsonString = offlineSessionJson(sessionData); if (kIsWeb && isWebFileHelpersAvailable) { // Web: Create a blob and trigger download @@ -317,9 +343,11 @@ class DataSettingsPage extends StatelessWidget { } else { // Mobile: write the JSON to a temp file and open the native share // sheet (Save to Files, Drive, email, …) — mirrors the debug-log share. - await appState.shareOfflineSession(filename); + await appState.shareOfflineSession(filename, + sharePositionOrigin: origin); } } catch (e) { + debugError('[OFFLINE] Failed to download session $filename: $e'); if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( @@ -330,6 +358,47 @@ class DataSettingsPage extends StatelessWidget { } } } + + /// Export every offline session at once (#560). Mobile: one share sheet + /// with a file per session. Web: one download per session. A dismissed + /// share sheet is not an error; the sessions are kept either way. + Future _exportAllOfflineSessions( + BuildContext context, AppStateProvider appState, Rect? origin) async { + try { + if (kIsWeb && isWebFileHelpersAvailable) { + final sessions = appState.offlineSessions; + for (final session in sessions) { + downloadFileWeb( + content: offlineSessionJson(session.data), + filename: session.filename, + mimeType: 'application/json', + ); + } + debugLog('[OFFLINE] Downloaded all ${sessions.length} sessions'); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Downloaded ${sessions.length} sessions'), + duration: const Duration(seconds: 2), + backgroundColor: Colors.green, + ), + ); + } + } else { + await appState.shareAllOfflineSessions(sharePositionOrigin: origin); + } + } catch (e) { + debugError('[OFFLINE] Failed to export all sessions: $e'); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error exporting: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + } } /// Widget for displaying an offline session in the list @@ -338,7 +407,9 @@ class _OfflineSessionTile extends StatelessWidget { final bool uploadEnabled; final VoidCallback onUpload; final VoidCallback onDelete; - final VoidCallback onDownload; + + /// Called with the download button's global rect (the iPad share anchor). + final ValueChanged onDownload; const _OfflineSessionTile({ required this.session, @@ -454,11 +525,13 @@ class _OfflineSessionTile extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ // Download button - always available - IconButton( - icon: const Icon(Icons.download), - onPressed: onDownload, - tooltip: 'Download JSON', - color: Colors.blue, + Builder( + builder: (buttonContext) => IconButton( + icon: const Icon(Icons.download), + onPressed: () => onDownload(globalRectOf(buttonContext)), + tooltip: 'Download JSON', + color: Colors.blue, + ), ), // Upload button - only when not uploaded if (!isUploaded) diff --git a/lib/screens/settings/general_settings_page.dart b/lib/screens/settings/general_settings_page.dart index 2681c998..a0a12949 100644 --- a/lib/screens/settings/general_settings_page.dart +++ b/lib/screens/settings/general_settings_page.dart @@ -91,8 +91,10 @@ class GeneralSettingsPage extends StatelessWidget { ], ]), - // Background location needs an OS permission the web build cannot hold. - if (!kIsWeb) + // Only iOS has a background location permission to manage. Android + // keeps GPS running through the session service, which needs none, + // and the web build cannot hold the permission. + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.iOS) SettingsSectionCard(title: 'Location', children: [ _BackgroundModeToggle(appState: appState), ]), @@ -115,7 +117,8 @@ class GeneralSettingsPage extends StatelessWidget { ), ]), - // Exit Options (Android only) + // Exit Options (Android only). The Close App button itself sits on + // the Settings tab. if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) SettingsSectionCard(title: 'Exit', children: [ SwitchListTile( @@ -127,49 +130,11 @@ class GeneralSettingsPage extends StatelessWidget { onChanged: (value) => appState.setCloseAppAfterDisconnect(value), ), - ListTile( - leading: - const Icon(Icons.power_settings_new, color: Colors.red), - title: const Text('Close App'), - subtitle: const Text('Exit the app completely'), - onTap: () => _showCloseAppConfirmation(context, appState), - ), ]), ], ), ); } - - void _showCloseAppConfirmation( - BuildContext context, AppStateProvider appState) { - final isConnected = appState.isConnected; - - showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Close App'), - content: Text( - isConnected - ? 'This will disconnect from the device and close the app. Continue?' - : 'This will close the app. Continue?', - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - TextButton( - onPressed: () { - Navigator.pop(context); - appState.exitApp(); - }, - style: TextButton.styleFrom(foregroundColor: Colors.red), - child: const Text('Close App'), - ), - ], - ), - ); - } } /// Widget for Background Mode toggle (iOS "Always" location permission) diff --git a/lib/screens/settings/map_settings_page.dart b/lib/screens/settings/map_settings_page.dart index 7c1e524b..e7173a96 100644 --- a/lib/screens/settings/map_settings_page.dart +++ b/lib/screens/settings/map_settings_page.dart @@ -5,8 +5,11 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import '../../models/user_preferences.dart'; import '../../providers/app_state_provider.dart'; +import '../../utils/gps_marker_colors.dart'; import '../offline_maps_screen.dart'; +import 'repeater_nicknames_page.dart'; import 'settings_section_card.dart'; /// Settings folder: Map. @@ -17,6 +20,7 @@ class MapSettingsPage extends StatelessWidget { Widget build(BuildContext context) { final appState = context.watch(); final prefs = appState.preferences; + final nicknameCount = appState.repeaterNicknameCount; return Scaffold( appBar: AppBar( @@ -48,7 +52,7 @@ class MapSettingsPage extends StatelessWidget { title: const Text('Use Downloaded Tiles Only'), subtitle: Text(prefs.mapTilesEnabled ? 'Online tiles load normally' - : 'Only downloaded areas are shown · no network tile requests'), + : 'Only downloaded areas are shown. The coverage overlay is hidden.'), value: !prefs.mapTilesEnabled, onChanged: (value) { appState @@ -57,6 +61,11 @@ class MapSettingsPage extends StatelessWidget { ), ]), SettingsSectionCard(title: 'Coverage Overlay', children: [ + if (!prefs.mapTilesEnabled) + const ListTile( + leading: Icon(Icons.layers_clear), + subtitle: Text('Hidden while Use Downloaded Tiles Only is on'), + ), if (prefs.mapTilesEnabled) ListTile( leading: const Icon(Icons.opacity), @@ -90,6 +99,16 @@ class MapSettingsPage extends StatelessWidget { trailing: const Icon(Icons.chevron_right), onTap: () => _showColorVisionSelector(context, appState), ), + // Its own setter, not updatePreferences: the selected repeater's + // lines update in place, with no map rebuild. + SwitchListTile( + secondary: const Icon(Icons.hub), + title: const Text('Repeater Coverage Lines'), + subtitle: const Text( + 'Dashed lines from a selected repeater to the squares that heard it'), + value: prefs.showRepeaterCoverageLines, + onChanged: appState.setShowRepeaterCoverageLines, + ), ]), SettingsSectionCard(title: 'Markers', children: [ ListTile( @@ -106,21 +125,44 @@ class MapSettingsPage extends StatelessWidget { trailing: const Icon(Icons.chevron_right), onTap: () => _showGpsMarkerSelector(context, appState), ), + ListTile( + leading: const Icon(Icons.palette), + title: const Text('GPS Marker Color'), + subtitle: Text(_gpsMarkerColorLabel(prefs.gpsMarkerColor)), + trailing: const Icon(Icons.chevron_right), + onTap: () => _showGpsMarkerColorSelector(context, appState), + ), SwitchListTile( secondary: const Icon(Icons.cell_tower), - title: const Text('Top Repeaters on Map'), - subtitle: - const Text('Show top 3 repeaters by SNR from last ping'), + title: const Text('Top Heard on Map'), + subtitle: const Text('Strongest repeaters from the last ping'), value: prefs.showTopRepeaters, onChanged: (value) { appState .updatePreferences(prefs.copyWith(showTopRepeaters: value)); }, ), - if (prefs.showTopRepeaters) + if (prefs.showTopRepeaters) ...[ + ListTile( + leading: const Icon(Icons.format_list_numbered), + title: const Text('Top Heard Rows'), + subtitle: Text('${prefs.topHeardRows} rows'), + trailing: const Icon(Icons.chevron_right), + onTap: () => _showTopHeardRowsSelector(context, appState), + ), + SwitchListTile( + secondary: const Icon(Icons.badge_outlined), + title: const Text('Repeater Names in Top Heard'), + subtitle: const Text('Names instead of hex IDs'), + value: prefs.topHeardShowNames, + onChanged: (value) { + appState.updatePreferences( + prefs.copyWith(topHeardShowNames: value)); + }, + ), SwitchListTile( secondary: const Icon(Icons.text_increase), - title: const Text('Larger Top 3 Overlay'), + title: const Text('Larger Top Heard Overlay'), subtitle: const Text( 'Increase the size of the overlay for easier reading'), value: prefs.largerTopRepeaters, @@ -129,6 +171,25 @@ class MapSettingsPage extends StatelessWidget { prefs.copyWith(largerTopRepeaters: value)); }, ), + ], + ListTile( + leading: const Icon(Icons.label_outline), + title: const Text('Repeater Nicknames'), + subtitle: Text(nicknameCount == 0 + ? 'Your own short names for Top Heard' + : nicknameCount == 1 + ? '1 nickname' + : '$nicknameCount nicknames'), + trailing: const Icon(Icons.chevron_right), + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const RepeaterNicknamesPage(), + ), + ); + }, + ), ]), ], ), @@ -182,52 +243,82 @@ class MapSettingsPage extends StatelessWidget { shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(16)), ), + // Scrolls: a sheet is capped at 9/16 of the screen, which cuts off the + // last options on a short Android screen. Same for every picker here. builder: (context) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Padding( - padding: EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Text('Map Marker Style', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), - ), - RadioGroup( - groupValue: appState.preferences.markerStyle, - onChanged: (v) { - if (v != null) { - appState.updatePreferences( - appState.preferences.copyWith(markerStyle: v)); - } - Navigator.pop(context); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final (value, label, icon) in options) - RadioListTile( - secondary: Icon(icon), - title: Text(label), - value: value, - ), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('Map Marker Style', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ), - ), - const SizedBox(height: 8), - ], + RadioGroup( + groupValue: appState.preferences.markerStyle, + onChanged: (v) { + if (v != null) { + appState.updatePreferences( + appState.preferences.copyWith(markerStyle: v)); + } + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final (value, label, icon) in options) + RadioListTile( + secondary: Icon(icon), + title: Text(label), + value: value, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), ), ), ); } + static const _gpsMarkerStyles = [ + 'arrow', + 'car', + 'bike', + 'boat', + 'walk', + 'dog', + 'chomper', + ]; + + /// The settings icon for a GPS marker [style]. + static Widget _gpsMarkerIcon(String style) { + return switch (style) { + 'car' => const Icon(Icons.directions_car), + 'bike' => const Icon(Icons.directions_bike), + 'boat' => const Icon(Icons.directions_boat), + 'walk' => const Icon(Icons.directions_walk), + 'dog' => const FaIcon(FontAwesomeIcons.dog), + 'chomper' => const _ChomperIcon(), + _ => const Icon(Icons.navigation), + }; + } + + String _gpsMarkerColorLabel(String color) { + return switch (GpsMarkerColors.normalize(color)) { + GpsMarkerColors.greenChoice => 'Green', + _ => 'Default', + }; + } + void _showGpsMarkerSelector(BuildContext context, AppStateProvider appState) { final options = <(String, String, Widget)>[ - ('arrow', 'Arrow', const Icon(Icons.navigation)), - ('car', 'Car', const Icon(Icons.directions_car)), - ('bike', 'Bike', const Icon(Icons.directions_bike)), - ('boat', 'Boat', const Icon(Icons.directions_boat)), - ('walk', 'Walk', const Icon(Icons.directions_walk)), - ('dog', 'Dog', const FaIcon(FontAwesomeIcons.dog)), - ('chomper', 'Chomper', const _ChomperIcon()), + for (final style in _gpsMarkerStyles) + (style, _gpsMarkerLabel(style), _gpsMarkerIcon(style)), ]; showModalBottomSheet( context: context, @@ -235,37 +326,97 @@ class MapSettingsPage extends StatelessWidget { borderRadius: BorderRadius.vertical(top: Radius.circular(16)), ), builder: (context) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Padding( - padding: EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Text('GPS Marker', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), - ), - RadioGroup( - groupValue: appState.preferences.gpsMarkerStyle, - onChanged: (v) { - if (v != null) { - appState.updatePreferences( - appState.preferences.copyWith(gpsMarkerStyle: v)); - } - Navigator.pop(context); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final (value, label, icon) in options) - RadioListTile( - secondary: icon, - title: Text(label), - value: value, - ), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('GPS Marker', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ), - ), - const SizedBox(height: 8), - ], + RadioGroup( + groupValue: appState.preferences.gpsMarkerStyle, + onChanged: (v) { + if (v != null) { + appState.updatePreferences( + appState.preferences.copyWith(gpsMarkerStyle: v)); + } + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final (value, label, icon) in options) + RadioListTile( + secondary: icon, + title: Text(label), + value: value, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), + ), + ), + ); + } + + /// GPS marker colour picker. Each option shows the current marker style in + /// that colour, so the choice previews what the map will show. + void _showGpsMarkerColorSelector( + BuildContext context, AppStateProvider appState) { + final style = appState.preferences.gpsMarkerStyle; + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (context) => SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('GPS Marker Color', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + ), + RadioGroup( + groupValue: GpsMarkerColors.normalize( + appState.preferences.gpsMarkerColor), + onChanged: (v) { + if (v != null) { + appState.updatePreferences( + appState.preferences.copyWith(gpsMarkerColor: v)); + } + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final color in GpsMarkerColors.choices) + RadioListTile( + secondary: IconTheme.merge( + data: IconThemeData( + color: + GpsMarkerColors.forStyle(style, color).body, + ), + child: _gpsMarkerIcon(style), + ), + title: Text(_gpsMarkerColorLabel(color)), + value: color, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), ), ), ); @@ -281,6 +432,56 @@ class MapSettingsPage extends StatelessWidget { }; } + /// How many ping rows the in-app Top Heard box shows. The RX row is extra, + /// and the Live Activity, CarPlay and watch keep 3 ping rows. + void _showTopHeardRowsSelector( + BuildContext context, AppStateProvider appState) { + showModalBottomSheet( + context: context, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (context) => SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('Top Heard Rows', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + ), + RadioGroup( + groupValue: appState.preferences.topHeardRows, + onChanged: (v) { + if (v != null) { + appState.updatePreferences( + appState.preferences.copyWith(topHeardRows: v)); + } + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var n = UserPreferences.topHeardRowsMin; + n <= UserPreferences.topHeardRowsMax; + n++) + RadioListTile( + title: Text('$n rows'), + value: n, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), + ), + ), + ); + } + /// Grid Mode preset selector — mirrors the web UI's Grid Mode /// (Simplified = 300 m, Detailed = 100 m + blob, applied server-side). void _showCoverageGridSelector( @@ -295,39 +496,42 @@ class MapSettingsPage extends StatelessWidget { borderRadius: BorderRadius.vertical(top: Radius.circular(16)), ), builder: (context) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Padding( - padding: EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Text('Grid Mode', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), - ), - RadioGroup( - groupValue: appState.preferences.coverageGridSize, - onChanged: (v) { - if (v != null) { - appState.updatePreferences( - appState.preferences.copyWith(coverageGridSize: v)); - } - Navigator.pop(context); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final (value, label, subtitle) in options) - RadioListTile( - secondary: const Icon(Icons.grid_on), - title: Text(label), - subtitle: - Text(subtitle, style: const TextStyle(fontSize: 12)), - value: value, - ), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('Grid Mode', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ), - ), - const SizedBox(height: 8), - ], + RadioGroup( + groupValue: appState.preferences.coverageGridSize, + onChanged: (v) { + if (v != null) { + appState.updatePreferences( + appState.preferences.copyWith(coverageGridSize: v)); + } + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final (value, label, subtitle) in options) + RadioListTile( + secondary: const Icon(Icons.grid_on), + title: Text(label), + subtitle: Text(subtitle, + style: const TextStyle(fontSize: 12)), + value: value, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), ), ), ); @@ -340,22 +544,22 @@ class MapSettingsPage extends StatelessWidget { ( 'protanopia', 'Protanopia', - 'Red-blind — difficulty distinguishing red and green' + 'Red-blind: difficulty distinguishing red and green' ), ( 'deuteranopia', 'Deuteranopia', - 'Green-blind — difficulty distinguishing red and green' + 'Green-blind: difficulty distinguishing red and green' ), ( 'tritanopia', 'Tritanopia', - 'Blue-blind — difficulty distinguishing blue and yellow' + 'Blue-blind: difficulty distinguishing blue and yellow' ), ( 'achromatopsia', 'Achromatopsia', - 'Total color blindness — sees in greyscale' + 'Total color blindness, sees in greyscale' ), ]; showModalBottomSheet( @@ -364,36 +568,39 @@ class MapSettingsPage extends StatelessWidget { borderRadius: BorderRadius.vertical(top: Radius.circular(16)), ), builder: (context) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Padding( - padding: EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Text('Color Vision', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), - ), - RadioGroup( - groupValue: appState.preferences.colorVisionType, - onChanged: (v) { - if (v != null) appState.setColorVisionType(v); - Navigator.pop(context); - }, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (final (value, label, subtitle) in options) - RadioListTile( - secondary: const Icon(Icons.visibility), - title: Text(label), - subtitle: - Text(subtitle, style: const TextStyle(fontSize: 12)), - value: value, - ), - ], + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Text('Color Vision', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ), - ), - const SizedBox(height: 8), - ], + RadioGroup( + groupValue: appState.preferences.colorVisionType, + onChanged: (v) { + if (v != null) appState.setColorVisionType(v); + Navigator.pop(context); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final (value, label, subtitle) in options) + RadioListTile( + secondary: const Icon(Icons.visibility), + title: Text(label), + subtitle: Text(subtitle, + style: const TextStyle(fontSize: 12)), + value: value, + ), + ], + ), + ), + const SizedBox(height: 8), + ], + ), ), ), ); diff --git a/lib/screens/settings/repeater_nicknames_page.dart b/lib/screens/settings/repeater_nicknames_page.dart new file mode 100644 index 00000000..58742c38 --- /dev/null +++ b/lib/screens/settings/repeater_nicknames_page.dart @@ -0,0 +1,215 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../providers/app_state_provider.dart'; +import '../../utils/public_key.dart'; +import '../../utils/repeater_nicknames.dart'; +import '../../widgets/repeater_nickname_dialog.dart'; +import '../../widgets/repeater_nickname_widgets.dart'; +import '../../widgets/repeater_picker_sheet.dart'; +import 'settings_section_card.dart'; + +/// Settings > Map > Repeater Nicknames: every saved nickname, with add, edit +/// and remove. Entries may belong to repeaters outside the current zone, so +/// edits and removals go by key, not through the catalogue. +class RepeaterNicknamesPage extends StatefulWidget { + const RepeaterNicknamesPage({super.key}); + + @override + State createState() => _RepeaterNicknamesPageState(); +} + +class _RepeaterNicknamesPageState extends State { + final _removed = NicknameRemovalBatch(); + + @override + Widget build(BuildContext context) { + final entries = context.watch().repeaterNicknames; + return Scaffold( + appBar: AppBar( + toolbarHeight: 40, + title: const Text('Repeater Nicknames', style: TextStyle(fontSize: 18)), + actions: [ + IconButton( + icon: const Icon(Icons.add), + tooltip: 'Add nickname', + onPressed: _add, + ), + ], + ), + body: RepeaterNicknameList( + entries: entries, + onAdd: _add, + onEdit: _edit, + onRemove: _remove, + ), + ); + } + + Future _add() async { + final appState = context.read(); + // Only repeaters with a full key can take a nickname, so the picker + // offers no others. + final picked = await showRepeaterPicker(context, + include: (repeater) => isFullPublicKey(repeater.hexId)); + if (!mounted || picked == null) return; + await editRepeaterNickname(context, appState, picked); + } + + Future _edit(String key, RepeaterNickname entry) async { + final appState = context.read(); + final result = await showRepeaterNicknameDialog( + context, + hex: entry.hex, + serverName: entry.name, + current: entry.nickname, + ); + // The save needs no context, so a page closed under the dialog still + // keeps what was typed. + if (!nicknameResultChanges(result, entry.nickname)) return; + await appState.setRepeaterNicknameByKey(key, result); + } + + Future _remove(String key, RepeaterNickname entry) async { + final appState = context.read(); + final messenger = ScaffoldMessenger.of(context); + await appState.setRepeaterNicknameByKey(key, null); + // A removal while the last one's bar is still up joins it, so one Undo + // brings both back. Replacing the bar alone used to lose the first. + final batch = _removed..add(key, entry); + messenger.hideCurrentSnackBar(); + messenger + .showSnackBar(SnackBar( + content: Text(batch.message), + // A snack bar with an action stays up until tapped unless told not + // to; this one is a short offer, not a question. + persist: false, + action: SnackBarAction( + label: 'Undo', + onPressed: () { + for (final removed in batch.take().entries) { + appState.setRepeaterNicknameByKey( + removed.key, + removed.value.nickname, + name: removed.value.name, + hex: removed.value.hex, + ); + } + }, + ), + )) + .closed + .then((reason) { + // Hidden means a newer removal replaced this bar and carries the batch + // on. Anything else ends the offer. + if (reason != SnackBarClosedReason.hide) batch.clear(); + }); + } +} + +/// The removals the Settings list's current Undo bar covers, so one Undo +/// restores every nickname removed while it was up. +class NicknameRemovalBatch { + final Map _entries = {}; + + /// Adds [entry], removed from the repeater with full key [key]. + void add(String key, RepeaterNickname entry) => _entries[key] = entry; + + /// "Removed Mell" for one, "Removed 2 nicknames" for more. + String get message => _entries.length == 1 + ? 'Removed ${_entries.values.single.nickname}' + : 'Removed ${_entries.length} nicknames'; + + /// Every removal in the batch, which is left empty. + Map take() { + final taken = Map.of(_entries); + _entries.clear(); + return taken; + } + + /// Ends the batch without restoring anything. + void clear() => _entries.clear(); +} + +/// The nickname list itself, fed by the page so it can be built without the +/// provider: the saved [entries] (full key, entry) one row each, hex first, +/// like the paper list taped in the car, or a prompt to add one. +class RepeaterNicknameList extends StatelessWidget { + const RepeaterNicknameList({ + super.key, + required this.entries, + required this.onEdit, + required this.onRemove, + required this.onAdd, + }); + + final List> entries; + final void Function(String key, RepeaterNickname entry) onEdit; + final void Function(String key, RepeaterNickname entry) onRemove; + final VoidCallback onAdd; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + if (entries.isEmpty) { + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.label_outline, + size: 40, color: scheme.onSurfaceVariant), + const SizedBox(height: 12), + Text( + 'Give repeaters your own short names, like Mell for 5007. ' + 'They show instead of the ID in Top Heard, and as the name ' + 'on the Live Activity, CarPlay, Apple Watch and Siri.', + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 16), + FilledButton.tonalIcon( + icon: const Icon(Icons.add), + label: const Text('Add nickname'), + onPressed: onAdd, + ), + const SizedBox(height: 12), + Text( + 'You can also tap a repeater on the map.', + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall + ?.copyWith(color: scheme.onSurfaceVariant), + ), + ], + ), + ), + ); + } + + return ListView( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 24), + children: [ + SettingsSectionCard(title: 'Nicknames', children: [ + for (final e in entries) + ListTile( + leading: RepeaterHexBadge(e.value.hex), + title: Text( + e.value.nickname, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + subtitle: e.value.name.isEmpty ? null : Text(e.value.name), + trailing: IconButton( + icon: const Icon(Icons.delete_outline), + tooltip: 'Remove', + onPressed: () => onRemove(e.key, e.value), + ), + onTap: () => onEdit(e.key, e.value), + ), + ]), + ], + ); + } +} diff --git a/lib/screens/settings/wardriving_settings_page.dart b/lib/screens/settings/wardriving_settings_page.dart index e868e127..07df3a02 100644 --- a/lib/screens/settings/wardriving_settings_page.dart +++ b/lib/screens/settings/wardriving_settings_page.dart @@ -5,6 +5,7 @@ import '../../models/connection_state.dart'; import '../../models/user_preferences.dart'; import '../../providers/app_state_provider.dart'; import '../../widgets/carpeater_setup_dialog.dart'; +import '../../widgets/scope_discovery_firmware_note.dart'; import 'settings_section_card.dart'; /// Settings folder: Wardriving. @@ -133,6 +134,24 @@ class WardrivingSettingsPage extends StatelessWidget { ? null : () => _showSmartPingDaysSelector(context, appState), ), + if (appState.smartPingEnabled) + SwitchListTile( + secondary: const Icon(Icons.swap_horiz), + title: const Text('Delay only flood pings'), + subtitle: appState.enforceSmartPing + ? Text( + 'Set by Regional Admin. ${_floodOnlySubtitle(appState.smartPingFloodOnly)}', + style: const TextStyle(color: Colors.amber), + ) + : Text(_floodOnlySubtitle(appState.smartPingFloodOnly)), + value: appState.smartPingFloodOnly, + onChanged: (isAutoMode || appState.enforceSmartPing) + ? null + : (value) { + appState.updatePreferences( + prefs.copyWith(smartPingFloodOnly: value)); + }, + ), if (appState.smartPingEnabled) SwitchListTile( secondary: const Icon(Icons.layers_outlined), @@ -157,6 +176,64 @@ class WardrivingSettingsPage extends StatelessWidget { prefs.copyWith(showDeferredMarkers: value)); }, ), + SwitchListTile( + secondary: const Icon(Icons.travel_explore), + title: Row( + children: [ + const Flexible( + child: Text('Scope Discovery', + overflow: TextOverflow.ellipsis)), + const SizedBox(width: 4), + IconButton( + onPressed: () => _showScopeDiscoveryInfo(context), + icon: Icon( + Icons.info_outline, + size: 18, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + appState.enforceScopeDiscovery + ? 'Set by Regional Admin. Asks nearby repeaters for their scopes. Adds a little airtime; pings are not delayed.' + : 'Asks nearby repeaters for their scopes. Adds a little airtime; pings are not delayed.', + style: appState.enforceScopeDiscovery + ? const TextStyle(color: Colors.amber) + : null, + ), + ScopeDiscoveryFirmwareNote( + show: appState.scopeDiscoveryNeedsNewerFirmware), + ], + ), + value: appState.scopeDiscoveryEnabled, + onChanged: (isAutoMode || appState.enforceScopeDiscovery) + ? null + : (value) { + appState.updatePreferences( + prefs.copyWith(scopeDiscoveryEnabled: value)); + }, + ), + if (appState.scopeDiscoveryEnabled) + ListTile( + leading: const Icon(Icons.history), + title: const Text('Ask repeaters again after'), + subtitle: Text(appState.enforceScopeDiscovery + ? '${_scopeDiscoveryDaysLabel(appState.scopeRefreshDays)} (set by Regional Admin)' + : _scopeDiscoveryDaysLabel(prefs.scopeDiscoveryDays)), + trailing: const Icon(Icons.chevron_right), + enabled: !isAutoMode && !appState.enforceScopeDiscovery, + onTap: (isAutoMode || appState.enforceScopeDiscovery) + ? null + : () => _showScopeDiscoveryDaysSelector(context, appState), + ), SwitchListTile( secondary: const Icon(Icons.timer_off), title: const Text('Auto-Stop After Idle'), @@ -668,7 +745,7 @@ class WardrivingSettingsPage extends StatelessWidget { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), SizedBox(height: 4), Text( - 'A deferred ping is kept and sent as soon as you reach a square with no recent coverage, then the interval restarts. Only one ping is ever held, and the countdown reads "Deferred" while it waits.', + 'A deferred ping is kept and sent as soon as you reach a square with no recent coverage, then the interval restarts. Only one ping is ever held, and the countdown reads "Deferred" while it waits. In Hybrid, a held GRP_TXT is never replaced by a discovery request, so it is the first ping into a clear square and can paint it green. With Delay only flood pings on, discovery keeps going out while the GRP_TXT waits.', style: TextStyle(fontSize: 13), ), SizedBox(height: 12), @@ -676,7 +753,7 @@ class WardrivingSettingsPage extends StatelessWidget { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), SizedBox(height: 4), Text( - 'A square with a two-way (green) or discovery (cyan) result inside your chosen window. Squares match your Coverage Grid setting, so what is deferred is what is already painted on the map.', + 'With Delay only flood pings on (the default), a flood ping waits only in a square with a two-way (green) result inside your window, and discovery requests always go out. With it off, both wait in a square with a green or cyan result. Squares match your Coverage Grid setting, so what is deferred is what is already painted on the map.', style: TextStyle(fontSize: 13), ), SizedBox(height: 12), @@ -711,6 +788,54 @@ class WardrivingSettingsPage extends StatelessWidget { ); } + void _showScopeDiscoveryInfo(BuildContext context) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Row( + children: [ + Icon(Icons.travel_explore, size: 24), + SizedBox(width: 8), + Text('Scope Discovery'), + ], + ), + content: const SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'In Passive and Hybrid, after each discovery MeshMapper can ask the repeaters it found which scopes they carry, and adds the answers to the map.', + style: TextStyle(fontSize: 14), + ), + SizedBox(height: 12), + Text( + 'A repeater is only asked when it is due: nobody has checked it within the "Ask repeaters again after" window. Answers from other wardrivers and from the region\'s observers count too, so a repeater someone else already checked is skipped and nothing is sent to it.', + style: TextStyle(fontSize: 14), + ), + SizedBox(height: 12), + Text( + 'When repeaters are due, your radio asks up to 3 of the strongest, one at a time, and waits a few seconds for each answer. Your pings keep their normal schedule. A small "Scopes" badge shows on the ping button while it is asking, and each request appears in the log under SCP.', + style: TextStyle(fontSize: 14), + ), + SizedBox(height: 12), + Text( + 'It needs companion firmware v1.16.0 or newer.', + style: TextStyle(fontSize: 14), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Got it'), + ), + ], + ), + ); + } + void _showDiscDropInfo(BuildContext context) { showDialog( context: context, @@ -1049,6 +1174,10 @@ class WardrivingSettingsPage extends StatelessWidget { ); } + String _floodOnlySubtitle(bool floodOnly) => floodOnly + ? 'Discovery always goes out. Flood pings wait only in green squares.' + : 'Flood pings and discovery wait in green or cyan squares.'; + String _smartPingDaysLabel(int days) => days == 1 ? '1 day' : '$days days'; void _showSmartPingDaysSelector( @@ -1093,6 +1222,62 @@ class WardrivingSettingsPage extends StatelessWidget { ); } + String _scopeDiscoveryDaysLabel(int days) => + days == 1 ? '1 day' : '$days days'; + + void _showScopeDiscoveryDaysSelector( + BuildContext context, AppStateProvider appState) { + final controller = TextEditingController( + text: appState.preferences.scopeDiscoveryDays.toString()); + String? errorText; + + showDialog( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setState) => AlertDialog( + title: const Text('Ask repeaters again after'), + content: TextField( + controller: controller, + keyboardType: TextInputType.number, + autofocus: true, + decoration: InputDecoration( + suffixText: 'days', + helperText: + '${ScopeDiscoveryDays.min} to ${ScopeDiscoveryDays.max} days', + errorText: errorText, + ), + onChanged: (_) { + if (errorText != null) setState(() => errorText = null); + }, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + final value = int.tryParse(controller.text.trim()); + if (value == null || + value < ScopeDiscoveryDays.min || + value > ScopeDiscoveryDays.max) { + setState(() => errorText = + 'Enter a number from ${ScopeDiscoveryDays.min} to ${ScopeDiscoveryDays.max}'); + return; + } + appState.updatePreferences( + appState.preferences.copyWith(scopeDiscoveryDays: value), + ); + Navigator.pop(context); + }, + child: const Text('Save'), + ), + ], + ), + ), + ); + } + /// The region's shared CARpeater list, read-only. The regional admin owns it. void _showRegionalCarpeaters( BuildContext context, AppStateProvider appState) { diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 4f61c2db..e6f7bf09 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,4 +1,5 @@ -import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/foundation.dart' + show kIsWeb, defaultTargetPlatform, TargetPlatform; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -7,6 +8,7 @@ import '../utils/constants.dart'; import 'settings/about_settings_page.dart'; import 'settings/account_settings_page.dart'; import 'settings/api_endpoints_settings_page.dart'; +import 'settings/close_app_tile.dart'; import 'settings/data_settings_page.dart'; import 'settings/developer_settings_page.dart'; import 'settings/general_settings_page.dart'; @@ -15,7 +17,8 @@ import 'settings/settings_section_card.dart'; import 'settings/wardriving_settings_page.dart'; import 'watch_diagnostics_screen.dart'; -/// Settings tab: one row per settings folder, each opening its own page. +/// Settings tab: one row per settings folder, each opening its own page, +/// plus Close App at the bottom on Android. /// /// The folder pages live in `settings/`. This screen only decides which rows /// to show; every tile, dialog and platform gate lives on the page it belongs @@ -34,6 +37,13 @@ class SettingsScreen extends StatelessWidget { final aboutSubtitle = kIsWeb ? 'Version ${AppConstants.appVersion}, feedback' : 'Version ${AppConstants.appVersion}, feedback, debug logs'; + // The background location setting is iOS-only and the exit options are + // Android-only, so the web build has neither. + final generalSubtitle = kIsWeb + ? 'Appearance, sounds' + : defaultTargetPlatform == TargetPlatform.iOS + ? 'Appearance, sounds, background location' + : 'Appearance, sounds, exit options'; return Scaffold( appBar: AppBar( @@ -49,7 +59,7 @@ class SettingsScreen extends StatelessWidget { _FolderTile( icon: Icons.tune, title: 'General', - subtitle: 'Appearance, sounds, background location', + subtitle: generalSubtitle, builder: (_) => const GeneralSettingsPage(), ), _FolderTile( @@ -112,6 +122,9 @@ class SettingsScreen extends StatelessWidget { builder: (_) => const DeveloperSettingsPage(), ), ]), + // iOS does not let an app exit itself, and the web build cannot. + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) + const SettingsSectionCard(children: [CloseAppTile()]), ], ), ); diff --git a/lib/services/android_altitude_channel.dart b/lib/services/android_altitude_channel.dart new file mode 100644 index 00000000..2cbf982d --- /dev/null +++ b/lib/services/android_altitude_channel.dart @@ -0,0 +1,25 @@ +import 'package:flutter/services.dart'; + +import 'fix_altitude.dart'; + +/// Asks the Android side to describe the location provider's most recent +/// fix object, so the altitude rule can prove which value the location +/// plugin delivered (see `fix_altitude.dart`). Android only. Every failure +/// answers null and says nothing: the resolver stores unknown and owns the +/// one throttled `[GPS]` warning, so a flapping channel cannot log per fix. +class AndroidAltitudeChannel { + AndroidAltitudeChannel({MethodChannel? channel}) + : _channel = channel ?? const MethodChannel('meshmapper/altitude'); + + final MethodChannel _channel; + + Future describeLastFix() async { + try { + final raw = await _channel.invokeMethod('describeLastFix'); + return NativeAltitudeAnswer.tryFromMap(raw); + } catch (_) { + // MissingPluginException, PlatformException or a codec error alike. + return null; + } + } +} diff --git a/lib/services/api_queue_service.dart b/lib/services/api_queue_service.dart index 24158985..eef930fd 100644 --- a/lib/services/api_queue_service.dart +++ b/lib/services/api_queue_service.dart @@ -5,10 +5,253 @@ import 'package:hive/hive.dart'; import '../models/api_queue_item.dart'; import '../utils/debug_logger_io.dart'; +import '../utils/public_key.dart'; import 'api_service.dart'; import 'custom_api_service.dart'; import 'network_state_service.dart'; +/// Extracts the public key a DISC item reports, or null when the item is +/// not a successful DISC (a failed discovery's heardRepeats is `'None'`, and +/// nothing else carries this shape). Used to line a SCOPES item up with the +/// DISC that must precede it. +String? _discKeyOf(ApiQueueItem item) { + if (item.type != 'DISC' || item.heardRepeats == 'None') return null; + // "repeaterId:nodeType:localSnr:localRssi:remoteSnr:pubkeyFull" + final parts = item.heardRepeats.split(':'); + if (parts.length < 6 || parts[5].isEmpty) return null; + return parts[5].toUpperCase(); +} + +/// Selects which eligible items belong in the next batch, holding a SCOPES +/// item back until its DISC has either already left in an earlier batch (no +/// longer anywhere in the queue) or rides along in this same batch. +/// +/// The server records every DISC-heard key of a batch before it checks any +/// SCOPES in it, but refuses a SCOPES whose DISC only arrives LATER, so a +/// SCOPES item must never be uploaded ahead of the DISC it depends on. +/// +/// [eligible] is every item ready for this batch, in the existing order +/// (retry eligibility, Hive before memory). [allQueued] is every item +/// currently held, Hive and memory alike, regardless of retry eligibility: +/// a DISC sitting in retry backoff still counts as "not yet delivered", so +/// its SCOPES must wait for it even though the DISC itself is not eligible +/// for this batch. +/// +/// Non-SCOPES items are selected first, up to [batchSize], so a run of +/// blocked SCOPES at the head of the queue can never crowd out the DISC +/// items behind them; a held-back SCOPES never occupies a slot. +List selectBatchWithScopesDependency({ + required List eligible, + required List allQueued, + required int batchSize, +}) { + final discKeysAnywhere = {}; + for (final item in allQueued) { + final key = _discKeyOf(item); + if (key != null) discKeysAnywhere.add(key); + } + + final nonScopes = []; + final scopesCandidates = []; + for (final item in eligible) { + if (item.type == 'SCOPES') { + scopesCandidates.add(item); + } else { + nonScopes.add(item); + } + } + + final selected = nonScopes.take(batchSize).toList(); + + final selectedDiscKeys = {}; + for (final item in selected) { + final key = _discKeyOf(item); + if (key != null) selectedDiscKeys.add(key); + } + + var remaining = batchSize - selected.length; + if (remaining > 0) { + for (final scopeItem in scopesCandidates) { + if (remaining <= 0) break; + final key = scopeItem.heardRepeats.toUpperCase(); + final discAlreadyDelivered = !discKeysAnywhere.contains(key); + if (selectedDiscKeys.contains(key) || discAlreadyDelivered) { + selected.add(scopeItem); + remaining--; + } + } + } + + return selected; +} + +/// Stable-partitions API JSON rows so every SCOPES row comes after every +/// other row, preserving relative order within each group. The server +/// records a batch or offline chunk's DISC-heard keys before it checks any +/// SCOPES in it, but refuses a SCOPES whose DISC only arrives in a LATER +/// batch or chunk, so every export and every chunk boundary must keep DISC +/// (and everything else) ahead of SCOPES, whatever order the rows were +/// recorded or stored in. +List> orderDiscBeforeScopes( + List> rows) { + final others = rows.where((r) => r['type'] != 'SCOPES').toList(); + final scopes = rows.where((r) => r['type'] == 'SCOPES').toList(); + return [...others, ...scopes]; +} + +/// The two altitude references the app ever labels. +const Set kAltitudeReferences = {'msl', 'ellipsoid'}; + +/// One short phrase per upload saying how many rows carried a labelled +/// altitude, by type, for the Android 14 device check. Batch level only, +/// never per fix. Example: `altitude_ref 3/5 (TX 2/3, RX 1/2)`. +String altitudeLabelSummary(List> entries) { + final byType = {}; + var labelled = 0; + var total = 0; + for (final e in entries) { + final type = e['type']?.toString() ?? '?'; + if (type == 'DEFER' || type == 'SCOPES') continue; + final has = kAltitudeReferences.contains(e['altitude_ref']); + total++; + if (has) labelled++; + final prev = byType[type] ?? (0, 0); + byType[type] = (prev.$1 + (has ? 1 : 0), prev.$2 + 1); + } + if (total == 0) return 'altitude_ref 0/0'; + final parts = byType.entries + .map((kv) => '${kv.key} ${kv.value.$1}/${kv.value.$2}') + .join(', '); + return 'altitude_ref $labelled/$total ($parts)'; +} + +/// Removes `altitude`, `altitude_ref` and `altitude_acc` from every row whose +/// reference is not one of [kAltitudeReferences]. An altitude never leaves +/// the phone without a proved reference, and a row saved by an older build +/// (an offline session from before the reference existed) was serialized +/// before that rule, so it is cleaned here, at the doors it leaves through. +/// No reference is ever guessed. Row order and count are unchanged. +List> withoutUnlabelledAltitude( + List> rows) { + return rows.map((r) { + final ref = r['altitude_ref']; + if (ref is String && kAltitudeReferences.contains(ref)) return r; + if (!r.containsKey('altitude') && + !r.containsKey('altitude_ref') && + !r.containsKey('altitude_acc')) { + return r; + } + return Map.from(r) + ..remove('altitude') + ..remove('altitude_ref') + ..remove('altitude_acc'); + }).toList(); +} + +/// Removes every SCOPES row from a list of API JSON rows, preserving the +/// order of everything else. Used before an offline upload when the auth +/// answer did not offer scope discovery: the server would refuse every one +/// of them, so they are stripped before the partial-upload cleanup counts +/// rows by how many were actually uploaded. +List> withoutScopesItems( + List> rows) { + return rows.where((r) => r['type'] != 'SCOPES').toList(); +} + +/// Result of [runOfflineChunkedUpload]. +class OfflineChunkedUploadResult { + /// The rows actually offered for upload, after the SCOPES strip and the + /// DISC-before-SCOPES reorder. This is also what was handed to + /// `persistRows` whenever the original rows held any SCOPES row, so it is + /// what the caller's prefix-by-uploaded-count cleanup must read against. + final List> orderedRows; + + /// How many of [orderedRows], counting from the start, were successfully + /// uploaded before the first chunk that was not. + final int uploadedCount; + + /// How many SCOPES rows were stripped because the upload auth did not + /// offer scope discovery (0 when it did). + final int removedScopesCount; + + const OfflineChunkedUploadResult({ + required this.orderedRows, + required this.uploadedCount, + required this.removedScopesCount, + }); +} + +/// Orchestrates an offline session's chunked upload, kept free of network +/// and storage specifics so it is testable without an `AppStateProvider`. +/// +/// Strips every SCOPES row when [scopeDiscoveryOffered] is false, then moves +/// every remaining SCOPES row after every other row (DISC before SCOPES, a +/// stable partition, [orderDiscBeforeScopes]). When [rows] held ANY SCOPES +/// row, the resulting order is handed to [persistRows] BEFORE the first +/// chunk is built: the caller's partial-upload cleanup later removes a +/// PREFIX of the stored rows by uploaded count, and that prefix only lines +/// up with what was actually sent when the stored file holds the same order +/// that was chunked. A session with no SCOPES rows at all skips the write +/// (the stored order already matches, since stripping and reordering are +/// both no-ops with nothing to strip or reorder). +/// +/// [uploadChunk] is called once per fixed-size chunk, in order, with the +/// chunk's rows, its 1-based number and the total chunk count; it must +/// perform whatever retry the caller wants and return true only on an +/// eventual success. The loop stops at the first chunk that returns false, +/// so every row from that chunk on is left un-uploaded. +/// +/// This function, not [uploadChunk], decides what reaches the custom API: +/// [forwardChunk] is called once for each chunk that uploaded, right after +/// it did, with exactly that chunk's rows. A chunk that failed and every +/// chunk after it are never forwarded, and no chunk is forwarded twice. +/// +/// Every row also loses a bare altitude first (`withoutUnlabelledAltitude`), +/// so a session saved by an older build never uploads or forwards an +/// altitude without its reference. +Future runOfflineChunkedUpload( + List> rows, { + required bool scopeDiscoveryOffered, + required int batchSize, + required Future Function(List> orderedRows) + persistRows, + required Future Function( + List> chunk, + int chunkNumber, + int totalChunks, + ) uploadChunk, + required void Function(List> chunk, int chunkNumber) + forwardChunk, +}) async { + final cleaned = withoutUnlabelledAltitude(rows); + final stripped = + scopeDiscoveryOffered ? cleaned : withoutScopesItems(cleaned); + final removedScopesCount = rows.length - stripped.length; + final ordered = orderDiscBeforeScopes(stripped); + + if (rows.any((r) => r['type'] == 'SCOPES')) { + await persistRows(ordered); + } + + final totalChunks = + ordered.isEmpty ? 0 : (ordered.length + batchSize - 1) ~/ batchSize; + var uploadedCount = 0; + for (var i = 0; i < ordered.length; i += batchSize) { + final chunkNumber = (i ~/ batchSize) + 1; + final chunk = ordered.skip(i).take(batchSize).toList(); + final ok = await uploadChunk(chunk, chunkNumber, totalChunks); + if (!ok) break; + uploadedCount += chunk.length; + forwardChunk(chunk, chunkNumber); + } + + return OfflineChunkedUploadResult( + orderedRows: ordered, + uploadedCount: uploadedCount, + removedScopesCount: removedScopesCount, + ); +} + /// API queue service with batch upload and retry logic /// Ported from apiQueue and batchUpload() in wardrive.js /// @@ -39,8 +282,16 @@ class ApiQueueService { StreamSubscription? _networkStateSubscription; late bool _lastIsConstrained; bool _isUploading = false; + Completer? _uploadInFlight; bool _isRecovering = false; + // Scheduled-upload pause (see pauseScheduledUploads). The two flags + // remember what the pause interrupted, or what asked for a timer while it + // held, so the resume puts back exactly that. + bool _scheduledUploadsPaused = false; + bool _batchTimerOwed = false; + bool _pingFlushOwed = false; + // In-memory fallback when Hive is corrupted/unavailable final List _memoryQueue = []; @@ -60,6 +311,26 @@ class ApiQueueService { // RX buffer for grouping by repeater final Map> _rxBuffer = {}; + /// Bumped every time the queue is cleared ([clear], [clearBeforeConnect], + /// [clearOnDisconnect], and the stale-item sweep in [init]). A scope + /// discovery answer's send and its enqueue are separated by a mesh round + /// trip, so the queue can be cleared out from under a call that is still + /// in flight; the caller reads this before starting and passes it back so + /// a late insertion can tell whether the queue it was aimed at still + /// exists. + int _generation = 0; + + /// The current queue generation. Read before a scope answer's send, then + /// passed back to [enqueueScopes] as `expectedGeneration`. + int get generation => _generation; + + /// Bumps [generation]. Called FIRST by every clear path, before the clear + /// itself, so a write already in flight against the old generation sees + /// the new one before (or regardless of whether) the clear it raced + /// finishes, and cannot resurrect a stale item into a queue that is being + /// or has just been emptied. + void _bumpGeneration() => _generation++; + /// Callback for queue updates void Function(int queueSize)? onQueueUpdated; @@ -93,6 +364,12 @@ class ApiQueueService { /// value. String? Function()? radioConfigGetter; + /// Whether the region has offered scope discovery, wired to + /// `ApiService.scopeDiscoveryOffered`. Null (not wired) is read as + /// allowed; the batch builder drops every queued SCOPES item the moment + /// this returns `false`, whatever the queue holds. + bool Function()? scopesAllowedGetter; + /// Number of pings accumulated in current offline session int get offlinePingCount => _offlinePings.length; @@ -149,6 +426,7 @@ class ApiQueueService { // ALWAYS START FRESH - clear any leftover pings from previous sessions // Pings without a valid session cannot be uploaded, so delete them + _bumpGeneration(); try { if (_box != null && _box!.isNotEmpty) { debugLog( @@ -219,6 +497,13 @@ class ApiQueueService { } } + /// Opens the fresh box [_recoverBox] switches to after deleting the + /// corrupt one. Production always opens the real queue box; a test swaps + /// this to control what the recovered box does with the retried write. + @visibleForTesting + Future> Function() reopenBoxForRecovery = + () => Hive.openBox(_boxName); + /// Recover from runtime Hive corruption by closing, deleting, and reopening the box Future _recoverBox() async { if (_isRecovering) { @@ -227,6 +512,16 @@ class ApiQueueService { } _isRecovering = true; + // Deleting the box erases every queued item, exactly as a clear does, so + // it is a new generation. Bumped synchronously, before the first await + // below, like the clear paths: a SCOPES whose DISC sat in this box would + // otherwise be accepted by its retry and uploaded as if the DISC had gone + // out. That includes a second enqueue that fails while this recovery is + // still closing the box: it skips recovery (one runs at a time) and must + // already see the new generation, or it lands in memory under the old one. + _bumpGeneration(); + debugLog('[API QUEUE] Queue generation bumped for storage recovery'); + try { debugLog( '[API QUEUE] Runtime corruption detected - recovering box "$_boxName"...'); @@ -242,8 +537,8 @@ class ApiQueueService { await Hive.deleteBoxFromDisk(_boxName); onStorageCleanup?.call('Queue storage was corrupted and has been reset'); - final box = await Hive.openBox(_boxName) - .timeout(const Duration(seconds: 5)); + final box = + await reopenBoxForRecovery().timeout(const Duration(seconds: 5)); _box = box; debugLog('[API QUEUE] Box recovered successfully'); } catch (e) { @@ -313,6 +608,8 @@ class ApiQueueService { int? pingCounter, String? wireTag, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, }) async { final item = ApiQueueItem.fromTx( latitude: latitude, @@ -325,6 +622,8 @@ class ApiQueueService { pingCounter: pingCounter, wireTag: wireTag, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoModeGetter?.call(), radioFreq: radioConfigGetter?.call(), ); @@ -362,6 +661,8 @@ class ApiQueueService { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, }) async { final item = ApiQueueItem.fromRx( latitude: latitude, @@ -372,6 +673,8 @@ class ApiQueueService { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoModeGetter?.call(), radioFreq: radioConfigGetter?.call(), ); @@ -412,6 +715,8 @@ class ApiQueueService { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, }) async { final item = ApiQueueItem.fromDisc( latitude: latitude, @@ -427,6 +732,8 @@ class ApiQueueService { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoModeGetter?.call(), radioFreq: radioConfigGetter?.call(), ); @@ -465,6 +772,8 @@ class ApiQueueService { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, }) async { final item = ApiQueueItem.fromTrace( latitude: latitude, @@ -478,6 +787,8 @@ class ApiQueueService { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoModeGetter?.call(), radioFreq: radioConfigGetter?.call(), ); @@ -512,6 +823,8 @@ class ApiQueueService { int? noiseFloor, double? power, double? altitude, + String? altitudeRef, + double? altitudeAccuracy, }) async { final item = ApiQueueItem.fromDiscDrop( latitude: latitude, @@ -521,6 +834,8 @@ class ApiQueueService { noiseFloor: noiseFloor, power: power, altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, autoMode: autoModeGetter?.call(), radioFreq: radioConfigGetter?.call(), ); @@ -586,6 +901,128 @@ class ApiQueueService { _schedulePingFlush(); } + /// Queue a repeater's scope discovery answer. The public key rides in the + /// heardRepeats slot, the DISC/DEFER packing precedent, with the answer + /// itself in [ApiQueueItem.scopes]. Modelled on [enqueueDefer]: offline + /// rows honour the airborne pause, a closed box falls back to memory, and + /// the network-aware flush timer sends it on. + /// + /// A scope answer's send and its enqueue are separated by a mesh round + /// trip, during which a disconnect can clear the queue out from under it. + /// [expectedGeneration] (read from [generation] before the send started) + /// is checked immediately before every write attempt this call makes, + /// including a Hive recovery retry and the memory-fallback insertion. A + /// mismatch at any of those points returns false and leaves nothing + /// inserted, undoing a write that already landed rather than resurrecting + /// an item into a queue that no longer exists. + Future enqueueScopes({ + required String publicKeyHex, + required List scopes, + required double lat, + required double lon, + required int timestamp, + required int expectedGeneration, + String? radioFreq, + }) async { + if (!lat.isFinite || !lon.isFinite) { + debugWarn('[API QUEUE] SCOPES dropped: non-finite lat/lon'); + return false; + } + + // The server rejects the whole item unless this is exactly 64 + // upper-case hex; refuse here rather than upload something it will + // discard silently. + final normalizedKey = normalizePublicKey(publicKeyHex); + if (normalizedKey == null) { + debugWarn('[API QUEUE] SCOPES dropped: invalid public key'); + return false; + } + + final item = ApiQueueItem.fromScopes( + publicKeyHex: normalizedKey, + scopes: scopes, + lat: lat, + lon: lon, + timestamp: timestamp, + radioFreq: radioFreq ?? radioConfigGetter?.call(), + ); + + // In offline mode, accumulate to offline pings list instead of queue + if (offlineMode) { + if (_dropOfflineRowIfPaused()) return false; + if (expectedGeneration != _generation) { + debugWarn( + '[API QUEUE] SCOPES dropped: queue generation changed (queue was cleared)'); + return false; + } + _offlinePings.add(item.toApiJson()); + debugLog('[API QUEUE] SCOPES enqueued (offline)'); + return true; + } + + if (expectedGeneration != _generation) { + debugWarn( + '[API QUEUE] SCOPES dropped: queue generation changed before write (queue was cleared)'); + return false; + } + + final box = _box; + var wrote = false; + if (box != null) { + try { + await box.add(item); + wrote = true; + } catch (e) { + debugError( + '[API QUEUE] SCOPES write failed: $e - attempting recovery'); + await _recoverBox(); + if (expectedGeneration != _generation) { + debugWarn( + '[API QUEUE] SCOPES dropped: queue generation changed during recovery (queue was cleared)'); + return false; + } + final retryBox = _box; + if (retryBox != null) { + try { + await retryBox.add(item); + wrote = true; + } catch (e2) { + debugError('[API QUEUE] SCOPES write failed after recovery: $e2'); + } + } + } + } + + if (wrote) { + if (expectedGeneration != _generation) { + // The clear that bumped the generation may have run while the write + // above (or its retry) was in flight. What landed belongs to a queue + // that no longer exists, so undo it rather than leave it queued. + try { + await item.delete(); + } catch (_) {} + debugWarn( + '[API QUEUE] SCOPES dropped: queue generation changed during write (queue was cleared)'); + return false; + } + debugLog('[API QUEUE] SCOPES enqueued (queue size: $queueSize)'); + } else { + // Every Hive attempt failed. A clear may have landed while the last + // of them was failing, so check again before the memory fallback. + if (expectedGeneration != _generation) { + debugWarn( + '[API QUEUE] SCOPES dropped: queue generation changed before memory fallback (queue was cleared)'); + return false; + } + _memoryQueue.add(item); + debugLog( + '[API QUEUE] SCOPES enqueued (memory fallback) (queue size: $queueSize)'); + } + onQueueUpdated?.call(queueSize); + _schedulePingFlush(); + return true; + } + // Guard to prevent concurrent RX buffer flushes bool _isFlushing = false; @@ -643,6 +1080,10 @@ class ApiQueueService { } void _schedulePingFlush() { + if (_scheduledUploadsPaused) { + _pingFlushOwed = true; + return; + } final timeout = _lastIsConstrained ? _pingFlushTimeoutConstrained : _pingFlushTimeout; _pingFlushTimer?.cancel(); @@ -657,6 +1098,10 @@ class ApiQueueService { } void _startBatchTimer() { + if (_scheduledUploadsPaused) { + _batchTimerOwed = true; + return; + } final constrained = _lastIsConstrained; final timeout = constrained ? _batchTimeoutConstrained : _batchTimeout; _batchTimer?.cancel(); @@ -678,6 +1123,36 @@ class ApiQueueService { await _uploadBatch(); } + /// Removes every queued SCOPES item when the region has not offered scope + /// discovery (the key was absent from the live /auth answer). Called at + /// the top of every upload attempt so a queue built before the app learned + /// this never tries to send rows the server will refuse. + Future _dropDisallowedScopesItems() async { + if (scopesAllowedGetter?.call() != false) return; + + final hiveScopes = _safeRead( + (box) => box.values.where((i) => i.type == 'SCOPES').toList(), + [], + ); + for (final item in hiveScopes) { + try { + await item.delete(); + } catch (e) { + debugError('[API QUEUE] Failed to drop disallowed SCOPES item: $e'); + } + } + + final beforeMemory = _memoryQueue.length; + _memoryQueue.removeWhere((i) => i.type == 'SCOPES'); + final dropped = hiveScopes.length + (beforeMemory - _memoryQueue.length); + + if (dropped > 0) { + debugWarn( + '[API QUEUE] Dropped $dropped SCOPES item(s): scope discovery not offered'); + onQueueUpdated?.call(queueSize); + } + } + /// Upload batch of queued items (from Hive box or in-memory fallback) /// /// [silentWhenEmpty] suppresses the empty-queue line for callers that @@ -689,47 +1164,83 @@ class ApiQueueService { debugLog('[API QUEUE] Upload skipped: already uploading'); return; } + // Claim the guard BEFORE any await below (including the scope-removal + // pass): two overlapping flushes (the batch timer and the ping flush + // timer can fire close together) both read `_isUploading` in the same + // event-loop turn if it is set any later, both pass the check, and both + // select and upload the same items. Released in `finally` so every + // return path below (including the early ones) clears it. + _isUploading = true; + _uploadInFlight = Completer(); - final hiveEmpty = _safeRead((box) => box.isEmpty, true); - final memoryEmpty = _memoryQueue.isEmpty; + try { + await _dropDisallowedScopesItems(); - if (hiveEmpty && memoryEmpty) { - if (!silentWhenEmpty) { - debugLog('[API QUEUE] Upload skipped: queue empty'); - } - return; - } + final hiveEmpty = _safeRead((box) => box.isEmpty, true); + final memoryEmpty = _memoryQueue.isEmpty; - _isUploading = true; + if (hiveEmpty && memoryEmpty) { + if (!silentWhenEmpty) { + debugLog('[API QUEUE] Upload skipped: queue empty'); + } + return; + } - try { - // Collect items from both Hive and memory queue - final hiveItems = _safeRead( + // Collect every eligible item from both Hive and memory queue, in the + // existing order (Hive before memory), uncapped: the SCOPES dependency + // filter below decides what fills the batch, not this read, or a run + // of blocked SCOPES at the head of the queue could crowd out the + // non-SCOPES items behind them. + final eligibleHive = _safeRead( (box) => box.values .where((item) => item.retryCount < _maxRetries && item.isReadyForRetry && item.isUploadEligible) - .take(_batchSize) .toList(), []); - final memoryItems = _memoryQueue + final eligibleMemory = _memoryQueue .where((item) => item.retryCount < _maxRetries && item.isReadyForRetry && item.isUploadEligible) - .take(_batchSize - hiveItems.length) .toList(); - final items = [...hiveItems, ...memoryItems]; + // Every item currently held, regardless of retry eligibility: a DISC + // still climbing the retry ladder has not been delivered, so its + // SCOPES must wait for it even though the DISC itself is not eligible + // for this batch. + final allQueued = [ + ..._safeRead((box) => box.values.toList(), []), + ..._memoryQueue, + ]; + + // Excluded here independently of whether `_dropDisallowedScopesItems` + // above actually managed to delete anything: a Hive deletion failure + // (logged there) must not let a disallowed SCOPES item back into the + // batch, or the custom-API forward that rides the same `pings` list. + final scopesBlocked = scopesAllowedGetter?.call() == false; + final eligible = scopesBlocked + ? [...eligibleHive, ...eligibleMemory] + .where((item) => item.type != 'SCOPES') + .toList() + : [...eligibleHive, ...eligibleMemory]; + + final items = selectBatchWithScopesDependency( + eligible: eligible, + allQueued: allQueued, + batchSize: _batchSize, + ); if (items.isEmpty) { debugLog('[API QUEUE] Upload skipped: no items ready for upload'); - _isUploading = false; return; } + final hiveItems = items.where((item) => item.isInBox).toList(); + final memoryItems = items.where((item) => !item.isInBox).toList(); + // Convert to API format final pings = items.map((item) => item.toApiJson()).toList(); @@ -756,7 +1267,15 @@ class ApiQueueService { final result = await _apiService.uploadBatch(pings); if (result == UploadResult.success) { - final uploadedCount = items.length; + // A replay that left SCOPES out (scope discovery withdrawn while the + // first attempt failed) still deletes them below, since the region + // no longer takes them, but they were never sent, so they are not + // counted as uploaded, handed on, or forwarded. + final strippedScopes = _apiService.lastUploadDroppedScopes > 0; + final sentItems = strippedScopes + ? items.where((item) => item.type != 'SCOPES').toList() + : items; + final uploadedCount = sentItems.length; // Remove successful Hive items for (final item in hiveItems) { try { @@ -767,13 +1286,20 @@ class ApiQueueService { for (final item in memoryItems) { _memoryQueue.remove(item); } - debugLog('[API QUEUE] Upload SUCCESS: deleted $uploadedCount items'); + debugLog('[API QUEUE] Upload SUCCESS: deleted ${items.length} items' + '${strippedScopes ? ' ($uploadedCount sent, ${items.length - uploadedCount} SCOPES dropped by the replay)' : ''}'); // The network is demonstrably back, so give anything the ladder has // already written off one more chance. _reviveFailedItems(); - onUploadSuccess?.call(uploadedCount, items); - // Fire-and-forget: forward to custom API endpoint - customApiService?.forwardPings(pings); + onUploadSuccess?.call(uploadedCount, sentItems); + // Fire-and-forget: forward to custom API endpoint. A withdrawal + // that landed while this batch was in flight made the replay leave + // its SCOPES out (ApiService.submitWardriveData), so leave them out + // here too: a withdrawn answer is never forwarded. + customApiService?.forwardPings( + strippedScopes || scopesAllowedGetter?.call() == false + ? withoutScopesItems(pings) + : pings); } else if (result == UploadResult.nonRetryable) { // Data is permanently invalid — discard for (final item in hiveItems) { @@ -819,9 +1345,73 @@ class ApiQueueService { // Retry later } finally { _isUploading = false; + final done = _uploadInFlight; + _uploadInFlight = null; + if (done != null && !done.isCompleted) done.complete(); + } + } + + /// True while a batch upload is on the wire. + bool get isUploading => _isUploading; + + /// Waits for an upload already in flight to finish, for at most [limit]. + /// True when no upload is running by then; false when the bound ran out + /// with it still on the wire. A caller about to release the session uses + /// this so a batch POSTed under that session is answered before the server + /// closes it: the answer to a batch that lands after the close is + /// `bad_session`, which ends the connection. + Future waitForUploadToFinish({ + Duration limit = const Duration(seconds: 15), + }) async { + final inFlight = _uploadInFlight; + if (inFlight == null) return true; + try { + await inFlight.future.timeout(limit); + return true; + } on TimeoutException { + debugWarn('[API QUEUE] Upload still in flight after ${limit.inSeconds}s'); + return false; } } + /// True while [pauseScheduledUploads] holds the timers. + bool get scheduledUploadsPaused => _scheduledUploadsPaused; + + /// Holds the scheduled uploads (the periodic batch timer and the + /// post-enqueue ping flush) without touching the queue, so no timer can + /// start a batch under a session the caller is about to release. Explicit + /// uploads ([forceUploadWithHoldWait], [flushQueue]) still run, which is + /// how a group handoff drains the queue while holding this. Idempotent. + void pauseScheduledUploads() { + if (_scheduledUploadsPaused) return; + _scheduledUploadsPaused = true; + _batchTimerOwed = _batchTimer != null; + _pingFlushOwed = _pingFlushTimer?.isActive ?? false; + _batchTimer?.cancel(); + _batchTimer = null; + _pingFlushTimer?.cancel(); + _pingFlushTimer = null; + debugLog('[API QUEUE] Scheduled uploads paused'); + } + + /// Undoes [pauseScheduledUploads]: the batch timer comes back when it was + /// running at the pause (or was asked for during it), and a ping flush is + /// scheduled when one was pending or anything was enqueued meanwhile. + /// Idempotent, and a no-op after [clearOnDisconnect] took the timers down. + void resumeScheduledUploads() { + if (!_scheduledUploadsPaused) return; + _scheduledUploadsPaused = false; + final restartBatch = _batchTimerOwed; + final flush = _pingFlushOwed || queueSize > 0 || _rxBuffer.isNotEmpty; + _batchTimerOwed = false; + _pingFlushOwed = false; + if (restartBatch) _startBatchTimer(); + if (flush) _schedulePingFlush(); + debugLog('[API QUEUE] Scheduled uploads resumed' + '${restartBatch ? ', batch timer restarted' : ''}' + '${flush ? ', ping flush scheduled' : ''}'); + } + /// Force upload all queued items Future forceUpload() async { await _flushRxBuffer(); @@ -838,6 +1428,7 @@ class ApiQueueService { /// Clear all queued items Future clear() async { + _bumpGeneration(); await _safeWrite((box) => box.clear()); _memoryQueue.clear(); _rxBuffer.clear(); @@ -848,11 +1439,18 @@ class ApiQueueService { /// Called when device disconnects to ensure no stale pings remain /// Also stops the batch timer to prevent upload attempts without a session Future clearOnDisconnect() async { - // Stop timers to prevent upload attempts without session + _bumpGeneration(); + + // Stop timers to prevent upload attempts without session. A pause still + // held by a handoff this disconnect superseded is dropped with them, so + // its resume restarts nothing. _batchTimer?.cancel(); _batchTimer = null; _pingFlushTimer?.cancel(); _pingFlushTimer = null; + _scheduledUploadsPaused = false; + _batchTimerOwed = false; + _pingFlushOwed = false; debugLog('[API QUEUE] Timers stopped on disconnect'); final count = queueSize + _rxBuffer.length; @@ -870,6 +1468,7 @@ class ApiQueueService { /// Called before establishing a new connection /// Also restarts the batch timer if it was stopped Future clearBeforeConnect() async { + _bumpGeneration(); final count = queueSize + _rxBuffer.length; if (count > 0) { debugLog('[API QUEUE] Clearing $count stale items before connect'); @@ -922,6 +1521,18 @@ class ApiQueueService { ..._memoryQueue, ]; + /// Direct access to the underlying Hive box. + /// + /// Exists so a test can force the "box unavailable" path for exactly one + /// write (set to null, enqueue, then restore) without going through the + /// real recovery flow, which deletes the box from disk and would destroy + /// items a test already committed to it. Production code never reads or + /// writes this; it always goes through [_box]. + @visibleForTesting + Box? get testBox => _box; + @visibleForTesting + set testBox(Box? box) => _box = box; + /// Get failed items (exceeded max retries) List get failedItems { final hiveItems = _safeRead( @@ -1033,7 +1644,13 @@ class ApiQueueService { 'offline session could upload (kept ${deliverable.length} untagged item(s))'); } - return deliverable.map((item) => item.toApiJson()).toList(); + // Hive-then-memory concatenation order says nothing about which item's + // DISC counterpart went out first, so every SCOPES row is moved after + // every other row here (a stable partition): the server records a + // batch's DISC-heard keys before it checks any SCOPES in it, and this + // snapshot becomes a fresh offline session that re-uploads in chunks. + return orderDiscBeforeScopes( + deliverable.map((item) => item.toApiJson()).toList()); } /// Dispose of resources diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart index 6dde069f..4db9b5c1 100644 --- a/lib/services/api_service.dart +++ b/lib/services/api_service.dart @@ -9,6 +9,9 @@ import 'package:http/http.dart' as http; import '../models/device_catalog.dart'; import '../models/repeater.dart'; import '../utils/debug_logger_io.dart'; +import '../utils/mvt_cells.dart'; +import 'api_queue_service.dart' show altitudeLabelSummary; +import 'border_loader.dart' show BorderAnswer; import 'meshcore/regional_carpeater_filter.dart'; import 'network_state_service.dart'; @@ -84,6 +87,20 @@ bool _connectionWasAlreadyClosed(Object error) => error is http.ClientException && error.message.contains('Connection closed before full header was received'); +/// A failed repeater read, distinct from a successful empty list. +/// Contains no response body, request headers or credentials. +class RepeaterFetchException implements Exception { + final int? statusCode; + const RepeaterFetchException([this.statusCode]); + + bool get isAuthenticationFailure => statusCode == 401 || statusCode == 403; + + @override + String toString() => isAuthenticationFailure + ? 'Repeater authentication failed (HTTP $statusCode)' + : 'Repeater request failed${statusCode == null ? '' : ' (HTTP $statusCode)'}'; +} + /// MeshMapper API service /// Handles communication with the MeshMapper backend /// @@ -129,9 +146,15 @@ class ApiService { /// Longest hold a `Retry-After` header can impose on the wardrive door. static const Duration maxWardriveRetryAfter = Duration(hours: 1); + // Repeater reads have their own per-host hold, independent of wardriving. + // A preset change must not bypass the host's Retry-After. + final Map + _repeaterReadHolds = {}; + final http.Client _client; final NetworkStateSource _networkState; final Duration _deviceCatalogTimeout; + final Duration _borderTimeout; final DateTime Function() _now; bool _heartbeatEnabled = false; // Track if heartbeat mode is active String? _sessionId; @@ -162,6 +185,10 @@ class ApiService { int _apiHopBytes = 1; bool _enforceSmartPing = false; int _apiSmartPingDays = 14; + bool _apiSmartPingFloodOnly = true; + bool _scopeDiscoveryOffered = false; + bool _enforceScopeDiscovery = false; + int _apiScopeRefreshDays = 14; /// The user's own CARpeater key, sent as `carpeater` on connect and /// register auths, never on an offline-mode auth. Null while the CARpeater @@ -206,6 +233,26 @@ class ApiService { /// [enforceSmartPing] is true. 14 when the field is missing or invalid. int get apiSmartPingDays => _apiSmartPingDays; + /// Whether Smart Pinging holds a flood (TX) ping back only for a green + /// square and never holds a discovery request; only binding when + /// [enforceSmartPing] is true. True when the field is + /// missing or anything other than false / 0. + bool get apiSmartPingFloodOnly => _apiSmartPingFloodOnly; + + /// Whether the last live auth carried the `scope_discovery` key at all. + /// The key's PRESENCE is the gate: a server that predates the feature never + /// sends it, and the app must never ask a repeater for its scopes without + /// it, whatever the user's own switch says. + bool get scopeDiscoveryOffered => _scopeDiscoveryOffered; + + /// Whether scope discovery is forced on by the regional admin. + bool get enforceScopeDiscovery => _enforceScopeDiscovery; + + /// The scope discovery refresh window (days) the server sent; only binding + /// when [enforceScopeDiscovery] is true. 14 when the field is missing or + /// non-numeric, floored at 7. + int get apiScopeRefreshDays => _apiScopeRefreshDays; + /// Every CARpeater key the region shares, replaced in full on every auth. /// Upper-case 64 hex, sorted. Empty when the server sent none or predates /// the feature. @@ -223,10 +270,12 @@ class ApiService { http.Client? client, NetworkStateSource? networkState, Duration deviceCatalogTimeout = const Duration(seconds: 10), + Duration borderTimeout = const Duration(seconds: 60), DateTime Function()? now, }) : _client = client ?? http.Client(), _networkState = networkState ?? NetworkStateService.instance, _deviceCatalogTimeout = deviceCatalogTimeout, + _borderTimeout = borderTimeout, _now = now ?? DateTime.now; /// Fetches the public model catalog without affecting session callbacks. @@ -337,22 +386,29 @@ class ApiService { /// /// The per-attempt timeout lives at the call site, so the replay gets its /// own full allowance rather than the remains of the first one's. + /// + /// [prepareReplay], when given, is asked for the replay at the moment it is + /// about to go out, so a caller whose body depends on state that may have + /// changed while the first attempt was failing can rebuild it. Returning + /// null skips the replay and rethrows the first attempt's error. Future _send( String label, Future Function() request, { DateTime? deadline, + Future Function()? Function()? prepareReplay, }) async { - Future sendAttempt() { - if (deadline == null) return request(); + Future sendAttempt(Future Function() send) { + if (deadline == null) return send(); final remaining = deadline.difference(_now()); if (remaining <= Duration.zero) { throw TimeoutException('$label deadline expired'); } - return request().timeout(remaining); + return send().timeout(remaining); } - Future completeWithinDeadline() async { - final response = await sendAttempt(); + Future completeWithinDeadline( + Future Function() send) async { + final response = await sendAttempt(send); if (deadline != null && !_now().isBefore(deadline)) { throw TimeoutException('$label deadline expired'); } @@ -360,15 +416,21 @@ class ApiService { } try { - return await completeWithinDeadline(); + return await completeWithinDeadline(request); } catch (e) { if (!_connectionWasAlreadyClosed(e)) rethrow; if (deadline != null && !_now().isBefore(deadline)) { throw TimeoutException('$label deadline expired'); } + final replay = prepareReplay == null ? request : prepareReplay(); + if (replay == null) { + debugWarn('[API] $label found the connection already closed by the ' + 'server, nothing left to send again'); + rethrow; + } debugWarn('[API] $label found the connection already closed by the ' 'server, sending it again'); - return completeWithinDeadline(); + return completeWithinDeadline(replay); } } @@ -530,6 +592,7 @@ class ApiService { required double lon, required double accuracyMeters, required String appVersion, + String? radioFreq, }) async { final stopwatch = Stopwatch()..start(); try { @@ -541,6 +604,9 @@ class ApiService { 'ver': appVersion, 'timestamp': timestamp, 'key': apiKey, + // The radio preset picks which of the zone's preset rows answers + // slots_max and flood_disabled. Without it the server uses the `*` row. + if (radioFreq != null) 'radio_freq': radioFreq, }; final response = await _send( @@ -593,10 +659,22 @@ class ApiService { /// Fetch regional boundary polygons from the MeshMapper API. /// - /// Returns a list of `{code, polygon}` maps where `polygon` is a list of - /// `[lat, lon]` pairs (as sent by the server). Returns `null` on failure - /// or maintenance mode. - Future>?> fetchBorderPolygons({ + /// Returns the `{code, polygon}` maps (`polygon` is a list of `[lat, lon]` + /// pairs as sent by the server) with the body's `border_hash`, which the + /// server sends only on a complete answer. Returns `null` on failure, on + /// maintenance mode and on the HTTP 503 `border_unavailable` answer (a + /// polygon the server could not read; see docs/APP_API.md in + /// MeshMapper_Server). + /// + /// A group's answer can be megabytes, so each attempt gets a long + /// allowance and is aborted when it runs out. A plain Future timeout would + /// leave the body downloading in the background, and the next zone check + /// would start another one on top of it. The returned future only + /// completes once the request has really ended. An abort is never sent + /// again; the one replay [_send] makes (the server closed a reused + /// connection before any header) gets its own allowance, so the call can + /// take up to twice [_borderTimeout]. + Future fetchBorderPolygons({ required double lat, required double lon, required String appVersion, @@ -612,15 +690,29 @@ class ApiService { 'key': apiKey, }; + Future post() async { + final abort = Completer(); + final abortTimer = Timer(_borderTimeout, () { + if (!abort.isCompleted) abort.complete(); + }); + try { + final request = http.AbortableRequest('POST', Uri.parse(borderUrl), + abortTrigger: abort.future) + ..headers['Content-Type'] = 'application/json' + ..body = json.encode(payload); + final streamed = await _client.send(request); + return await http.Response.fromStream(streamed); + } finally { + abortTimer.cancel(); + } + } + + // The abort ends an attempt at _borderTimeout. The outer timeout is + // only a backstop for a client that ignores the abort trigger, so the + // caller's in-flight guard can never stay set forever. final response = await _send( 'POST /wardrive-api.php/border', - () => _client - .post( - Uri.parse(borderUrl), - headers: {'Content-Type': 'application/json'}, - body: json.encode(payload), - ) - .timeout(const Duration(seconds: 10)), + () => post().timeout(_borderTimeout + const Duration(seconds: 15)), ); stopwatch.stop(); @@ -652,17 +744,30 @@ class ApiService { if (data == null) return null; if (_checkMaintenanceMode(data)) return null; + if (response.statusCode != 200 || data['success'] == false) { + // 503 border_unavailable among them: never shown, never saved. + return null; + } final polygons = data['polygons']; if (polygons is! List) return null; - - return polygons - .whereType() - .map((p) => Map.from(p)) - .toList(); + final hash = data['border_hash']; + + return BorderAnswer( + polygons + .whereType() + .map((p) => Map.from(p)) + .toList(), + borderHash: hash is String && hash.isNotEmpty ? hash : null, + ); } catch (e) { stopwatch.stop(); - debugError('[BORDER] POST /wardrive-api.php/border failed: $e'); + if (e is http.RequestAbortedException) { + debugError('[BORDER] POST /wardrive-api.php/border aborted after ' + '${_borderTimeout.inSeconds}s'); + } else { + debugError('[BORDER] POST /wardrive-api.php/border failed: $e'); + } return null; } } @@ -676,6 +781,7 @@ class ApiService { /// @param offlineMode Set to true when uploading offline session data /// @param skipSessionStore When true, does not write to shared _sessionId/_txAllowed/etc. Caller manages session locally. /// @param sessionId Explicit session ID for disconnect. When provided, disconnect uses this instead of _sessionId and skips _clearSession(). + /// @param keepPolicy On a disconnect release that a connect for the same radio follows at once (a group handoff): clear the session itself but keep the zone policy the UI reads, see [_clearSession]. /// @returns Map with success, session_id, tx_allowed, rx_allowed, expires_at, reason, message Future?> requestAuth({ required String reason, @@ -695,6 +801,7 @@ class ApiService { bool Function()? shouldStoreSession, String? sessionId, Map? extras, + bool keepPolicy = false, }) async { final stopwatch = Stopwatch()..start(); try { @@ -822,6 +929,10 @@ class ApiService { // upload, so tell the listener to drop those pings. final previousSessionId = _sessionId; final newSessionId = data['session_id'] as String?; + // A withdrawal of scope discovery takes effect before anything is + // awaited: a lookup already out could otherwise complete and send + // its scope request while the queue cleanup below runs. + _applyScopeDiscovery(data, withdrawOnly: true); if (previousSessionId != null && newSessionId != null && previousSessionId != newSessionId) { @@ -926,9 +1037,25 @@ class ApiService { (smartDays is int && smartDays >= 1 && smartDays <= 365) ? smartDays : 14; + final floodOnly = data['smart_ping_flood_only']; + _apiSmartPingFloodOnly = !(floodOnly == false || floodOnly == 0); if (_enforceSmartPing) { debugLog( - '[API] Regional admin enforces smart pinging: $_apiSmartPingDays day window'); + '[API] Regional admin enforces smart pinging: $_apiSmartPingDays day window, ' + '${_apiSmartPingFloodOnly ? 'flood only' : 'all pings'}'); + } + + // Scope discovery (APP_API.md). The key's PRESENCE is the gate: a + // server that predates the feature would store a SCOPES item as a + // TX row. + _applyScopeDiscovery(data); + final sdDays = data['scope_refresh_days']; + _apiScopeRefreshDays = sdDays is num && sdDays.isFinite + ? (sdDays.toInt() < 7 ? 7 : sdDays.toInt()) + : 14; + if (_enforceScopeDiscovery) { + debugLog( + '[SCOPES] Regional admin enforces scope discovery: $_apiScopeRefreshDays day window'); } // Note: Heartbeat is enabled by AppStateProvider when auto mode starts @@ -969,8 +1096,17 @@ class ApiService { } else if (reason == 'disconnect') { // Only clear shared session when no explicit sessionId was provided // (explicit sessionId means caller manages its own session lifecycle) + // A release only forgets the session it released. A new session + // stored while this POST was out (a reconnect's connect auth landing + // inside a handoff's release) must not be nulled by the old one's + // answer. if (sessionId == null) { - _clearSession(); + if (_sessionId == null || _sessionId == payload['session_id']) { + _clearSession(keepPolicy: keepPolicy); + } else { + debugLog('[API] Release answered for a session already replaced, ' + 'keeping the new one'); + } } } @@ -1035,6 +1171,14 @@ class ApiService { 'holding every wardrive send for ${wait.inSeconds}s'); } + int _lastUploadDroppedScopes = 0; + + /// How many SCOPES items the last [submitWardriveData] call left out of + /// its replay because scope discovery was withdrawn while the first + /// attempt was failing. Zero when nothing was left out. The queue reads it + /// after a success so it counts only what the server actually received. + int get lastUploadDroppedScopes => _lastUploadDroppedScopes; + /// Submit wardrive data batch to API /// Matches submitWardriveData() in wardrive.js /// @@ -1045,6 +1189,7 @@ class ApiService { /// that apart from a rejection and hold the data without spending a retry Future?> submitWardriveData( List> entries) async { + _lastUploadDroppedScopes = 0; if (_sessionId == null) { throw Exception('Cannot submit: no session_id'); } @@ -1059,15 +1204,33 @@ class ApiService { if (autoMode != null) 'auto_mode': autoMode, }; + Future post(Map body) => _client + .post( + Uri.parse(wardriveEndpoint), + headers: {'Content-Type': 'application/json'}, + body: json.encode(body), + ) + .timeout(const Duration(seconds: 30)); + final response = await _send( 'POST /wardrive-api.php/wardrive', - () => _client - .post( - Uri.parse(wardriveEndpoint), - headers: {'Content-Type': 'application/json'}, - body: json.encode(payload), - ) - .timeout(const Duration(seconds: 30)), + () => post(payload), + // The queue only let SCOPES into this batch because scope discovery + // was offered when it built it. A live auth can withdraw that while + // the first attempt is failing on a dead socket, so the replay reads + // the gate again and leaves the answers out once it has closed. + prepareReplay: () { + if (_scopeDiscoveryOffered) return () => post(payload); + final kept = + entries.where((e) => e['type'] != 'SCOPES').toList(); + if (kept.length == entries.length) return () => post(payload); + _lastUploadDroppedScopes = entries.length - kept.length; + debugWarn('[API] Replay drops ${entries.length - kept.length} ' + 'SCOPES item(s): scope discovery withdrawn since the batch ' + 'was built'); + if (kept.isEmpty) return null; + return () => post({...payload, 'data': kept}); + }, ); stopwatch.stop(); @@ -1106,6 +1269,7 @@ class ApiService { request: { 'data': '${entries.length} items', 'items': antennaSummary, + 'altitude': altitudeLabelSummary(entries), if (autoMode != null) 'auto_mode': autoMode, }, response: data, @@ -1500,6 +1664,10 @@ class ApiService { _heartbeatInFlight = true; _lastHeartbeatSentAt = now; + // The session this keepalive speaks for. A manual action can recover to a + // replacement session while this send is still in flight, and the late + // answer about the old one must not cancel or retry the new one's lane. + final sentSessionId = _sessionId; Map? result; try { // Get GPS coordinates from provider (matching wardrive.js behavior) @@ -1509,6 +1677,12 @@ class ApiService { _heartbeatInFlight = false; } + if (result?['success'] != true && _sessionId != sentSessionId) { + debugLog('[HEARTBEAT] Ignoring a failed keepalive for a session that ' + 'has since been replaced'); + return; + } + if (result?['success'] == true) { debugLog('[HEARTBEAT] Heartbeat successful'); // Reset retry state on success @@ -1549,6 +1723,26 @@ class ApiService { 'zone_disabled', }; + // An idle app (no mode running or stopping, no ping in flight, nothing + // queued) has no use for a fresh session. This is the Android case + // where a stopped mode lets the process freeze in the background, the + // keepalive never fires, and the overdue one comes back expired on + // resume: recovering here minted a session that never saw a ping. Stop + // the keepalive instead and leave the session lapsed. The next Start or + // manual ping runs checkSessionValid, which posts its own heartbeat, + // gets the same session_expired and recovers there. The enabled flag is + // kept so that recovery reschedules the keepalive for the new session. + if (reason == 'session_expired' && (isSessionIdle?.call() ?? false)) { + debugLog('[HEARTBEAT] Session lapsed while idle, stopping the ' + 'keepalive; the next ping or mode start will refresh it'); + _heartbeatTimer?.cancel(); + _heartbeatTimer = null; + _heartbeatRetryTimer?.cancel(); + _heartbeatRetryTimer = null; + _heartbeatRetryCount = 0; + return; + } + final recovery = reason == 'session_expired' ? await _recoverExpiredSession() : null; if (recovery == SessionRecoveryResult.recovered) { @@ -1583,31 +1777,57 @@ class ApiService { } /// Clear session data and cancel all timers - void _clearSession() { + /// Forgets the session. With [keepPolicy] only the session itself goes + /// (id, wire key, counter, expiry, storm-brake hold, keepalive timers) and + /// the zone policy stays: `txAllowed`, `rxAllowed`, the channels and + /// scopes, the enforce flags, the minimum interval, the hop width, the + /// Smart Pinging and scope discovery terms. A group handoff releases with + /// that and mints again at once; the connect branch overwrites every one of + /// those fields on success, so nothing stale can outlive the mint, and the + /// UI (the ping buttons, the status bar, the Smart Pinging lookup) does not + /// read the release-to-mint gap as "Passive only" with no session. + void _clearSession({bool keepPolicy = false}) { _sessionId = null; _wireKey = null; _pingCounter = 0; - _txAllowed = false; - _rxAllowed = false; _sessionExpiresAt = null; - _channels = []; - _scopes = []; - _enforceHybrid = false; - _enforceDiscDrop = false; - _floodDisabled = false; - _minModeInterval = 15; - _apiHopBytes = 1; - _enforceSmartPing = false; - _apiSmartPingDays = 14; + if (!keepPolicy) { + _txAllowed = false; + _rxAllowed = false; + _channels = []; + _scopes = []; + _enforceHybrid = false; + _enforceDiscDrop = false; + _floodDisabled = false; + _minModeInterval = 15; + _apiHopBytes = 1; + _enforceSmartPing = false; + _apiSmartPingDays = 14; + _apiSmartPingFloodOnly = true; + final scopeWasOffered = _scopeDiscoveryOffered; + final scopeWasEnforced = _enforceScopeDiscovery; + _scopeDiscoveryOffered = false; + _enforceScopeDiscovery = false; + _apiScopeRefreshDays = 14; + if (scopeWasOffered || scopeWasEnforced) onScopeDiscoveryChanged?.call(); + } _heartbeatTimer?.cancel(); _heartbeatTimer = null; _heartbeatRetryTimer?.cancel(); _heartbeatRetryTimer = null; _heartbeatRetryCount = 0; _wardriveBlockedUntil = null; - debugLog('[API] Session cleared'); + debugLog(keepPolicy + ? '[API] Session cleared, zone policy kept for the mint' + : '[API] Session cleared'); } + /// Forgets the session and its zone policy in full. For a caller that + /// released with `keepPolicy` and then could not mint: with no session to + /// follow, the kept policy would otherwise outlive the session it came + /// with. + void clearSession() => _clearSession(); + /// Legacy: Check if we have a slot (compatibility with old code) bool get hasSlot => hasSession; @@ -1616,6 +1836,13 @@ class ApiService { /// decides whether its connection state still permits recovery. Future Function()? onSessionExpiredRecovery; + /// True when nothing would use a refreshed session right now: no auto mode + /// running or stopping, no ping in flight, nothing queued for upload. Read + /// only by the scheduled keepalive, which then lets an expired session lapse + /// instead of re-minting one (see [_sendScheduledHeartbeat]). Every action + /// path still recovers through [checkSessionValid] or the upload door. + bool Function()? isSessionIdle; + /// Callback for session errors (session_expired, bad_session, outside_zone) /// Set by AppStateProvider to handle auto-disconnect /// @@ -1628,6 +1855,32 @@ class ApiService { /// Callback for maintenance mode detection (while connected) void Function(String message, String? url)? onMaintenanceMode; + /// Reads `scope_discovery` from a live auth answer and fires + /// [onScopeDiscoveryChanged] when either flag changes. With [withdrawOnly] + /// only a withdrawal is applied (offered or enforced going false), never a + /// grant: it runs before the answer's session is known to be stored, so a + /// stale answer can only ever switch scope work off. + void _applyScopeDiscovery(Map data, + {bool withdrawOnly = false}) { + final offered = data.containsKey('scope_discovery'); + final sd = data['scope_discovery']; + final enforced = sd == true || sd == 1; + final wasOffered = _scopeDiscoveryOffered; + final wasEnforced = _enforceScopeDiscovery; + _scopeDiscoveryOffered = withdrawOnly ? wasOffered && offered : offered; + _enforceScopeDiscovery = withdrawOnly ? wasEnforced && enforced : enforced; + if (wasOffered != _scopeDiscoveryOffered || + wasEnforced != _enforceScopeDiscovery) { + onScopeDiscoveryChanged?.call(); + } + } + + /// Fired synchronously whenever [scopeDiscoveryOffered] or + /// [enforceScopeDiscovery] changes (a live `/auth` answer, or the session + /// being cleared), so scope work the server just withdrew stops before its + /// next write to the radio. + void Function()? onScopeDiscoveryChanged; + /// Fired when /auth returns a session id different from the one we held. /// Wired to ApiQueueService.dropStaleTaggedItems(). See that method for why. Future Function(String previousSessionId, String newSessionId)? @@ -1693,7 +1946,11 @@ class ApiService { /// 304 retains this verdict; it does not mean the render was unchanged. /// `body`: the uncompressed MVT bytes on a 200, null otherwise (204 = tile /// is empty; package:http has already gunzipped the response). - Future<({bool? changed, Uint8List? body})> freshenVectorTile({ + /// `noVerdictReason`: why `changed` is null (`header absent`, `HTTP ` + /// or `request failed`); null whenever a verdict came back. An absent + /// header is the normal answer for an on-demand render, not a failure. + Future<({bool? changed, Uint8List? body, String? noVerdictReason})> + freshenVectorTile({ required String zone, required int z, required int x, @@ -1705,7 +1962,7 @@ class ApiService { '${recentDays == null ? '' : '&f_days=$recentDays'}'; final url = Uri.parse('https://${zone.toLowerCase()}.meshmapper.net/vector_tile.php' - '?z=$z&x=$x&y=$y&gsize=$gsize&fresh=1$filter'); + '?z=$z&x=$x&y=$y&gsize=$gsize&cf=$kCoverageTileFormat&fresh=1$filter'); final verdictOnly = z >= 11 && z <= 13; final sw = Stopwatch()..start(); // No GET line here: the response and failure lines below both name the @@ -1727,17 +1984,22 @@ class ApiService { if (response.statusCode != 200 && response.statusCode != 204 && !(verdictOnly && response.statusCode == 304)) { - return (changed: null, body: null); + return ( + changed: null, + body: null, + noVerdictReason: 'HTTP ${response.statusCode}', + ); } final body = response.statusCode == 200 ? response.bodyBytes : null; return ( changed: changed == null ? null : changed == '1', body: body, + noVerdictReason: changed == null ? 'header absent' : null, ); } catch (e) { debugWarn( '[API] Tile $z/$x/$y (zone ${zone.toLowerCase()}) fresh fetch failed in ${(sw.elapsedMilliseconds / 1000).toStringAsFixed(2)}s: $e'); - return (changed: null, body: null); + return (changed: null, body: null, noVerdictReason: 'request failed'); } } @@ -1765,13 +2027,14 @@ class ApiService { 'x': '$x', 'y': '$y', 'gsize': '$gsize', + 'cf': '$kCoverageTileFormat', 'f_days': '$days', 'f_types': 'green,cyan', ...filter, }); final sw = Stopwatch()..start(); debugLog( - '[COVERAGE] GET /vector_tile.php?z=$z&x=$x&y=$y&gsize=$gsize&f_days=$days&f_types=green,cyan${_radioFilterSuffix()} (zone ${zone.toLowerCase()})'); + '[COVERAGE] GET /vector_tile.php?z=$z&x=$x&y=$y&gsize=$gsize&cf=$kCoverageTileFormat&f_days=$days&f_types=green,cyan${_radioFilterSuffix()} (zone ${zone.toLowerCase()})'); try { final response = await _send( 'GET /vector_tile.php?z=$z&x=$x&y=$y (recent coverage)', @@ -1814,6 +2077,9 @@ class ApiService { } try { + // The session this batch is sent under (submitWardriveData reads the + // same field before its first await). + final sentSessionId = _sessionId; final result = await submitWardriveData(pings); if (result == null) { @@ -1834,6 +2100,17 @@ class ApiService { // Check for session errors that require disconnect final reason = result['reason'] as String?; + // A refusal for a session this service no longer holds (released by a + // Disconnect, or replaced by a reconnect or recovery while the POST was + // out) says nothing about the current one. Acting on it cleared a fresh + // session and tore down the new connection. Same rule as the release + // answer: only the session it was about is forgotten. + if (_sessionId != sentSessionId) { + debugLog('[API] Upload batch refused ($reason) for a session already ' + 'released or replaced, ignoring'); + return UploadResult.held; + } + // All errors that require session invalidation and disconnect const criticalErrors = { // Session errors @@ -1907,18 +2184,24 @@ class ApiService { } /// Fetch repeaters for a zone from the MeshMapper API - /// Returns a list of enabled repeaters for the given IATA zone code + /// Uses the build-time App key even before a session exists. Throws on + /// failure so callers can preserve a still-valid list. Failed reads are + /// held per host for a minute, or the server's Retry-After on a 429. Future> fetchRepeaters(String iata) async { final stopwatch = Stopwatch()..start(); const endpoint = '/get_repeaters.php'; + final host = '${iata.toLowerCase()}.meshmapper.net'; + final hold = _repeaterReadHolds[host]; + if (hold != null && _now().isBefore(hold.until)) throw hold.failure; + _repeaterReadHolds.remove(host); try { final filter = _radioFilterParams(); - final url = Uri.https('${iata.toLowerCase()}.meshmapper.net', endpoint, - filter.isEmpty ? null : filter); + final url = Uri.https(host, endpoint, filter.isEmpty ? null : filter); final response = await _send( 'GET $endpoint', - () => _client.get(url).timeout(const Duration(seconds: 15)), + () => _client.get(url, headers: const {'X-API-Key': apiKey}).timeout( + const Duration(seconds: 15)), ); stopwatch.stop(); @@ -1931,7 +2214,15 @@ class ApiService { statusCode: response.statusCode, response: 'error', ); - return []; + final failure = RepeaterFetchException(response.statusCode); + final until = _now().add(response.statusCode == 429 + ? parseRetryAfter(response.headers['retry-after']) + : const Duration(minutes: 1)); + final existing = _repeaterReadHolds[host]; + if (existing == null || until.isAfter(existing.until)) { + _repeaterReadHolds[host] = (until: until, failure: failure); + } + throw failure; } final List jsonList = @@ -1961,8 +2252,16 @@ class ApiService { return repeaters; } catch (e) { stopwatch.stop(); - debugError('[API] GET $endpoint failed: $e'); - return []; + final failure = + e is RepeaterFetchException ? e : const RepeaterFetchException(); + _repeaterReadHolds.putIfAbsent( + host, + () => ( + until: _now().add(const Duration(minutes: 1)), + failure: failure, + )); + debugError('[API] GET $endpoint failed: $failure'); + throw failure; } } @@ -2130,7 +2429,11 @@ class ApiService { method: 'POST', stopwatch: stopwatch, statusCode: response.statusCode, - request: {'data': '${entries.length} items', 'items': antennaSummary}, + request: { + 'data': '${entries.length} items', + 'items': antennaSummary, + 'altitude': altitudeLabelSummary(entries), + }, response: data, ); diff --git a/lib/services/app_intents/app_intent_bridge_service.dart b/lib/services/app_intents/app_intent_bridge_service.dart index 1a413b8b..261fee52 100644 --- a/lib/services/app_intents/app_intent_bridge_service.dart +++ b/lib/services/app_intents/app_intent_bridge_service.dart @@ -90,19 +90,34 @@ class AppIntentBridgeService { return _refusal('Malformed command').toMap(); } + final shortId = + command.id.length > 8 ? command.id.substring(0, 8) : command.id; final previous = _commandOutcomes[command.id]; - if (previous != null) return previous.toMap(commandId: command.id); + if (previous != null) { + debugLog('[SIRI] ${command.kind.name} $shortId: repeat delivery, ' + 'returning the earlier answer'); + return previous.toMap(commandId: command.id); + } final inFlight = _inFlightCommands[command.id]; if (inFlight != null) { + debugLog('[SIRI] ${command.kind.name} $shortId: repeat delivery, ' + 'joining the one in flight'); final completion = await inFlight; return completion.toMap(commandId: command.id); } final handler = _commandHandler; if (handler == null) { + debugWarn('[SIRI] ${command.kind.name} $shortId: refused, no handler ' + 'attached yet'); return _refusal('App not ready').toMap(commandId: command.id); } + final received = DateTime.now(); + final budget = command.expiresAt?.difference(received).inMilliseconds; + debugLog('[SIRI] ${command.kind.name} $shortId: received, ' + '${budget == null ? 'no deadline' : '${budget}ms to answer'}'); + // Normalize handler failures inside the shared future so every concurrent // delivery of this UUID receives the same refusal instead of the owner // catching an error while a duplicate sees a PlatformException. @@ -111,6 +126,9 @@ class AppIntentBridgeService { try { final completion = await execution; _remember(command.id, completion); + debugLog('[SIRI] ${command.kind.name} $shortId: answered in ' + '${DateTime.now().difference(received).inMilliseconds}ms, ' + '${completion.disposition.name} success=${completion.success}'); return completion.toMap(commandId: command.id); } finally { if (identical(_inFlightCommands[command.id], execution)) { diff --git a/lib/services/app_intents/last_companion_connection.dart b/lib/services/app_intents/last_companion_connection.dart index c1e40023..083fa3a8 100644 --- a/lib/services/app_intents/last_companion_connection.dart +++ b/lib/services/app_intents/last_companion_connection.dart @@ -69,3 +69,28 @@ ExternalCommandAdmission resolveLastCompanionConnection({ disposition: ExternalCommandDisposition.admitted, ); } + +/// Longest the connect intent waits for the dial to finish before answering. +/// +/// A reachable radio connects in 4 to 7 seconds (measured on device), so this +/// covers the ordinary case with room to spare. An unreachable one would run +/// three 15 second BLE attempts, far past iOS's 30 second limit on the intent, +/// so past this point the intent answers "connecting" and the dial carries on. +const Duration lastCompanionQuickAnswer = Duration(seconds: 12); + +/// Kept clear of the intent's own deadline so the answer reaches native code +/// before it stops waiting. +const Duration lastCompanionAnswerMargin = Duration(seconds: 3); + +/// How long to wait for the reconnect before answering that it is underway. +/// +/// [lastCompanionQuickAnswer], shortened when the intent's deadline is closer +/// than that plus [lastCompanionAnswerMargin] (a cold launch spends part of the +/// budget before the command arrives). Never negative. +Duration lastCompanionAnswerWindow(DateTime? expiresAt, {DateTime? now}) { + if (expiresAt == null) return lastCompanionQuickAnswer; + final left = expiresAt.difference(now ?? DateTime.now()) - + lastCompanionAnswerMargin; + if (left <= Duration.zero) return Duration.zero; + return left < lastCompanionQuickAnswer ? left : lastCompanionQuickAnswer; +} diff --git a/lib/services/app_intents/siri_snapshot_builder.dart b/lib/services/app_intents/siri_snapshot_builder.dart index 687345d4..94c0392e 100644 --- a/lib/services/app_intents/siri_snapshot_builder.dart +++ b/lib/services/app_intents/siri_snapshot_builder.dart @@ -1,5 +1,6 @@ import '../../models/log_entry.dart'; import '../../models/repeater.dart'; +import '../../utils/repeater_nicknames.dart'; import '../external_surfaces/geo/external_surface_geo_builder.dart'; import '../watch/watch_models.dart'; import 'siri_snapshot_models.dart'; @@ -34,6 +35,7 @@ class SiriSnapshotBuilder { required List repeaters, int? hopBytes, DateTime? now, + Map nicknames = const {}, }) { final cutoff = (now ?? DateTime.now()).subtract(maximumObservationAge); final candidates = <_SiriObservationCandidate>[]; @@ -44,18 +46,12 @@ class SiriSnapshotBuilder { Repeater? lookup(_SiriObservationCandidate candidate) { final cacheKey = _identityKey(candidate); if (repeaterCache.containsKey(cacheKey)) return repeaterCache[cacheKey]; - final found = (candidate.identity == null - ? null - : ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: repeaters, - id: candidate.identity!, - hopBytes: hopBytes, - )) ?? - ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: repeaters, - id: candidate.displayId.toUpperCase(), - hopBytes: hopBytes, - ); + final found = ExternalSurfaceGeoBuilder.resolveOverlayRow( + displayId: candidate.displayId, + identity: candidate.identity, + repeaters: repeaters, + hopBytes: hopBytes, + ); repeaterCache[cacheKey] = found; return found; } @@ -73,7 +69,13 @@ class SiriSnapshotBuilder { return SiriRepeaterObservation( entityId: resolved ? repeaterEntityId(repeater) : null, displayHexId: normalizedId, - name: resolved && repeater.name != 'Unknown' ? repeater.name : null, + // The user's nickname for the resolved repeater outranks the server's + // name. Only the observations carry it: the Shortcuts catalogue keeps + // server names. + name: (resolved + ? RepeaterNicknames.nicknameFor(repeater, nicknames) + : null) ?? + (resolved && repeater.name != 'Unknown' ? repeater.name : null), observedAt: candidate.observedAt, kind: candidate.kind, direct: candidate.direct, @@ -263,18 +265,12 @@ class SiriSnapshotBuilder { required int? hopBytes, }) { if (heardRepeaters.isEmpty) return null; - final match = (candidate.identity == null - ? null - : ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: heardRepeaters, - id: candidate.identity!, - hopBytes: hopBytes, - )) ?? - ExternalSurfaceGeoBuilder.resolveRepeater( - repeaters: heardRepeaters, - id: candidate.displayId.toUpperCase(), - hopBytes: hopBytes, - ); + final match = ExternalSurfaceGeoBuilder.resolveOverlayRow( + displayId: candidate.displayId, + identity: candidate.identity, + repeaters: heardRepeaters, + hopBytes: hopBytes, + ); return match == null ? null : repeaterEntityId(match); } diff --git a/lib/services/background_location_policy.dart b/lib/services/background_location_policy.dart new file mode 100644 index 00000000..598dd2e7 --- /dev/null +++ b/lib/services/background_location_policy.dart @@ -0,0 +1,129 @@ +/// When GPS and Android's background session service may run. +/// +/// Location is collected in the background only while a radio session is live. +/// A session is live from the Connect tap until cleanup finishes, which covers +/// connecting, connected, disconnecting, auto-reconnecting and a pending +/// connect re-run. Outside a session, a backgrounded app collects nothing. +/// +/// | | App on screen | App in background | +/// |----------------------|--------------------|----------------------------------| +/// | No radio session | GPS on (unchanged) | GPS off | +/// | Radio session live | GPS on | GPS on (see the platform note) | +/// +/// On Android the background GPS runs under the session service, which keeps +/// the process alive. On iOS an already-running stream is kept, but GPS is +/// never started in the background: a stream started there stays quiet, so +/// the status never reaches `GpsStatus.locked`, which `canPing` needs. +/// +/// Pure, so the whole table is checkable without a device. +library; + +import 'dart:ui' show AppLifecycleState; + +import '../models/connection_state.dart'; + +/// True while a radio session is live: every step except +/// [ConnectionStep.disconnected] and [ConnectionStep.error], or whenever a +/// reconnect or a pending connect re-run is in flight. +/// +/// The flags matter because both run while [step] reads `disconnected`, yet +/// the session is not over. +bool radioSessionActive({ + required ConnectionStep step, + required bool autoReconnecting, + required bool connectRerunPending, +}) { + if (autoReconnecting || connectRerunPending) return true; + return step != ConnectionStep.disconnected && step != ConnectionStep.error; +} + +/// What a lifecycle change should do to the GPS stream. +/// +/// [keep] means leave it as it is: `inactive` is a transient state (a system +/// dialog, the app switcher) and must not tear GPS down or start it. +enum GpsRunDecision { run, stop, keep } + +/// Decides what the GPS stream should do for the current [lifecycle]. +/// +/// Checked in order: a resumed app always runs; a live radio session runs on +/// Android and only keeps on iOS (see the library comment); then a backgrounded +/// app stops; anything else, `inactive` or an unknown lifecycle, keeps. +GpsRunDecision gpsRunDecision({ + required AppLifecycleState? lifecycle, + required bool radioActive, + required bool isIos, +}) { + if (lifecycle == AppLifecycleState.resumed) return GpsRunDecision.run; + if (radioActive) return isIos ? GpsRunDecision.keep : GpsRunDecision.run; + switch (lifecycle) { + case AppLifecycleState.paused: + case AppLifecycleState.hidden: + case AppLifecycleState.detached: + return GpsRunDecision.stop; + case AppLifecycleState.resumed: + case AppLifecycleState.inactive: + case null: + return GpsRunDecision.keep; + } +} + +/// True when a GPS start asked for after a location permission check must +/// wait for the app to come on screen instead of running now. +/// +/// The startup permission check runs on every launch, including a background +/// launch (iOS waking the app with no radio), and a start there would send +/// the first fix to the zone check. Holding it leaves the first, full start to +/// the policy sync once the app is resumed. A grant read while a system dialog +/// still holds the app `inactive` waits the same way, for the resume that +/// follows. [keepTracking] marks the quiet restart that sync itself makes, +/// which only ever runs on a `run` decision, so it is never held. +/// [alreadyWatching] is never held either: holding marks GPS stopped by the +/// policy, and a stream that is running would read as stopped without being +/// stopped. +bool deferGpsStartAfterPermission({ + required bool keepTracking, + required bool alreadyWatching, + required bool policyApplies, + required GpsRunDecision decision, +}) => + !keepTracking && + !alreadyWatching && + policyApplies && + decision != GpsRunDecision.run; + +/// True when the Android session service should be started now. +/// +/// Every input must hold: the platform follows the connection +/// ([followsConnection]), the service is neither [running] nor [starting], a +/// radio session is live ([sessionActive]) and not already +/// [ConnectionStep.disconnecting], the app is on screen ([lifecycle] resumed, +/// because Android refuses to start a location service from the background), +/// and location permission is granted ([locationGranted]). +bool shouldStartConnectionService({ + required bool followsConnection, + required bool running, + required bool starting, + required bool sessionActive, + required ConnectionStep step, + required AppLifecycleState? lifecycle, + required bool locationGranted, +}) { + return followsConnection && + !running && + !starting && + sessionActive && + step != ConnectionStep.disconnecting && + lifecycle == AppLifecycleState.resumed && + locationGranted; +} + +/// True when the end of disconnect cleanup should stop the session service. +/// +/// A service that does not follow the connection always stops here. One that +/// does follow it stays up while another session (a reconnect or a re-run) is +/// still live. +bool shouldStopServiceAtCleanupEnd({ + required bool followsConnection, + required bool sessionActive, +}) => + !followsConnection || !sessionActive; diff --git a/lib/services/background_service.dart b/lib/services/background_service.dart index 02fbccbe..c42f76fc 100644 --- a/lib/services/background_service.dart +++ b/lib/services/background_service.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:ui'; import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; @@ -9,31 +10,66 @@ import '../utils/debug_logger_io.dart'; /// Background service manager for continuous wardriving operation. /// -/// Android: Uses a foreground service with persistent notification to keep -/// BLE and GPS active when the app is backgrounded. +/// Android: the app's own foreground service (MeshMapperSessionService.kt), +/// driven over the `meshmapper/session_service` channel. Its notification +/// keeps BLE and GPS running while the app is in the background. Android +/// decides a foreground service's while-in-use location access when it is +/// started, so a start is only worth sending while the app is on screen. It +/// stops when the app is swiped away (stopWithTask), and nothing restarts it: +/// no boot start and no restart timer. The flutter_background_service +/// plugin's Android service and receivers are removed from the manifest. /// -/// iOS: Uses declared background modes (bluetooth-central, location) with -/// proper delegate setup. iOS may still throttle after extended periods. +/// iOS: the flutter_background_service plugin, started and stopped per mode. +/// The declared background modes (bluetooth-central, location) do the real +/// work, and iOS may still throttle after extended periods. /// /// Web: No-op (Web Bluetooth requires active tab). -/// -/// Reference: Option A from background execution plan @pragma('vm:entry-point') class BackgroundServiceManager { static const String _notificationChannelId = 'meshmapper_wardriving'; - static const String _notificationChannelName = 'MeshMapper Wardriving'; static const int _notificationId = 888; + /// The Android session service (MeshMapperSessionService.kt). + static const MethodChannel _sessionChannel = + MethodChannel('meshmapper/session_service'); + static FlutterBackgroundService? _service; static bool _isInitialized = false; static bool _isRunning = false; - /// Initialize the background service. + /// Bumped by every [stopService] call, even one that finds nothing running. + /// A start captures it first and abandons itself when it moved, so a + /// disconnect that lands while a start is on its way cannot be followed by + /// that start marking the service running (or, on iOS, leaving one behind). + static int _stopGeneration = 0; + + /// Bumped by every Android start. The status check after a start only acts + /// if no other start or stop came after it. + static int _startGeneration = 0; + + /// The last content sent to the Android service, so a repeat is dropped. + /// Cleared by every start and stop. + static ({String title, String body, bool keepAwake})? _lastNotification; + + /// How often [waitUntilStopped] polls, and how long it waits at most. + static const Duration _stopPollInterval = Duration(milliseconds: 100); + static const Duration _stopWaitLimit = Duration(seconds: 2); + + /// How long after an Android start to ask the service whether it came up. + /// A start that fails inside the service (startForeground refused) is only + /// reported there, after the channel call has already answered. + static const Duration _startStatusDelay = Duration(milliseconds: 1500); + + /// True where the background service runs for the whole radio session + /// (Android, the app's own session service). False where it runs per mode + /// (iOS, the plugin) and on web. + static bool get followsConnection => + !kIsWeb && defaultTargetPlatform == TargetPlatform.android; + + /// Initialize the iOS background service. /// Called lazily on first startService() call — never at app startup. - /// On Android, configure() may start the foreground service as a side effect - /// (service resurrection), so this MUST only be called when we actually - /// intend to start the service. Startup orphan cleanup uses - /// cleanupOrphanedService() which cancels the notification directly. + /// Startup orphan cleanup uses cleanupOrphanedService(), which needs no + /// configure(). static Future initialize() async { // Skip on web - no background service support if (kIsWeb) { @@ -41,6 +77,9 @@ class BackgroundServiceManager { return; } + // Android runs the app's own session service, not the plugin's. + if (followsConnection) return; + if (_isInitialized) { debugLog('[BACKGROUND] Already initialized'); return; @@ -49,41 +88,21 @@ class BackgroundServiceManager { debugLog('[BACKGROUND] Initializing background service'); try { - // Initialize local notifications for Android - final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = - FlutterLocalNotificationsPlugin(); - - // Android notification channel setup - const AndroidNotificationChannel channel = AndroidNotificationChannel( - _notificationChannelId, - _notificationChannelName, - description: 'Shows wardriving status while app is in background', - importance: Importance.low, // Low importance = no sound/vibration - showBadge: false, - ); - - await flutterLocalNotificationsPlugin - .resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin>() - ?.createNotificationChannel(channel); - // Initialize the background service _service = FlutterBackgroundService(); await _service!.configure( + // configure() requires an Android configuration even though Android + // never runs the plugin's service. Both starts stay off explicitly. androidConfiguration: AndroidConfiguration( onStart: _onStart, - autoStart: false, // We'll start it manually when auto-mode is enabled + autoStart: false, + autoStartOnBoot: false, isForegroundMode: true, notificationChannelId: _notificationChannelId, initialNotificationTitle: 'MeshMapper', initialNotificationContent: 'Wardriving active', foregroundServiceNotificationId: _notificationId, - foregroundServiceTypes: [ - AndroidForegroundType.location, - AndroidForegroundType.connectedDevice, - AndroidForegroundType.dataSync, - ], ), iosConfiguration: IosConfiguration( autoStart: false, @@ -92,13 +111,16 @@ class BackgroundServiceManager { ), ); - // Defense-in-depth: configure() may unexpectedly start the service - // (e.g., Android resurrecting a previously-killed foreground service). + // Defense-in-depth: a service this session did not start may already + // be running. final isRunning = await _service!.isRunning(); if (isRunning) { debugLog( '[BACKGROUND] Service unexpectedly running after configure(), stopping it'); _service!.invoke('stop'); + // Wait for it to actually go, so its stop cannot land after the + // start that follows and take that one down with it. + await _awaitPendingStop(_service!, 'stale service after configure()'); } _isInitialized = true; @@ -109,20 +131,37 @@ class BackgroundServiceManager { } /// Start the background service. - /// Called when auto-ping mode (TX/RX or RX-only) is enabled. /// /// [title] and [body] are the finished notification strings. The caller - /// composes them (mode name and stats live on the app side); the background - /// isolate only displays what it is handed. + /// composes them (mode name and stats live on the app side); the service + /// only displays what it is handed. + /// + /// Android only: [keepAwake] holds a wake lock while the service runs, and + /// [mayStart], when given, is asked right before the start is sent, with no + /// await in between. A start it refuses sends nothing. A service that is + /// already running or starting only takes the new content. static Future startService({ required String title, required String body, + bool keepAwake = false, + bool Function()? mayStart, }) async { if (kIsWeb) { debugLog('[BACKGROUND] Cannot start service on web'); return; } + if (followsConnection) { + return _startSessionService( + title: title, + body: body, + keepAwake: keepAwake, + mayStart: mayStart, + ); + } + + final generation = _stopGeneration; + if (!_isInitialized) { debugLog('[BACKGROUND] Service not initialized, initializing now'); await initialize(); @@ -135,6 +174,12 @@ class BackgroundServiceManager { } try { + if (generation != _stopGeneration) { + debugLog('[BACKGROUND] Start abandoned: a stop arrived while it ' + 'was waiting'); + return; + } + debugLog('[BACKGROUND] Starting background service ($title)'); // Seed the title so the "Starting wardriving..." notification names the @@ -142,6 +187,11 @@ class BackgroundServiceManager { _service?.invoke('setInitialTitle', {'title': title}); await _service?.startService(); + if (generation != _stopGeneration) { + debugLog('[BACKGROUND] A stop arrived during the start, stopping it'); + _service?.invoke('stop'); + return; + } _isRunning = true; // Update notification with initial stats @@ -153,11 +203,176 @@ class BackgroundServiceManager { } } + static Future _startSessionService({ + required String title, + required String body, + required bool keepAwake, + required bool Function()? mayStart, + }) async { + // Asked here, synchronously before the channel call: Android only grants + // the service while-in-use location if the app is on screen at the + // start, and the app may have left it since the caller decided to start. + if (mayStart != null && !mayStart()) { + debugLog('[BACKGROUND] Start skipped: the caller no longer wants it'); + return; + } + + final startGeneration = ++_startGeneration; + final stopGeneration = _stopGeneration; + _lastNotification = null; + debugLog('[BACKGROUND] Starting background service ($title)'); + + try { + final reply = await _sessionChannel.invokeMapMethod( + 'start', + {'title': title, 'body': body, 'keepAwake': keepAwake}, + ); + if (reply?['started'] != true) { + debugError('[BACKGROUND] Failed to start service: ${reply?['error']}'); + return; + } + if (stopGeneration != _stopGeneration) { + // The stop already reached the service, which stops itself once it + // is up. Counting it running here would outlive that stop. + debugLog('[BACKGROUND] A stop arrived during the start'); + return; + } + _isRunning = true; + debugLog('[BACKGROUND] Background service started'); + unawaited(_checkStartStatus( + startGeneration: startGeneration, + stopGeneration: stopGeneration, + )); + } catch (e) { + debugError('[BACKGROUND] Failed to start service: $e'); + } + } + + /// Shortly after an Android start, ask the service whether it came up. The + /// channel answers a start before the service has tried startForeground, + /// so a refusal there (no location permission, started from the + /// background) only shows up here. Skipped when another start or stop came + /// since: the answer would describe that one instead. + static Future _checkStartStatus({ + required int startGeneration, + required int stopGeneration, + }) async { + bool superseded() => + startGeneration != _startGeneration || stopGeneration != _stopGeneration; + + await Future.delayed(_startStatusDelay); + if (superseded()) return; + final running = await _readStatus(); + if (running == null || superseded()) return; + if (!running) _isRunning = false; + } + + /// Ask the Android service whether it is running (or still starting). + /// Reading the status clears the service's last error, so the error is + /// logged here, whoever asked. Null when the channel call failed. + static Future _readStatus() async { + try { + final status = + await _sessionChannel.invokeMapMethod('status'); + if (status == null) return null; + final lastError = status['lastError']; + if (lastError != null) { + debugError('[BACKGROUND] Service failed to start: $lastError'); + } + return status['running'] == true; + } catch (e) { + debugWarn('[BACKGROUND] Could not read the service status: $e'); + return null; + } + } + + /// On return to the app (Android), bring the service in line with the + /// radio session. A service still running with no session left is stopped; + /// otherwise [isRunning] takes the service's own answer, so a service that + /// died in the background can be started again while the app is on screen. + static Future healAfterResume({required bool sessionActive}) async { + if (!followsConnection) return; + + final startGeneration = _startGeneration; + final stopGeneration = _stopGeneration; + final running = await _readStatus(); + if (running == null) return; + // A start or stop sent meanwhile is newer than this answer. + if (startGeneration != _startGeneration || + stopGeneration != _stopGeneration) { + return; + } + + if (running && !sessionActive) { + debugLog('[BACKGROUND] Service running with no radio session, ' + 'stopping it'); + await _stopSessionService(); + return; + } + _isRunning = running; + } + + /// Wait (bounded) for a service that was sent 'stop' to actually stop, and + /// log how long it took. Never throws. + static Future _awaitPendingStop( + FlutterBackgroundService service, + String what, + ) async { + final elapsed = await waitUntilStopped( + isRunning: service.isRunning, + pollInterval: _stopPollInterval, + timeout: _stopWaitLimit, + ); + if (elapsed == null) { + debugWarn('[BACKGROUND] $what still running after ' + '${_stopWaitLimit.inMilliseconds} ms, starting anyway'); + } else { + debugLog('[BACKGROUND] $what stopped after ${elapsed.inMilliseconds} ms'); + } + } + + /// Poll [isRunning] every [pollInterval] until it reports false, for at most + /// [timeout]. Returns how long that took, or null if it was still running + /// at the bound. A poll that throws counts as still running. + @visibleForTesting + static Future waitUntilStopped({ + required Future Function() isRunning, + Duration pollInterval = _stopPollInterval, + Duration timeout = _stopWaitLimit, + }) async { + final watch = Stopwatch()..start(); + while (true) { + bool running; + try { + running = await isRunning(); + } catch (e) { + debugWarn('[BACKGROUND] isRunning() check failed: $e'); + running = true; + } + if (!running) return watch.elapsed; + if (watch.elapsed >= timeout) return null; + await Future.delayed(pollInterval); + } + } + /// Stop the background service. /// Called when auto-ping mode is disabled or on disconnect. + /// + /// Android always sends the stop, even with nothing counted as running: a + /// start may still be on its way, and the service holds the stop until it + /// is up (stopping it before startForeground would crash the app). static Future stopService() async { if (kIsWeb) return; + if (followsConnection) { + await _stopSessionService(); + return; + } + + // Always, even with nothing running: a start may be waiting on + // initialize() and must not go ahead after this one. + _stopGeneration++; + if (!_isRunning) { debugLog('[BACKGROUND] Service not running'); return; @@ -173,13 +388,59 @@ class BackgroundServiceManager { } } + static Future _stopSessionService() async { + _stopGeneration++; + _isRunning = false; + _lastNotification = null; + debugLog('[BACKGROUND] Stopping background service'); + try { + await _sessionChannel.invokeMethod('stop'); + } catch (e) { + debugError('[BACKGROUND] Failed to stop service: $e'); + } + } + + /// Stop the Android service whoever started it, before the app closes + /// itself or at startup. On Android this is the same stop as + /// [stopService], which is always sent. A no-op elsewhere. + static Future stopLiveService(String what) async { + if (!followsConnection) return; + debugLog('[BACKGROUND] Stopping running service ($what)'); + await _stopSessionService(); + } + /// Update the notification with the current wardriving title and body. /// Called periodically to show TX/RX counts and queue size. + /// + /// Android drops an update identical to the last one sent, and sends one + /// even before a start has answered: the service keeps the latest content + /// and shows it once it is up. [keepAwake] is Android only. static Future updateNotification({ required String title, required String body, + bool keepAwake = false, }) async { - if (kIsWeb || !_isRunning) return; + if (kIsWeb) return; + + if (followsConnection) { + final content = (title: title, body: body, keepAwake: keepAwake); + if (content == _lastNotification) return; + _lastNotification = content; + try { + await _sessionChannel.invokeMethod('update', { + 'title': title, + 'body': body, + 'keepAwake': keepAwake, + }); + } catch (e) { + // Let the same content through again next time. + if (_lastNotification == content) _lastNotification = null; + debugError('[BACKGROUND] Failed to update notification: $e'); + } + return; + } + + if (!_isRunning) return; try { _service?.invoke('updateNotification', { @@ -191,28 +452,45 @@ class BackgroundServiceManager { } } - /// Check if the background service is running. + /// Check if the background service is running. On Android this counts a + /// start the service has accepted and not yet finished. static bool get isRunning => _isRunning; + /// Install a stand-in plugin service and reset the manager's state, so the + /// start and stop paths can be driven without the plugin. + @visibleForTesting + static void debugInstallService(FlutterBackgroundService? service) { + _service = service; + _isInitialized = service != null; + _isRunning = false; + _lastNotification = null; + // Moved on, not reset, so a status check still waiting from before finds + // itself superseded. + _stopGeneration++; + _startGeneration++; + } + /// Check if the background service is initialized. static bool get isInitialized => _isInitialized; - /// Clean up any orphaned foreground service from a previous app session. - /// On Android, the foreground service can survive app process death. - /// Call this at app startup to ensure no stale notification persists. + /// Clean up any orphaned service from a previous app session. Call this at + /// app startup, from a cold main(): the isolate that drove any earlier + /// service is gone, so a service running now is an orphan. /// - /// This intentionally does NOT call BackgroundService.configure()/initialize(), - /// because configure() with isForegroundMode:true can cause Android to - /// resurrect a killed foreground service as a side effect — producing a - /// phantom notification hours later (the "3am notification" bug). + /// Android: stops the session service. Its notification belongs to a + /// foreground service, which Android does not let the app cancel, only + /// stop. One can still be up here when the process outlived the engine + /// that started it. /// - /// We DO initialize the local-notifications plugin first: cancel() silently - /// no-ops until the plugin's platform channel is initialized, which is why - /// the orphaned notification kept reappearing after a reboot (#178). - /// Initializing the notifications plugin has no foreground-service side - /// effects — only configure() does. + /// iOS: cancels notification [_notificationId]. The local-notifications + /// plugin is initialized first: cancel() silently no-ops until its platform + /// channel is initialized. static Future cleanupOrphanedService() async { if (kIsWeb) return; + if (followsConnection) { + await stopLiveService('orphaned service'); + return; + } try { debugLog( '[BACKGROUND] Dismissing any orphaned notification from previous session'); @@ -234,7 +512,8 @@ class BackgroundServiceManager { } } - /// Called when the background service starts (Android). + /// Called when the plugin's service starts: iOS's onForeground. The + /// Android branches never run now that Android uses its own service. @pragma('vm:entry-point') static Future _onStart(ServiceInstance service) async { // Required for background execution @@ -274,6 +553,17 @@ class BackgroundServiceManager { title: currentTitle, content: 'Starting wardriving...', ); + + // Clear a boot-start flag saved by older builds, so this start (often + // the BootReceiver's own, on the update that installs this build) is + // the last one it makes. Done after the listeners above: events that + // arrive before a listener exists are dropped, so awaiting first could + // lose a 'stop'. + try { + await service.setAutoStartOnBootMode(false); + } catch (_) { + // Best effort: initialize() also saves false on the next mode start. + } } } diff --git a/lib/services/bluetooth/bluetooth_service.dart b/lib/services/bluetooth/bluetooth_service.dart index d6d0d871..05f126e4 100644 --- a/lib/services/bluetooth/bluetooth_service.dart +++ b/lib/services/bluetooth/bluetooth_service.dart @@ -86,6 +86,13 @@ abstract class BluetoothService implements CompanionTransport { /// budget inside one call. Future connect(String deviceId, {int? maxAttempts}); + /// Abandon a connect() that is still in progress, at the user's request. + /// + /// The in-flight connect() stops retrying and throws. A link the platform + /// had not finished opening is dropped without a 'disconnected' event; one + /// that finished just before the cancel is closed through [disconnect]. + Future cancelConnect(); + /// Disconnect from current device @override Future disconnect(); diff --git a/lib/services/bluetooth/mobile_bluetooth.dart b/lib/services/bluetooth/mobile_bluetooth.dart index 36f83be1..3515764a 100644 --- a/lib/services/bluetooth/mobile_bluetooth.dart +++ b/lib/services/bluetooth/mobile_bluetooth.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; +import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter_blue_plus/flutter_blue_plus.dart' as fbp; import 'package:geolocator/geolocator.dart'; import 'package:permission_handler/permission_handler.dart'; @@ -14,6 +15,53 @@ import 'bluetooth_service.dart'; /// Mobile Bluetooth implementation using flutter_blue_plus /// For Android and iOS platforms +/// Delays between retries of an Android write the stack refused as busy. +const List kGattBusyRetryDelays = [ + Duration(milliseconds: 50), + Duration(milliseconds: 100), + Duration(milliseconds: 150), +]; + +/// True when [error] is Android's ERROR_GATT_WRITE_REQUEST_BUSY, which the +/// stack returns when another write (often a second app on the same radio) +/// still holds the GATT queue. The write never went out, so it is safe to +/// send again. +bool isGattWriteBusy(Object error) => + error.toString().contains('ERROR_GATT_WRITE_REQUEST_BUSY'); + +/// Runs [write], retrying it after each of [delays] while it fails with +/// [isGattWriteBusy]. Any other error, or a busy error after the last retry, +/// is rethrown unchanged. +@visibleForTesting +Future writeRetryingGattBusy( + Future Function() write, { + List delays = kGattBusyRetryDelays, + Future Function(Duration delay)? sleep, +}) async { + for (var attempt = 0;; attempt++) { + try { + await write(); + if (attempt > 0) { + debugLog('[BLE] Write succeeded after $attempt GATT busy ' + 'retr${attempt == 1 ? 'y' : 'ies'}'); + } + return; + } catch (e) { + if (!isGattWriteBusy(e) || attempt >= delays.length) { + if (attempt > 0) { + debugWarn('[BLE] Write failed after $attempt GATT busy ' + 'retr${attempt == 1 ? 'y' : 'ies'}: $e'); + } + rethrow; + } + final delay = delays[attempt]; + debugLog('[BLE] GATT write busy, retrying in ${delay.inMilliseconds} ms ' + '(${attempt + 1}/${delays.length})'); + await (sleep ?? Future.delayed)(delay); + } + } +} + class MobileBluetoothService implements BluetoothService { // Retry constants for transient connect failures (see ble_connect_retry_policy.dart) static const int _maxRetries = 3; @@ -280,6 +328,12 @@ class MobileBluetoothService implements BluetoothService { /// the shared device state (_bleDevice, characteristics, subscriptions). int _connectEpoch = 0; + /// The highest epoch cancelled by [cancelConnect]. Separates "the user + /// cancelled this attempt" from "a newer connect superseded it": only a + /// cancelled attempt may close a link it opened after the cancel, since a + /// superseding connect may be using the same peripheral. + int _cancelledEpoch = 0; + @override Future connect(String deviceId, {int? maxAttempts}) async { final epoch = ++_connectEpoch; @@ -318,17 +372,36 @@ class MobileBluetoothService implements BluetoothService { _bleDevice = null; } + // A cancel can land during the previous-device disconnect above; + // check before taking a fresh device reference into shared state. + if (epoch != _connectEpoch) { + throw Exception('Connection attempt superseded'); + } + // Get the device - _bleDevice = fbp.BluetoothDevice.fromId(deviceId); + final pendingDevice = fbp.BluetoothDevice.fromId(deviceId); + _bleDevice = pendingDevice; debugLog('[BLE] Device reference created'); // Connect to GATT server FIRST (before subscribing to state changes) debugLog('[BLE] Connecting to GATT...'); - await _bleDevice!.connect( + await pendingDevice.connect( timeout: const Duration(seconds: 15), mtu: null, // Disable automatic MTU negotiation during connect to avoid race condition errors on Android ); + if (epoch <= _cancelledEpoch) { + // The link's connected event raced the cancel's disconnect and + // won, so the link is open even though the attempt was cancelled. + debugLog('[BLE] Link opened after the connect was cancelled, ' + 'closing it'); + try { + await pendingDevice.disconnect(queue: false); + } catch (e) { + debugWarn('[BLE] Closing cancelled link failed (ignoring): $e'); + } + throw Exception('Connection attempt cancelled'); + } debugLog('[BLE] GATT connected'); // Request larger MTU AFTER connection is established @@ -352,6 +425,9 @@ class MobileBluetoothService implements BluetoothService { final mtu = await _bleDevice!.mtu.first; debugLog('[BLE] iOS MTU: $mtu bytes'); } + if (epoch != _connectEpoch) { + throw Exception('Connection attempt superseded'); + } // NOW subscribe to connection state changes (after we're connected) // Use skip(1) to ignore the initial state emission from the stream. @@ -369,6 +445,9 @@ class MobileBluetoothService implements BluetoothService { // Discover services debugLog('[BLE] Discovering services...'); final services = await _bleDevice!.discoverServices(); + if (epoch != _connectEpoch) { + throw Exception('Connection attempt superseded'); + } debugLog('[BLE] Found ${services.length} services'); // Find our service @@ -397,6 +476,9 @@ class MobileBluetoothService implements BluetoothService { // Enable notifications on TX characteristic debugLog('[BLE] Enabling notifications...'); await _txCharacteristic!.setNotifyValue(true); + if (epoch != _connectEpoch) { + throw Exception('Connection attempt superseded'); + } _notificationSubscription = _txCharacteristic!.lastValueStream.listen((value) { if (value.isNotEmpty && @@ -522,6 +604,52 @@ class MobileBluetoothService implements BluetoothService { _updateStatus(ConnectionStatus.disconnected); } + @override + Future cancelConnect() async { + // Bumping the epoch makes the running connect() loop stop retrying and + // rethrow from wherever it is, without cleaning up after itself. + _cancelledEpoch = _connectEpoch; + ++_connectEpoch; + if (_connectionStatus == ConnectionStatus.connected) { + // The link finished opening just before the cancel landed: close it + // the normal way so the provider's disconnect cleanup runs. + debugLog('[BLE] Connect cancelled after the link opened, disconnecting'); + await disconnect(); + return; + } + final device = _bleDevice; + debugLog('[BLE] Cancelling connection attempt ' + '(pending device: ${device?.remoteId.str ?? 'none'})'); + // Take every shared field before the first await, so a connect loop + // resuming in a gap cannot install a listener that is then dropped + // uncancelled. The state listener goes first so the GATT drop cannot + // fire _handleDisconnection mid-cancel. + final stateSubscription = _connectionStateSubscription; + final notificationSubscription = _notificationSubscription; + _connectionStateSubscription = null; + _notificationSubscription = null; + _bleDevice = null; + _rxCharacteristic = null; + _txCharacteristic = null; + await stateSubscription?.cancel(); + await notificationSubscription?.cancel(); + if (device != null) { + try { + // queue: false jumps the plugin's operation queue, which the pending + // connect holds. Without it the cancel would wait for the connect + // timeout. It also tells iOS to drop the pending connection, which it + // would otherwise complete later on its own. + // Bounded so a platform that never reports the drop cannot leave + // the button on "Cancelling"; the epoch bump has already freed the + // connect loop. + await device.disconnect(queue: false, timeout: 5); + } catch (e) { + debugWarn('[BLE] Cancel disconnect failed (ignoring): $e'); + } + } + _updateStatus(ConnectionStatus.error); + } + @override Future disconnect() async { try { @@ -531,14 +659,36 @@ class MobileBluetoothService implements BluetoothService { } } + /// Tail of the local write queue. Every write waits for the one before it, + /// so a write retrying a GATT busy refusal keeps its place in line instead + /// of letting a later frame reach the radio first. Never completes with an + /// error. + Future _writeTail = Future.value(); + @override Future write(Uint8List data) async { - if (_rxCharacteristic == null) { - throw Exception('Not connected'); - } + final previous = _writeTail; + final done = Completer(); + _writeTail = done.future; + try { + await previous; + final characteristic = _rxCharacteristic; + if (characteristic == null) { + throw Exception('Not connected'); + } - // Write to RX characteristic (device reads from this) - await _rxCharacteristic!.write(data, withoutResponse: false); + // Write to RX characteristic (device reads from this). Android can + // refuse a write as busy without sending it; that one is retried + // briefly here so the caller's await covers the retry. + Future send() => characteristic.write(data, withoutResponse: false); + if (Platform.isAndroid) { + await writeRetryingGattBusy(send); + } else { + await send(); + } + } finally { + done.complete(); + } } @override diff --git a/lib/services/bluetooth/web_bluetooth.dart b/lib/services/bluetooth/web_bluetooth.dart index eff37be5..bb6ef29a 100644 --- a/lib/services/bluetooth/web_bluetooth.dart +++ b/lib/services/bluetooth/web_bluetooth.dart @@ -237,6 +237,11 @@ class WebBluetoothService implements BluetoothService { } } + /// Not offered on web: the Chrome picker owns device selection and the + /// connect is short, so there is nothing for the user to cancel. + @override + Future cancelConnect() async {} + @override Future disconnect() async { debugLog('[BLE] Disconnecting...'); diff --git a/lib/services/border_loader.dart b/lib/services/border_loader.dart new file mode 100644 index 00000000..25468112 --- /dev/null +++ b/lib/services/border_loader.dart @@ -0,0 +1,329 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:hive/hive.dart'; + +import '../utils/debug_logger_io.dart'; + +/// Region border polygons as `/border` sends them: `{code, polygon}` maps. +typedef BorderPolygons = List>; + +/// One `/border` answer. +class BorderAnswer { + final BorderPolygons polygons; + + /// The body's top-level `border_hash`. The server sends it only when every + /// polygon in the answer is real, so only an answer carrying it is saved + /// to disk. Null on a degraded answer and on older servers. + final String? borderHash; + + const BorderAnswer(this.polygons, {this.borderHash}); +} + +/// Whether [polygons] belong where the phone is: they must include +/// [zoneCode], and inside a group every code must be a member (or the zone +/// itself). A `/border` answer for another place, for instance from a fix +/// that moved on since `/status`, fails this and is never shown or saved. +bool bordersFitZone( + BorderPolygons polygons, { + required String zoneCode, + List? groupMembers, +}) { + final codes = polygons + .map((p) => p['code']) + .whereType() + .map((c) => c.toUpperCase()) + .toSet(); + final zone = zoneCode.toUpperCase(); + if (!codes.contains(zone)) return false; + if (groupMembers == null || groupMembers.isEmpty) return true; + final allowed = {zone, ...groupMembers.map((m) => m.toUpperCase())}; + return codes.every(allowed.contains); +} + +/// Where the last border set per context survives an app restart. +abstract class BorderCacheStore { + /// The hash saved for [contextKey], or null. Cheap: never reads polygons. + Future hashFor(String contextKey); + + /// The polygons saved for [contextKey], or null when none were saved under + /// that exact [borderHash]. + Future read(String contextKey, String borderHash); + + Future write( + String contextKey, String borderHash, BorderPolygons polygons); +} + +String _encodePolygons(BorderPolygons polygons) => json.encode(polygons); + +BorderPolygons? _decodePolygons(String raw) { + final decoded = json.decode(raw); + if (decoded is! List) return null; + return decoded + .whereType() + .map((p) => Map.from(p)) + .toList(); +} + +/// Hive-backed [BorderCacheStore], one entry per context, the oldest dropped +/// past [maxContexts]. +/// +/// The polygons (a group's run to megabytes) sit in a lazy box and are read +/// only on a hash match. The hash and save time per context sit in a small +/// index box held in memory, so checking for a hit and choosing what to +/// evict never touches the polygons. JSON work runs off the UI isolate. +class HiveBorderCacheStore implements BorderCacheStore { + static const String boxName = 'region_borders'; + static const String indexBoxName = 'region_borders_index'; + static const int maxContexts = 4; + + final DateTime Function() _now; + + HiveBorderCacheStore({DateTime Function()? now}) + : _now = now ?? DateTime.now; + + LazyBox? _box; + Box? _index; + + Future _open() async { + if (_box != null && _box!.isOpen && _index != null && _index!.isOpen) { + return true; + } + try { + _box = await Hive.openLazyBox(boxName) + .timeout(const Duration(seconds: 5)); + _index = await Hive.openBox(indexBoxName) + .timeout(const Duration(seconds: 5)); + // Polygons with no index entry can never be served or evicted. + final orphans = + _box!.keys.where((k) => !_index!.containsKey(k)).toList(); + if (orphans.isNotEmpty) { + await _box!.deleteAll(orphans); + await _box!.compact(); + } + return true; + } catch (e) { + debugWarn('[BORDER] Border cache unavailable: $e'); + return false; + } + } + + @override + Future hashFor(String contextKey) async { + try { + if (!await _open()) return null; + final entry = _index!.get(contextKey); + final hash = entry is Map ? entry['hash'] : null; + return hash is String ? hash : null; + } catch (e) { + debugWarn('[BORDER] Border cache index read failed: $e'); + return null; + } + } + + @override + Future read(String contextKey, String borderHash) async { + try { + if (!await _open()) return null; + final entry = await _box!.get(contextKey); + if (entry is! Map || entry['hash'] != borderHash) return null; + final raw = entry['json']; + if (raw is! String) return null; + return await compute(_decodePolygons, raw); + } catch (e) { + debugWarn('[BORDER] Border cache read failed: $e'); + return null; + } + } + + @override + Future write( + String contextKey, String borderHash, BorderPolygons polygons) async { + try { + if (!await _open()) return; + final box = _box!; + final index = _index!; + final encoded = await compute(_encodePolygons, polygons); + final replaced = box.containsKey(contextKey); + await box.put(contextKey, {'hash': borderHash, 'json': encoded}); + await index.put(contextKey, { + 'hash': borderHash, + 'saved_at': _now().millisecondsSinceEpoch, + }); + + var evicted = false; + final keys = index.keys.toList(); + if (keys.length > maxContexts) { + // A missing or malformed save time sorts oldest, so it is evicted + // first instead of stopping eviction. + int savedAt(dynamic key) { + final entry = index.get(key); + final value = entry is Map ? entry['saved_at'] : null; + return value is int ? value : 0; + } + + keys.sort((a, b) => savedAt(a).compareTo(savedAt(b))); + final drop = keys.take(keys.length - maxContexts).toList(); + await index.deleteAll(drop); + await box.deleteAll(drop); + evicted = true; + } + // Hive appends, so a replaced or deleted multi-megabyte entry stays in + // the file until compacted. + if (replaced || evicted) await box.compact(); + } catch (e) { + debugWarn('[BORDER] Border cache write failed: $e'); + } + } +} + +/// Decides when the app asks `/border` for the region polygons. +/// +/// Borders are display only, and a group's answer can run to megabytes, so: +/// one request at a time (the in-flight guard holds until the request has +/// really ended), at most one load per context and `/status` `border_hash`, +/// a growing pause after a failed, empty or misplaced answer, and a disk +/// cache (see MeshMapper_Server/docs/APP_API.md). Only an answer whose body +/// carries its own `border_hash` is saved, under that hash; the `/status` +/// hash only decides whether the saved copy is still current. A server that +/// sends no hash gets one load per context. +class BorderLoader { + /// Pause before asking again after the Nth failure in a row; the last + /// entry repeats. + static const List backoffSchedule = [ + Duration(minutes: 5), + Duration(minutes: 15), + Duration(minutes: 30), + ]; + + final BorderCacheStore? _cache; + final DateTime Function() _now; + + BorderLoader({BorderCacheStore? cache, DateTime Function()? now}) + : _cache = cache, + _now = now ?? DateTime.now; + + String? _loadedKey; + String? _loadedHash; + bool _inFlight = false; + + String? _failedKey; + String? _failedHash; + int _failures = 0; + DateTime? _retryAt; + + /// (context, hash) pairs the disk cache is known not to hold, so a zone + /// check during a backoff does not read it again. + final Set _knownMisses = {}; + + /// The context whose borders were last handed out, or null. + String? get loadedKey => _loadedKey; + + bool get fetchInProgress => _inFlight; + + /// When the next request is allowed after a failure, or null. + DateTime? get retryAt => _retryAt; + + /// Forget what is displayed (offline mode, out of zone, borders cleared). + /// The disk cache and any running request stay. + void forget() { + _loadedKey = null; + _loadedHash = null; + } + + /// Polygons to display for [contextKey], or null when nothing changes. + /// + /// [borderHash] is the `/status` zone hash. [fetch] makes the `/border` + /// request and returns null on failure. [accept] rejects an answer that + /// does not belong to the zone (see [bordersFitZone]); a rejected answer + /// counts as a failure. [onStale] runs just before a request for a + /// context other than the one displayed, so the caller can clear borders + /// that no longer belong; the loader then counts nothing as displayed. + Future ensure({ + required String contextKey, + String? borderHash, + required Future Function() fetch, + bool Function(BorderPolygons polygons)? accept, + void Function()? onStale, + }) async { + if (borderHash != null && borderHash.isEmpty) borderHash = null; + if (_inFlight) return null; + if (_loadedKey == contextKey && _loadedHash == borderHash) return null; + + if (_failedKey != contextKey || _failedHash != borderHash) { + _failedKey = contextKey; + _failedHash = borderHash; + _failures = 0; + _retryAt = null; + } + + _inFlight = true; + try { + final cache = _cache; + final missKey = '$contextKey\n$borderHash'; + if (borderHash != null && + cache != null && + !_knownMisses.contains(missKey)) { + BorderPolygons? cached; + if (await cache.hashFor(contextKey) == borderHash) { + cached = await cache.read(contextKey, borderHash); + } + if (cached != null && cached.isNotEmpty) { + _markLoaded(contextKey, borderHash); + debugLog('[BORDER] Using ${cached.length} cached polygon(s) for ' + '$contextKey (hash $borderHash)'); + return cached; + } + _knownMisses.add(missKey); + } + + final retryAt = _retryAt; + if (retryAt != null && _now().isBefore(retryAt)) return null; + + if (_loadedKey != contextKey) { + // Whatever was displayed belongs elsewhere and is cleared here, so + // a later return to that context must load it again. + forget(); + onStale?.call(); + } + + final answer = await fetch(); + final polygons = answer?.polygons; + String? problem; + if (polygons == null || polygons.isEmpty) { + problem = 'No polygons'; + } else if (accept != null && !accept(polygons)) { + problem = 'Polygons for another place'; + } + if (problem != null) { + final pause = backoffSchedule[ + _failures < backoffSchedule.length + ? _failures + : backoffSchedule.length - 1]; + _failures++; + _retryAt = _now().add(pause); + debugWarn('[BORDER] $problem for $contextKey; next try in ' + '${pause.inMinutes} min'); + return null; + } + + _markLoaded(contextKey, borderHash); + final bodyHash = answer!.borderHash; + if (bodyHash != null && bodyHash.isNotEmpty && cache != null) { + await cache.write(contextKey, bodyHash, polygons!); + _knownMisses.remove('$contextKey\n$bodyHash'); + } + return polygons; + } finally { + _inFlight = false; + } + } + + void _markLoaded(String contextKey, String? borderHash) { + _loadedKey = contextKey; + _loadedHash = borderHash; + _failures = 0; + _retryAt = null; + } +} diff --git a/lib/services/custom_api_service.dart b/lib/services/custom_api_service.dart index 90fe04e3..eda3cd95 100644 --- a/lib/services/custom_api_service.dart +++ b/lib/services/custom_api_service.dart @@ -5,6 +5,7 @@ import 'package:http/http.dart' as http; import '../models/user_preferences.dart'; import '../utils/debug_logger_io.dart'; +import 'api_queue_service.dart' show kAltitudeReferences; /// Service for forwarding wardrive ping payloads to a user-configured /// third-party API endpoint. Fire-and-forget: never blocks MeshMapper uploads. @@ -85,6 +86,15 @@ class CustomApiService { final enrichedPing = Map.from(ping); // The auto mode stamp is MeshMapper analytics, never a third party's. enrichedPing.remove('auto_mode'); + // An altitude without a proved reference is never forwarded either; a + // row from an older offline session can still carry one. + final ref = enrichedPing['altitude_ref']; + if (ref is! String || !kAltitudeReferences.contains(ref)) { + enrichedPing + ..remove('altitude') + ..remove('altitude_ref') + ..remove('altitude_acc'); + } if (contact != null) enrichedPing['contact'] = contact; if (iata != null) enrichedPing['iata'] = iata; return enrichedPing; diff --git a/lib/services/debug_file_logger.dart b/lib/services/debug_file_logger.dart index 8d4e4cd1..0bb3da4b 100644 --- a/lib/services/debug_file_logger.dart +++ b/lib/services/debug_file_logger.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:path_provider/path_provider.dart'; import '../utils/constants.dart'; @@ -11,21 +12,60 @@ import '../utils/constants.dart'; /// - Writes debug logs to timestamped files in app documents directory /// - Auto-rotates to maintain max 10 log files (deletes oldest) /// - Provides file listing, viewing, and deletion capabilities -/// - Non-persistent (always starts disabled on app launch) +/// - On by default. The stored preference is read before the first file is +/// created: `main.dart` calls [beginCapture] first thing, which holds the +/// startup lines in memory, and only once the preference is known does it +/// call [enable] (the held lines land under the header) or [discardCapture]. +/// Opening a file first and closing it when the preference read off left +/// one stub file per launch, and they all surfaced the moment the user +/// turned logging on. class DebugFileLogger { static const int maxLogFiles = 10; + /// Lines held while capturing (or while a rotation has no sink yet). The + /// cap is a safety net: nothing normal leaves a capture open for long. + static const int maxPendingLogs = 500; + /// Maximum file size for upload (4.5MB, 0.5MB safety margin under 5MB server limit) static const int maxUploadSizeBytes = 4718592; static File? _currentLogFile; static IOSink? _logSink; static bool _enabled = false; + static bool _capturing = false; + static int _droppedPendingLogs = 0; + static Future? _enabling; static final List _pendingLogs = []; static Timer? _flushTimer; /// Returns whether file logging is currently enabled static bool get isEnabled => _enabled; + /// Whether a stored `debug_logs_enabled` preference asks for file logging. + /// Only an explicit `false` turns it off; a missing or malformed value keeps + /// the default (on). One definition, read by `main.dart` and the provider. + static bool wantsFileLogging(Object? stored) => stored != false; + + /// Hold every line written from now on in memory, without a file, until + /// [enable] flushes them into the first file or [discardCapture] drops them. + /// A no-op while a file is already open. + static void beginCapture() { + if (_enabled) return; + _capturing = true; + } + + /// End a capture without a file: the preference read off. + static void discardCapture() { + _capturing = false; + _pendingLogs.clear(); + _droppedPendingLogs = 0; + } + + @visibleForTesting + static int get pendingLogCount => _pendingLogs.length; + + @visibleForTesting + static List get pendingLogsForTest => List.unmodifiable(_pendingLogs); + /// The app build and the device this log came from, resolved once per launch /// and written at the top of every log file. A report that blames the app is /// often an OEM battery manager or an OS version quirk instead, and the @@ -38,12 +78,18 @@ class DebugFileLogger { if (cached != null) return cached; final parts = ['App ${AppConstants.appVersion}']; + const flutterVersion = String.fromEnvironment('FLUTTER_VERSION'); + const engineRevision = String.fromEnvironment('FLUTTER_ENGINE_REVISION'); + if (flutterVersion.isNotEmpty) parts.add('Flutter $flutterVersion'); + if (engineRevision.isNotEmpty) parts.add('Engine $engineRevision'); try { final info = DeviceInfoPlugin(); if (Platform.isAndroid) { final a = await info.androidInfo; parts.add('Android ${a.version.release} (SDK ${a.version.sdkInt})'); parts.add('${a.manufacturer} ${a.model}'); + parts + .add('OS build ${a.id}, security patch ${a.version.securityPatch}'); } else if (Platform.isIOS) { final i = await info.iosInfo; parts.add('iOS ${i.systemVersion}'); @@ -67,9 +113,14 @@ class DebugFileLogger { /// /// Creates a new file with format: meshmapper-debug-{unix_timestamp}.txt /// Auto-rotates old files if limit exceeded - static Future enable() async { - if (_enabled) return; + static Future enable() { + if (_enabled) return Future.value(); + // The flag only flips after two awaits, so a second caller landing in + // that window would open a second file. Hand it the same future instead. + return _enabling ??= _enable().whenComplete(() => _enabling = null); + } + static Future _enable() async { try { // Resolved before the sink exists: an await between opening it and // writing the header would let a concurrent debugLog land above the @@ -92,6 +143,7 @@ class DebugFileLogger { // Flush any logs that were captured before the sink was ready _flushPendingLogs(); + _capturing = false; // Start periodic flush timer (every 5 seconds) to ensure logs persist // This is important on iOS where background suspension can lose buffered data @@ -103,6 +155,9 @@ class DebugFileLogger { await _rotateOldFiles(dir); } catch (e) { _enabled = false; + _capturing = false; + _pendingLogs.clear(); + _droppedPendingLogs = 0; _logSink = null; _currentLogFile = null; rethrow; @@ -131,6 +186,9 @@ class DebugFileLogger { _logSink = null; _currentLogFile = null; _enabled = false; + _capturing = false; + _pendingLogs.clear(); + _droppedPendingLogs = 0; } } @@ -188,16 +246,20 @@ class DebugFileLogger { /// Called by debug_logger_stub.dart for each log message /// Format: [ISO8601_timestamp] LEVEL: message /// - /// If the log sink isn't ready yet (race condition during init), logs are - /// buffered and flushed when the sink becomes available. + /// While capturing, or while the sink isn't ready yet (a rotation in + /// flight), lines are held in memory and written once a sink exists, up to + /// [maxPendingLogs]; past the cap the newest lines are dropped and counted. static void write(String level, String message) { - if (!_enabled) return; + if (!_enabled && !_capturing) return; final timestamp = DateTime.now().toIso8601String(); final line = '[$timestamp] $level: ${scrubSecrets(message)}'; if (_logSink == null) { - // Buffer logs until sink is ready (race condition during initialization) + if (_pendingLogs.length >= maxPendingLogs) { + _droppedPendingLogs++; + return; + } _pendingLogs.add(line); return; } @@ -224,6 +286,15 @@ class DebugFileLogger { // Silently fail - avoid recursive logging errors } } + if (_droppedPendingLogs > 0) { + try { + sink.writeln('=== $_droppedPendingLogs lines dropped while the log ' + 'had no file ==='); + } catch (e) { + // Silently fail - avoid recursive logging errors + } + _droppedPendingLogs = 0; + } _pendingLogs.clear(); } @@ -263,6 +334,43 @@ class DebugFileLogger { } } + /// The line the old startup path wrote right before closing the file it had + /// just opened: every file containing it is a stub by construction. The + /// provider's wording changed with the fix, so no new file can match. + static const String legacyStartupStubLine = + '[INIT] Debug logs disabled by user preference, turning off'; + + /// Only files this small are ever read by [deleteStartupStubs]. + static const int maxStartupStubBytes = 16 * 1024; + + /// Whether a log file's content is a stub left by the old startup path. + static bool isStartupStubContent(String content) => + content.contains(legacyStartupStubLine); + + /// Delete the stub files the old startup path left behind, once per launch + /// and best effort: at most [maxLogFiles] stats, and only a small file that + /// is not the current one is read. + static Future deleteStartupStubs() async { + var deleted = 0; + try { + final currentPath = _currentLogFile?.path; + for (final file in await listLogFiles()) { + if (file.path == currentPath) continue; + try { + if (await file.length() > maxStartupStubBytes) continue; + if (!isStartupStubContent(await file.readAsString())) continue; + await file.delete(); + deleted++; + } catch (e) { + // Best effort: a file that cannot be read or deleted stays. + } + } + } catch (e) { + // Best effort: the cleanup is never allowed to fail startup. + } + return deleted; + } + /// Delete all debug log files /// /// Removes all files matching the meshmapper-debug-* pattern diff --git a/lib/services/debug_submit_service.dart b/lib/services/debug_submit_service.dart index df147e74..81a27263 100644 --- a/lib/services/debug_submit_service.dart +++ b/lib/services/debug_submit_service.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -69,13 +70,104 @@ class UploadSession { ); } +/// Outcome of one file upload attempt. +enum UploadAttemptOutcome { + /// The server stored the file. + success, + + /// The request never got a usable answer (connection dropped, timeout). + /// The bytes may still have landed. + transportError, + + /// HTTP 400 "Session Closed": the server no longer accepts uploads for + /// this session, which it does once a file has landed. + sessionClosed, + + /// Any other refusal. + failed, +} + +/// Result of the upload step for one file, before it is confirmed. +enum _UploadStepResult { + /// An attempt succeeded. + uploaded, + + /// "Session Closed" after an earlier transport error: the file most likely + /// landed on that earlier attempt, so upload-complete decides (its hash + /// check is the authority). + landedUnconfirmed, + + /// Every attempt failed. + failed, +} + /// Service for submitting bug reports and uploading debug files class DebugSubmitService { static const String baseUrl = 'https://meshmapper.net/debug/submitdebug.php'; final http.Client _client; - DebugSubmitService({http.Client? client}) : _client = client ?? http.Client(); + /// Base step for retry backoff. Tests shorten it; the app uses 1 s. + final Duration _retryDelayUnit; + + DebugSubmitService({ + http.Client? client, + Duration retryDelayUnit = const Duration(seconds: 1), + }) : _client = client ?? http.Client(), + _retryDelayUnit = retryDelayUnit; + + /// Attempts at request-upload: the first plus two retries on a transport + /// error. + static const int _requestUploadAttempts = 3; + + /// Attempts at the file upload itself. + static const int _uploadAttempts = 3; + + /// Upload [file] to [session], retrying up to [_uploadAttempts] times. + Future<_UploadStepResult> _uploadWithRetries({ + required UploadSession session, + required File file, + required String tag, + }) async { + var sawTransportError = false; + for (int attempt = 1; attempt <= _uploadAttempts; attempt++) { + final outcome = await uploadFileAttempt( + uploadUrl: session.uploadUrl, + file: file, + ); + + if (outcome == UploadAttemptOutcome.success) { + debugLog('$tag File data uploaded'); + return _UploadStepResult.uploaded; + } + if (outcome == UploadAttemptOutcome.sessionClosed) { + if (sawTransportError) { + // The earlier attempt's answer was lost, but the server has since + // closed the session, which it does once a file lands. Let + // upload-complete check the hash instead of failing here. + debugLog('$tag Session closed after an earlier dropped attempt; ' + 'asking the server to confirm the file'); + return _UploadStepResult.landedUnconfirmed; + } + // No attempt of ours can have landed, and a closed session takes no + // more uploads, so a retry cannot succeed. + debugWarn('$tag Upload session closed with no file from this app; ' + 'not retrying'); + return _UploadStepResult.failed; + } + if (outcome == UploadAttemptOutcome.transportError) { + sawTransportError = true; + } + + if (attempt < _uploadAttempts) { + final delay = _retryDelayUnit * (attempt * 2); // 2s, 4s backoff + debugWarn('$tag Upload attempt $attempt/$_uploadAttempts failed, ' + 'retrying in ${delay.inMilliseconds / 1000}s...'); + await Future.delayed(delay); + } + } + return _UploadStepResult.failed; + } /// Main orchestration method - submits bug report with optional file uploads Future submitBugReport({ @@ -342,31 +434,15 @@ class DebugSubmitService { // Step 3: Upload the file (with retry logic) debugLog('[BUG REPORT] Step 3/4: Uploading file data...'); - var uploadSuccess = false; - const maxRetries = 3; - - for (int attempt = 1; attempt <= maxRetries; attempt++) { - uploadSuccess = await uploadFile( - uploadUrl: session.uploadUrl, - file: file, - ); - - if (uploadSuccess) { - debugLog('[BUG REPORT] SUCCESS: File data uploaded'); - break; - } - - if (attempt < maxRetries) { - final delaySeconds = attempt * 2; // 2s, 4s backoff - debugWarn( - '[BUG REPORT] Upload attempt $attempt/$maxRetries failed, retrying in ${delaySeconds}s...'); - await Future.delayed(Duration(seconds: delaySeconds)); - } - } + final upload = await _uploadWithRetries( + session: session, + file: file, + tag: '[BUG REPORT]', + ); - if (!uploadSuccess) { - debugError( - '[BUG REPORT] FAILED: File upload failed after $maxRetries attempts for: $filename'); + if (upload == _UploadStepResult.failed) { + debugError('[BUG REPORT] FAILED: File upload failed after ' + '$_uploadAttempts attempts for: $filename'); return false; } @@ -386,6 +462,13 @@ class DebugSubmitService { userNotes: userNotes, ); + if (!completeSuccess && upload == _UploadStepResult.landedUnconfirmed) { + // No attempt was ever acknowledged, so without the server's + // confirmation there is no evidence the file landed. + debugError('[BUG REPORT] FAILED: Server did not confirm $filename ' + 'after a closed session'); + return false; + } if (!completeSuccess) { debugWarn( '[BUG REPORT] WARNING: Upload confirmation failed for: $filename'); @@ -501,13 +584,27 @@ class DebugSubmitService { debugLog('[BUG REPORT] platform: $platform'); final stopwatch = Stopwatch()..start(); - final response = await _client - .post( - Uri.parse(url), - headers: {'Content-Type': 'application/json'}, - body: json.encode(payload), - ) - .timeout(const Duration(seconds: 30)); + http.Response? response; + for (int attempt = 1; response == null; attempt++) { + try { + response = await _client + .post( + Uri.parse(url), + headers: {'Content-Type': 'application/json'}, + body: json.encode(payload), + ) + .timeout(const Duration(seconds: 30)); + } on Exception catch (e) { + if (!_isTransportError(e) || attempt >= _requestUploadAttempts) { + rethrow; + } + final delay = _retryDelayUnit * attempt; // 1s, 2s backoff + debugWarn('[BUG REPORT] Request upload attempt ' + '$attempt/$_requestUploadAttempts got no answer ($e), ' + 'retrying in ${delay.inMilliseconds / 1000}s...'); + await Future.delayed(delay); + } + } stopwatch.stop(); debugLog( @@ -541,10 +638,26 @@ class DebugSubmitService { } } + /// A failure to get any answer back, as opposed to a server refusal. + static bool _isTransportError(Object e) => + e is http.ClientException || + e is TimeoutException || + e is SocketException || + e is HttpException; + /// Step 3: Upload the file using multipart/form-data Future uploadFile({ required String uploadUrl, required File file, + }) async => + await uploadFileAttempt(uploadUrl: uploadUrl, file: file) == + UploadAttemptOutcome.success; + + /// One upload attempt, saying how it went so the caller can tell a lost + /// answer from a refusal. + Future uploadFileAttempt({ + required String uploadUrl, + required File file, }) async { try { final filename = file.path.split('/').last; @@ -565,7 +678,7 @@ class DebugSubmitService { final stopwatch = Stopwatch()..start(); final streamedResponse = - await request.send().timeout(const Duration(seconds: 120)); + await _client.send(request).timeout(const Duration(seconds: 120)); final response = await http.Response.fromStream(streamedResponse); stopwatch.stop(); @@ -580,9 +693,13 @@ class DebugSubmitService { debugLog('[BUG REPORT] HTTP Status: ${response.statusCode}'); if (response.statusCode != 200) { + if (response.statusCode == 400 && _isSessionClosed(response.body)) { + debugWarn('[BUG REPORT] Upload refused: session closed'); + return UploadAttemptOutcome.sessionClosed; + } debugError('[BUG REPORT] HTTP error: ${response.statusCode}'); debugError('[BUG REPORT] Response body: ${response.body}'); - return false; + return UploadAttemptOutcome.failed; } final data = json.decode(response.body) as Map; @@ -596,15 +713,31 @@ class DebugSubmitService { '[BUG REPORT] stored_hash: ${data['stored_hash'].toString().substring(0, 16)}...'); } - final success = data['success'] == true; - return success; + return data['success'] == true + ? UploadAttemptOutcome.success + : UploadAttemptOutcome.failed; } catch (e, stackTrace) { + if (_isTransportError(e)) { + debugWarn('[BUG REPORT] Upload attempt got no answer: $e'); + return UploadAttemptOutcome.transportError; + } debugError('[BUG REPORT] Upload file exception: $e'); debugError('[BUG REPORT] Stack trace: $stackTrace'); - return false; + return UploadAttemptOutcome.failed; } } + static bool _isSessionClosed(String body) { + try { + final data = json.decode(body); + if (data is Map && data['message'] is String) { + return (data['message'] as String).trim().toLowerCase() == + 'session closed'; + } + } catch (_) {} + return false; + } + /// Step 4: Confirm upload completion Future completeUpload({ required String deviceId, @@ -766,31 +899,15 @@ class DebugSubmitService { // Step 3: Upload file reportChunkProgress('Uploading $chunkName...', 0.4); debugLog('[DEBUG UPLOAD] Uploading file...'); - var uploadSuccess = false; - const maxRetries = 3; - - for (int attempt = 1; attempt <= maxRetries; attempt++) { - uploadSuccess = await uploadFile( - uploadUrl: session.uploadUrl, - file: chunk, - ); - - if (uploadSuccess) { - debugLog('[DEBUG UPLOAD] File uploaded successfully'); - break; - } - - if (attempt < maxRetries) { - final delaySeconds = attempt * 2; - debugWarn( - '[DEBUG UPLOAD] Upload attempt $attempt/$maxRetries failed, retrying in ${delaySeconds}s...'); - await Future.delayed(Duration(seconds: delaySeconds)); - } - } + final upload = await _uploadWithRetries( + session: session, + file: chunk, + tag: '[DEBUG UPLOAD]', + ); - if (!uploadSuccess) { - debugError( - '[DEBUG UPLOAD] FAILED: Upload failed after $maxRetries attempts for $chunkName'); + if (upload == _UploadStepResult.failed) { + debugError('[DEBUG UPLOAD] FAILED: Upload failed after ' + '$_uploadAttempts attempts for $chunkName'); allSucceeded = false; break; } @@ -806,6 +923,15 @@ class DebugSubmitService { userNotes: userNotes ?? 'Direct debug log upload', ); + if (!completeSuccess && + upload == _UploadStepResult.landedUnconfirmed) { + // No attempt was ever acknowledged, so without the server's + // confirmation there is no evidence the file landed. + debugError('[DEBUG UPLOAD] FAILED: Server did not confirm ' + '$chunkName after a closed session'); + allSucceeded = false; + break; + } if (!completeSuccess) { debugWarn( '[DEBUG UPLOAD] Confirmation failed but file was uploaded'); diff --git a/lib/services/external_surfaces/geo/external_surface_geo_builder.dart b/lib/services/external_surfaces/geo/external_surface_geo_builder.dart index d1e80563..7439b460 100644 --- a/lib/services/external_surfaces/geo/external_surface_geo_builder.dart +++ b/lib/services/external_surfaces/geo/external_surface_geo_builder.dart @@ -3,6 +3,7 @@ import '../../../models/ping_data.dart'; import '../../../models/repeater.dart'; import '../../../providers/app_state_provider.dart' show OverlayPingType; import '../../../utils/ping_colors.dart'; +import '../../../utils/repeater_nicknames.dart'; import '../external_surface_color.dart'; import 'external_surface_geo_models.dart'; @@ -289,6 +290,39 @@ class ExternalSurfaceGeoBuilder { return prefixed.length == 1 ? prefixed.single : null; } + /// Resolve one overlay row to a repeater: the fullest identity the row + /// arrived with first, then the display hash it is shown under. + /// + /// **The fallback is the point.** A discovery response's public key is a + /// better identity, but the catalogue is matched by a `hexId` that the API + /// frequently omits, and the display hash additionally resolves + /// through `displayHexId`, which falls back to the short numeric ID when + /// there is no hex at all. Trying only the longer form threw away the lookup + /// that was doing the work, and left named repeaters unnamed. An [identity] + /// that is null, empty or matches nothing (or more than one repeater) falls + /// through to [displayId]. + /// + /// Returns null unless exactly one repeater matches, as [resolveRepeater] + /// does: a confidently wrong name is worse than none. + static Repeater? resolveOverlayRow({ + required String displayId, + String? identity, + required List repeaters, + int? hopBytes, + }) => + (identity == null || identity.isEmpty + ? null + : resolveRepeater( + repeaters: repeaters, + id: identity, + hopBytes: hopBytes, + )) ?? + resolveRepeater( + repeaters: repeaters, + id: displayId.toUpperCase(), + hopBytes: hopBytes, + ); + /// Resolve overlay display hashes to repeaters, preferring the fuller /// identity the ping actually carried. /// @@ -368,12 +402,13 @@ class ExternalSurfaceGeoBuilder { static ExternalSurfaceColor snrColor(double snr) => ExternalSurfaceColor.fromColor(PingColors.snrColor(snr)); - /// The "Top Heard" overlay rows: up to three top-SNR repeaters from the - /// latest ping, then the current RX slot. + /// The "Top Heard" overlay rows: up to [ExternalSurfaceGeoWire.maxHeard] + /// rows, the top-SNR repeaters from the latest ping, then the current RX + /// slot, which is always kept when present (ping rows are cut to make room). /// /// Order is deliberate rather than a global SNR sort: it matches the map /// overlay, where the RX slot is a distinct trailing row rather than a - /// competitor for the top three. + /// competitor for the top-SNR rows. static List buildHeard({ required List<({String repeaterId, double snr, OverlayPingType type})> top, ({String repeaterId, double snr})? rxSlot, @@ -382,13 +417,17 @@ class ExternalSurfaceGeoBuilder { required DateTime? rxAt, double? lat, double? lon, + Map nicknames = const {}, }) { final rows = []; + // Leave the RX row its place under the wire cap. + const cap = ExternalSurfaceGeoWire.maxHeard; + final maxPingRows = rxSlot != null && rxAt != null ? cap - 1 : cap; // Missing time means the provider cannot truthfully say when this set was // heard. Omitting such a row is safer than presenting a plausible lie in // Node Detail; every production mutation records its timestamp atomically. - for (final entry in top.where((_) => topAt != null)) { + for (final entry in top.where((_) => topAt != null).take(maxPingRows)) { rows.add(_row( id: entry.repeaterId, snr: entry.snr, @@ -397,6 +436,7 @@ class ExternalSurfaceGeoBuilder { at: topAt!, lat: lat, lon: lon, + nicknames: nicknames, )); } @@ -409,6 +449,7 @@ class ExternalSurfaceGeoBuilder { at: rxAt, lat: lat, lon: lon, + nicknames: nicknames, )); } @@ -423,6 +464,7 @@ class ExternalSurfaceGeoBuilder { required OverlayPingType type, required Map repeaterByHex, required DateTime at, + required Map nicknames, double? lat, double? lon, }) { @@ -441,8 +483,12 @@ class ExternalSurfaceGeoBuilder { return ExternalSurfaceHeardNode( id: hex, // Null rather than a guess: a short path hash can match several - // repeaters, and a confidently wrong name is worse than none. - name: repeater?.name, + // repeaters, and a confidently wrong name is worse than none. The user's + // own nickname for the resolved repeater outranks the server's name. + name: (repeater == null + ? null + : RepeaterNicknames.nicknameFor(repeater, nicknames)) ?? + repeater?.name, snr: snr, at: at, distanceM: distance, diff --git a/lib/services/fix_altitude.dart b/lib/services/fix_altitude.dart new file mode 100644 index 00000000..9dd113d0 --- /dev/null +++ b/lib/services/fix_altitude.dart @@ -0,0 +1,314 @@ +import 'package:geolocator/geolocator.dart'; + +/// The vertical reference an altitude is measured from. +/// +/// iOS always reports height above mean sea level. Android reports height +/// above the WGS84 ellipsoid, except that on Android 14 and later the location +/// plugin swaps in a sea level value whenever the fix object carries one. The +/// two differ by the local geoid separation, tens of meters in most places, +/// which is why an altitude is only uploaded together with its reference. The +/// server contract is documented in `MeshMapper_Server/docs/APP_API.md`. +enum AltitudeReference { + /// Height above mean sea level. + msl('msl'), + + /// Height above the WGS84 ellipsoid. + ellipsoid('ellipsoid'); + + const AltitudeReference(this.wireName); + + /// The value sent as `altitude_ref`. + final String wireName; +} + +/// A fix's altitude as the app is willing to report it: the meters, the +/// reference they are measured from and the vertical accuracy, or nothing at +/// all. An altitude is never reported without its reference. +class FixAltitude { + /// Meters, null when unknown. + final double? meters; + + /// The reference [meters] is measured from, null when unknown. + final AltitudeReference? reference; + + /// Vertical accuracy in meters (about one standard deviation on both phone + /// platforms), null when the fix did not carry one or it was not usable. + final double? accuracy; + + const FixAltitude.unknown() + : meters = null, + reference = null, + accuracy = null; + + FixAltitude.known({ + required double this.meters, + required AltitudeReference this.reference, + double? accuracy, + }) : accuracy = sanitizeAccuracy(accuracy); + + bool get isKnown => meters != null && reference != null; + + /// The `altitude_ref` wire value, null when unknown. + String? get wireReference => reference?.wireName; + + /// An accuracy is usable when it is a finite number above zero. geolocator + /// reports a missing accuracy as 0.0, and Android permits a known zero, so + /// zero is treated as unknown on purpose. + static double? sanitizeAccuracy(double? value) { + if (value == null || !value.isFinite || value <= 0) return null; + return value; + } + + @override + String toString() => isKnown + ? 'FixAltitude(${meters}m ${reference!.wireName}' + '${accuracy != null ? ' ±${accuracy}m' : ''})' + : 'FixAltitude(unknown)'; +} + +/// The altitude a fix actually carries, or null when the platform had none. +/// +/// geolocator reports a missing altitude as 0.0 with 0.0 accuracy on both +/// platforms. Android also omits the accuracy on fixes that DO carry an +/// altitude, so the accuracy alone cannot decide; only the 0/0 pair means +/// unknown. A non-finite altitude is unknown too. +double? reportedAltitudeOrNull(Position position) { + if (position.altitude == 0.0 && position.altitudeAccuracy == 0.0) { + return null; + } + if (!position.altitude.isFinite) return null; + return position.altitude; +} + +/// Which labelling rule applies. Decided once from the running platform. +enum AltitudePlatform { ios, android, web, other } + +/// The first Android SDK whose fixes can carry a sea level altitude +/// (Android 14, `Build.VERSION_CODES.UPSIDE_DOWN_CAKE`). +const int kAndroidMslSdk = 34; + +/// One fix object as the Android handler read it off the location provider. +/// Field names mirror `android.location.Location`: [altitude] is the +/// ellipsoid height, [msl] the sea level height when [hasMsl]. +class NativeFixDescription { + final String source; + final int timeMs; + final double lat; + final double lon; + final bool hasAltitude; + final double altitude; + final bool hasVerticalAccuracy; + final double verticalAccuracy; + final bool hasMsl; + final double msl; + final bool hasMslAccuracy; + final double mslAccuracy; + final bool isMock; + + const NativeFixDescription({ + required this.source, + required this.timeMs, + required this.lat, + required this.lon, + required this.hasAltitude, + required this.altitude, + required this.hasVerticalAccuracy, + required this.verticalAccuracy, + required this.hasMsl, + required this.msl, + required this.hasMslAccuracy, + required this.mslAccuracy, + required this.isMock, + }); + + /// Parses one entry of the channel's `fixes` list. Returns null when the + /// entry is not a map, when a required field is missing or mistyped, when + /// the timestamp is not an integer, or when an altitude flag is true but + /// its value is absent or not finite. Nothing is invented: a value the + /// handler did not send cannot prove anything. An accuracy is different: + /// it never proves the reference, so a missing or non-finite accuracy + /// only clears its flag and the altitude can still be proved without it. + static NativeFixDescription? tryFromMap(Object? raw) { + if (raw is! Map) return null; + double? d(Object? v) => v is num && v.isFinite ? v.toDouble() : null; + bool? b(Object? v) => v is bool ? v : null; + final timeMs = raw['timeMs']; + final lat = d(raw['lat']); + final lon = d(raw['lon']); + final hasAltitude = b(raw['hasAltitude']); + final hasVerticalAccuracy = b(raw['hasVerticalAccuracy']); + final hasMsl = b(raw['hasMsl']); + final hasMslAccuracy = b(raw['hasMslAccuracy']); + final isMock = b(raw['isMock']); + if (timeMs is! int || + lat == null || + lon == null || + hasAltitude == null || + hasVerticalAccuracy == null || + hasMsl == null || + hasMslAccuracy == null || + isMock == null) { + return null; + } + final altitude = d(raw['altitude']); + final verticalAccuracy = d(raw['verticalAccuracy']); + final msl = d(raw['msl']); + final mslAccuracy = d(raw['mslAccuracy']); + if ((hasAltitude && altitude == null) || (hasMsl && msl == null)) { + return null; + } + return NativeFixDescription( + source: raw['source'] is String ? raw['source'] as String : 'unknown', + timeMs: timeMs, + lat: lat, + lon: lon, + hasAltitude: hasAltitude, + altitude: altitude ?? 0.0, + hasVerticalAccuracy: hasVerticalAccuracy && verticalAccuracy != null, + verticalAccuracy: verticalAccuracy ?? 0.0, + hasMsl: hasMsl, + msl: msl ?? 0.0, + hasMslAccuracy: hasMslAccuracy && mslAccuracy != null, + mslAccuracy: mslAccuracy ?? 0.0, + isMock: isMock, + ); + } +} + +/// What the Android handler answered: the SDK it runs on and the fix objects +/// it could read (empty below Android 14, where no read is performed). +class NativeAltitudeAnswer { + final int sdk; + final List fixes; + + const NativeAltitudeAnswer({required this.sdk, required this.fixes}); + + /// Null unless [raw] is a map whose `sdk` is a positive integer. A missing + /// or zero SDK must never be read as "below Android 14": that would label + /// every later fix ellipsoid on the strength of a malformed answer. + static NativeAltitudeAnswer? tryFromMap(Object? raw) { + if (raw is! Map) return null; + final sdkRaw = raw['sdk']; + if (sdkRaw is! int || sdkRaw <= 0) return null; + final fixesRaw = raw['fixes']; + return NativeAltitudeAnswer( + sdk: sdkRaw, + fixes: fixesRaw is List + ? fixesRaw + .map(NativeFixDescription.tryFromMap) + .whereType() + .toList(growable: false) + : const [], + ); + } +} + +/// The rule's answer plus a short token saying which branch decided it, for +/// the resolver's (throttled) logging and for the tests. +class AltitudeResolution { + final FixAltitude altitude; + final String reason; + const AltitudeResolution(this.altitude, this.reason); + + static const _unknown = FixAltitude.unknown(); + const AltitudeResolution.unknown(this.reason) : altitude = _unknown; +} + +/// Decides what altitude, if any, a fix may be uploaded with. +/// +/// Pure. [simulated] is true for a GPS simulator fix. [native] is the Android +/// handler's answer for the moment this fix was accepted, null on every other +/// platform or when the read failed. The Android 14 proof is exact equality: +/// same timestamp, same coordinates, and the altitude the plugin delivered +/// equals the fix's sea level value or its ellipsoid value. Nearness is never +/// accepted, since two fixes a few seconds apart can carry different +/// altitudes and different references. +AltitudeResolution resolveFixAltitude({ + required AltitudePlatform platform, + required Position position, + required bool simulated, + NativeAltitudeAnswer? native, +}) { + if (simulated) return const AltitudeResolution.unknown('simulated'); + if (position.isMocked) return const AltitudeResolution.unknown('mocked'); + final meters = reportedAltitudeOrNull(position); + if (meters == null) return const AltitudeResolution.unknown('no_altitude'); + + switch (platform) { + case AltitudePlatform.ios: + return AltitudeResolution( + FixAltitude.known( + meters: meters, + reference: AltitudeReference.msl, + accuracy: position.altitudeAccuracy), + 'ios', + ); + case AltitudePlatform.web: + // The browser reports a 95% confidence figure while the phones report + // about one sigma, so the web accuracy is withheld. + return AltitudeResolution( + FixAltitude.known(meters: meters, reference: AltitudeReference.ellipsoid), + 'web', + ); + case AltitudePlatform.other: + return const AltitudeResolution.unknown('other_platform'); + case AltitudePlatform.android: + if (native == null) return const AltitudeResolution.unknown('no_native'); + if (native.sdk < kAndroidMslSdk) { + // With this app's location settings (NMEA sea level off) the plugin + // can only have delivered the ellipsoid height here. + return AltitudeResolution( + FixAltitude.known( + meters: meters, + reference: AltitudeReference.ellipsoid, + accuracy: position.altitudeAccuracy), + 'android_legacy', + ); + } + if (native.fixes.isEmpty) return const AltitudeResolution.unknown('no_fix'); + // Every candidate is examined: the location manager path can answer + // several providers, and a non-matching or mock candidate must not + // hide a genuine match beside it. The sea level value is tried first; + // an exact ellipsoid match is accepted whether or not the fix also + // carries sea level, because the plugin only swaps in sea level when + // the fix object has extras, which the location manager path may not. + final timeMs = position.timestamp.millisecondsSinceEpoch; + var sawTime = false; + var sawCoord = false; + var sawMock = false; + for (final fix in native.fixes) { + if (fix.timeMs != timeMs) continue; + sawTime = true; + if (fix.lat != position.latitude || fix.lon != position.longitude) { + continue; + } + sawCoord = true; + if (fix.isMock) { + sawMock = true; + continue; + } + if (fix.hasMsl && meters == fix.msl) { + return AltitudeResolution( + FixAltitude.known( + meters: meters, + reference: AltitudeReference.msl, + accuracy: fix.hasMslAccuracy ? fix.mslAccuracy : null), + 'android_msl', + ); + } + if (fix.hasAltitude && meters == fix.altitude) { + return AltitudeResolution( + FixAltitude.known( + meters: meters, + reference: AltitudeReference.ellipsoid, + accuracy: fix.hasVerticalAccuracy ? fix.verticalAccuracy : null), + 'android_ellipsoid', + ); + } + } + if (!sawTime) return const AltitudeResolution.unknown('time_differs'); + if (!sawCoord) return const AltitudeResolution.unknown('coord_differs'); + if (sawMock) return const AltitudeResolution.unknown('native_mock'); + return const AltitudeResolution.unknown('value_differs'); + } +} diff --git a/lib/services/fix_altitude_resolver.dart b/lib/services/fix_altitude_resolver.dart new file mode 100644 index 00000000..22ec7dad --- /dev/null +++ b/lib/services/fix_altitude_resolver.dart @@ -0,0 +1,256 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:geolocator/geolocator.dart'; + +import '../utils/debug_logger_io.dart'; +import 'fix_altitude.dart'; + +/// One answer per fix, keyed on everything the rule reads from the fix: its +/// timestamp, coordinates, altitude, altitude accuracy and mock flag. Two +/// fixes that share only a time and place (a mocked twin, or a different +/// altitude) must never share an answer, completed or pending. +typedef _FixKey = ({ + int timeMs, + double? lat, + double? lon, + double? altitude, + double? altitudeAccuracy, + bool isMocked, +}); + +/// NaN never equals itself, so it would make every lookup a fresh key. It is +/// keyed as null instead; every other double, infinities included, is +/// compared exactly. +double? _keyDouble(double v) => v.isNaN ? null : v; + +_FixKey _keyOf(Position p) => ( + timeMs: p.timestamp.millisecondsSinceEpoch, + lat: _keyDouble(p.latitude), + lon: _keyDouble(p.longitude), + altitude: _keyDouble(p.altitude), + altitudeAccuracy: _keyDouble(p.altitudeAccuracy), + isMocked: p.isMocked, + ); + +/// Running counts of how the Android proof went, for one bounded summary +/// line and for the device check. Real Android fixes only: simulator fixes +/// and fixes with no altitude are unknown by rule, not by failure. +class AltitudeResolutionStats { + int proved = 0; + int unproved = 0; + final Map reasons = {}; +} + +/// Resolves and remembers [FixAltitude] for every fix the GPS service +/// accepts, so the send paths can read a finished answer later without +/// waiting for anything. +/// +/// Nothing waits on this store. iOS, web and simulator fixes are answered +/// synchronously inside [track]. Android fixes need the native handler's +/// description of the provider's last fix, which is read in the background; +/// until it lands, [lookup] answers unknown. An entry is inserted (as +/// unknown) the moment the fix is ACCEPTED, so eviction follows acceptance +/// order and a late completion for an evicted fix is dropped rather than +/// resurrected. A source generation, bumped by [reset], discards late +/// completions from a fix source that has since restarted (watching +/// restarted, the simulator switched on or off). +/// +/// Completion touches nothing else: no position is re-emitted, nothing is +/// notified and `mapRevision` is never bumped (Rule 9). Logging is one line +/// the first time a reference is resolved per generation, one throttled +/// warning when an Android fix could not be proved, and one summary line per +/// [summaryEvery] Android resolutions, never one line per fix. +class FixAltitudeResolver { + FixAltitudeResolver({ + required this.platform, + this.readNative, + DateTime Function()? now, + this.capacity = 128, + this.nativeTimeout = const Duration(seconds: 2), + }) : _now = now ?? DateTime.now; + + final AltitudePlatform platform; + + /// Reads the Android handler's description of the provider's last fix. + /// Null on every platform but Android. Null answers mean "nothing proved". + final Future Function()? readNative; + + final DateTime Function() _now; + final int capacity; + final Duration nativeTimeout; + + static const Duration _warnSpacing = Duration(minutes: 1); + + /// One summary line per this many real Android resolutions. + static const int summaryEvery = 50; + + final LinkedHashMap<_FixKey, FixAltitude> _store = LinkedHashMap(); + + /// Keys whose native read is in flight, independent of cache eviction: a + /// fix evicted and accepted again while its read is still out must not be + /// read twice, counted twice, or have the older answer overwrite the newer. + final Set<_FixKey> _inFlight = {}; + final Set> _pending = {}; + final AltitudeResolutionStats _stats = AltitudeResolutionStats(); + int _generation = 0; + int? _androidSdk; + bool _loggedFirst = false; + DateTime? _lastWarn; + + int get generation => _generation; + int get size => _store.length; + AltitudeResolutionStats get stats => _stats; + + /// Completes once every native read started so far has settled. Tests only. + Future get idle => Future.wait(_pending.toList()).then((_) {}); + + /// Forgets everything and invalidates every read in flight. Called whenever + /// the fix source restarts. + void reset() { + _generation++; + _store.clear(); + _inFlight.clear(); + _loggedFirst = false; + } + + /// Resolves [position] if it is not already stored or in flight. + void track(Position position, {bool simulated = false}) { + final key = _keyOf(position); + if (_store.containsKey(key)) return; + if (_inFlight.contains(key)) { + // Evicted while its read was out and now accepted again: re-reserve the + // slot so the pending answer has somewhere to land, but do not read + // again. + _insert(key); + return; + } + + final needsNative = !simulated && + platform == AltitudePlatform.android && + readNative != null && + (_androidSdk == null || _androidSdk! >= kAndroidMslSdk); + + if (!needsNative) { + final native = platform == AltitudePlatform.android && _androidSdk != null + ? NativeAltitudeAnswer(sdk: _androidSdk!, fixes: const []) + : null; + _insert(key); + _complete( + key, + resolveFixAltitude( + platform: platform, + position: position, + simulated: simulated, + native: native, + ), + simulated: simulated, + ); + return; + } + + // Reserve the slot now so eviction follows acceptance order; the answer + // replaces the unknown placeholder when the read lands. + _insert(key); + _inFlight.add(key); + final generation = _generation; + late Future work; + work = _resolveNative(key, position, generation).whenComplete(() { + _pending.remove(work); + }); + _pending.add(work); + } + + Future _resolveNative( + _FixKey key, Position position, int generation) async { + NativeAltitudeAnswer? native; + String? failure; + try { + native = await readNative!().timeout(nativeTimeout); + } on TimeoutException { + failure = 'native read timed out'; + } catch (e) { + failure = 'native read threw: $e'; + } + if (generation != _generation) return; // the fix source restarted + _inFlight.remove(key); + if (native != null) _androidSdk = native.sdk; + final resolution = resolveFixAltitude( + platform: platform, + position: position, + simulated: false, + native: native, + ); + if (!_store.containsKey(key)) { + // Evicted while in flight: the read still happened, so it counts once + // toward the proof stats, but it is never stored or resurrected. + _count(resolution, simulated: false); + return; + } + _complete(key, resolution, simulated: false, failure: failure); + } + + /// The stored answer for [position], or unknown when none has landed. + FixAltitude lookup(Position position) => + _store[_keyOf(position)] ?? const FixAltitude.unknown(); + + void _insert(_FixKey key) { + _store[key] = const FixAltitude.unknown(); + while (_store.length > capacity) { + _store.remove(_store.keys.first); + } + } + + void _complete(_FixKey key, AltitudeResolution resolution, + {required bool simulated, String? failure}) { + _store[key] = resolution.altitude; + _count(resolution, simulated: simulated); + _log(resolution, simulated: simulated, failure: failure); + } + + void _count(AltitudeResolution resolution, {required bool simulated}) { + if (simulated || + platform != AltitudePlatform.android || + resolution.reason == 'no_altitude' || + resolution.reason == 'mocked') { + return; + } + if (resolution.altitude.isKnown) { + _stats.proved++; + } else { + _stats.unproved++; + _stats.reasons.update(resolution.reason, (n) => n + 1, + ifAbsent: () => 1); + } + final total = _stats.proved + _stats.unproved; + if (total % summaryEvery == 0) { + debugLog('[GPS] Altitude reference summary: ${_stats.proved} of $total ' + 'fixes proved, unknown by reason: ${_stats.reasons}'); + } + } + + void _log(AltitudeResolution resolution, + {required bool simulated, String? failure}) { + if (resolution.altitude.isKnown) { + if (_loggedFirst) return; + _loggedFirst = true; + debugLog('[GPS] Altitude reference resolved: ' + '${resolution.altitude.wireReference} (${resolution.reason})'); + return; + } + // Only an Android fix that could not be proved is worth a warning. A + // simulator fix, a fix with no altitude and a non-Android platform are + // unknown by rule, not by failure. + if (simulated || + platform != AltitudePlatform.android || + resolution.reason == 'no_altitude' || + resolution.reason == 'mocked') { + return; + } + final now = _now(); + if (_lastWarn != null && now.difference(_lastWarn!) < _warnSpacing) return; + _lastWarn = now; + debugWarn('[GPS] Altitude reference unknown for this fix: ' + '${resolution.reason}${failure != null ? ' ($failure)' : ''}'); + } +} diff --git a/lib/services/gps_service.dart b/lib/services/gps_service.dart index 411d931a..5c74fd1a 100644 --- a/lib/services/gps_service.dart +++ b/lib/services/gps_service.dart @@ -3,17 +3,94 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:geolocator/geolocator.dart'; -import 'package:permission_handler/permission_handler.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../models/connection_state.dart'; import '../utils/debug_logger_io.dart'; import '../utils/geo_validation.dart'; import 'gps_simulator_service.dart'; +import 'location_consent.dart'; +import 'android_altitude_channel.dart'; +import 'fix_altitude.dart'; +import 'fix_altitude_resolver.dart'; + +/// The position stream settings: high accuracy and a 10 m distance filter +/// everywhere. On Android, both Google's fused provider and Android's own +/// location service ([useAndroidLocationManager]) are asked for a fix every +/// second: left unset, the plugin asks every 5 s, and pings reused a stale +/// fix while driving. `useMSLAltitude` stays off; see the note at the stream. +@visibleForTesting +LocationSettings gpsStreamSettings({ + required bool isAndroid, + required bool useAndroidLocationManager, +}) => + isAndroid + ? AndroidSettings( + accuracy: LocationAccuracy.high, + distanceFilter: 10, + intervalDuration: const Duration(seconds: 1), + forceLocationManager: useAndroidLocationManager, + ) + : const LocationSettings( + accuracy: LocationAccuracy.high, + distanceFilter: 10, + ); + +/// Whether a position stream error means the user declined Google's +/// "Location Accuracy" dialog rather than turned location off, so GPS should +/// move to Android's own location service, which never shows that dialog. +/// The plugin reports both as location services disabled; only a decline +/// leaves the device location setting on. Declining used to loop: the error +/// marked GPS disabled, the dialog closing resumed the app, the resume +/// restarted GPS, and the restart showed the dialog again (#595). +@visibleForTesting +bool shouldUseAndroidLocationManager({ + required bool isAndroid, + required bool alreadyUsing, + required Object error, + required bool deviceLocationOn, +}) => + isAndroid && + !alreadyUsing && + error is LocationServiceDisabledException && + deviceLocationOn; /// GPS service for location tracking /// Ported from wardrive.js geolocation logic /// Note: Zone validation is now handled server-side by the API class GpsService { + GpsService({FixAltitudeResolver? altitudeResolver}) + : _altitude = altitudeResolver ?? _defaultAltitudeResolver(); + + /// Resolves and remembers each fix's altitude reference. See + /// `fix_altitude.dart` for the rule and `fix_altitude_resolver.dart` for + /// the store. Reset whenever the fix source restarts. + final FixAltitudeResolver _altitude; + + static FixAltitudeResolver _defaultAltitudeResolver() { + final AltitudePlatform platform; + if (kIsWeb) { + platform = AltitudePlatform.web; + } else if (defaultTargetPlatform == TargetPlatform.android) { + platform = AltitudePlatform.android; + } else if (defaultTargetPlatform == TargetPlatform.iOS) { + platform = AltitudePlatform.ios; + } else { + platform = AltitudePlatform.other; + } + return FixAltitudeResolver( + platform: platform, + readNative: platform == AltitudePlatform.android + ? AndroidAltitudeChannel().describeLastFix + : null, + ); + } + + /// The altitude [position] may be uploaded with: meters, reference and + /// accuracy, or unknown when the reference is not (yet) proved. Resolved + /// in the background when the fix was accepted; nothing waits here. + FixAltitude fixAltitudeOf(Position position) => _altitude.lookup(position); + /// Minimum distance (meters) from last ping before allowing new ping static const double minDistanceMeters = 25.0; @@ -39,6 +116,13 @@ class GpsService { /// trips it too; that is accepted. static const double airborneSpeedMetersPerSecond = 250.0 / 3.6; + /// Airborne block: a fix whose altitude clears [airborneAltitudeMeters] + /// only counts when its speed is unknown or at least this (150 km/h). + /// Nothing above 6,000 m flies that slowly, so a known slower speed means + /// the altitude is the bad reading (an iOS fix once read 18,490 m in a car + /// doing 8 km/h). + static const double airborneAltitudeMinSpeedMetersPerSecond = 150.0 / 3.6; + /// Consecutive fixes needed to set or clear the airborne latch. One wild /// fix is GPS jitter, three in a row is real (same idea as the provider's /// idle-anchor streak). @@ -73,6 +157,36 @@ class GpsService { Position? _lastActivityPosition; StreamSubscription? _positionSubscription; + /// Counts every startWatching() and stopWatching(). A startWatching() call + /// that finds the count changed after an await has been overtaken (by a + /// newer start or by a stop) and must end without touching any state. + int _watchGeneration = 0; + + /// True from the first statement of startWatching() until stopWatching() + /// runs or a start ends with no stream for a reason of its own (location + /// services off, no permission, no consent). + bool _watchRequested = false; + + /// Whether GPS is meant to be running. A start still in flight counts, so + /// a caller deciding whether to restart does not start a second one. + bool get isWatching => _watchRequested; + + /// Android only: read GPS through Android's location service instead of + /// Google's. See [shouldUseAndroidLocationManager]. Saved under + /// [_androidLocationManagerKey] so later runs start there and never show + /// Google's dialog again. + bool _useAndroidLocationManager = false; + bool _androidLocationManagerLoaded = false; + static const String _androidLocationManagerKey = + 'gps_android_location_manager'; + + /// The stream settings: Google's fused provider on Android, or Android's + /// own location service once that is in use. See [gpsStreamSettings]. + LocationSettings _streamSettings() => gpsStreamSettings( + isAndroid: !kIsWeb && defaultTargetPlatform == TargetPlatform.android, + useAndroidLocationManager: _useAndroidLocationManager, + ); + /// Airborne latch state. See [trackAirborne]. int _airborneStreak = 0; int _groundStreak = 0; @@ -144,12 +258,8 @@ class GpsService { /// platforms. Android also omits the accuracy on fixes that DO carry an /// altitude, so the accuracy alone cannot decide; only the 0/0 pair means /// unknown. - static double? altitudeOrNull(Position position) { - if (position.altitude == 0.0 && position.altitudeAccuracy == 0.0) { - return null; - } - return position.altitude; - } + static double? altitudeOrNull(Position position) => + reportedAltitudeOrNull(position); /// The ground speed a fix actually carries in m/s, or null when the /// platform had none. Same shape as [altitudeOrNull]: geolocator reports a @@ -164,14 +274,25 @@ class GpsService { /// Pure gate: does this single fix look like it came from an aircraft? /// /// The altitude test subtracts the fix's own vertical error first, so a - /// shaky reading has to be well clear of the line. Unknown altitude and - /// unknown speed arrive as 0.0 and never qualify (fail open). + /// shaky reading has to be well clear of the line, and is ignored when the + /// fix's own known speed is too slow for anything at that height. Unknown + /// altitude and unknown speed arrive as 0.0 and never qualify (fail open). static bool positionLooksAirborne(Position position) { - final altitudeFloor = position.altitude - position.altitudeAccuracy; - return altitudeFloor > airborneAltitudeMeters || + return _altitudeGateFires(position) || position.speed > airborneSpeedMetersPerSecond; } + /// The altitude half of [positionLooksAirborne], shared with the latch so + /// the recorded gate always agrees with the test that let the fix through. + /// A known speed under [airborneAltitudeMinSpeedMetersPerSecond] + /// contradicts the altitude, so the fix does not qualify on it. + static bool _altitudeGateFires(Position position) { + final altitudeFloor = position.altitude - position.altitudeAccuracy; + if (altitudeFloor <= airborneAltitudeMeters) return false; + final speed = speedOrNull(position); + return speed == null || speed >= airborneAltitudeMinSpeedMetersPerSecond; + } + /// Feed one accepted fix into the airborne latch. /// /// Every path that accepts a fix (the position stream, the simulator and @@ -187,8 +308,7 @@ class GpsService { _airborneStreak++; if (!_airborne && _airborneStreak >= airborneStreakRequired) { _airborne = true; - final altitudeFloor = position.altitude - position.altitudeAccuracy; - _airborneGate = altitudeFloor > airborneAltitudeMeters + _airborneGate = _altitudeGateFires(position) ? AirborneGate.altitude : AirborneGate.speed; // Both readings of the latching fix, each null when unknown. @@ -257,34 +377,6 @@ class GpsService { permission == LocationPermission.whileInUse; } - /// Request GPS permissions (When In Use) - Future requestPermissions() async { - debugLog('[GPS] Requesting location permission...'); - LocationPermission permission = await Geolocator.checkPermission(); - debugLog('[GPS] Current permission: $permission'); - - if (permission == LocationPermission.denied) { - permission = await Geolocator.requestPermission(); - debugLog('[GPS] Permission result after request: $permission'); - } - - if (permission == LocationPermission.deniedForever) { - debugLog( - '[GPS] Permission denied forever - user must enable in Settings'); - _updateStatus(GpsStatus.permissionDenied); - return false; - } - - if (permission == LocationPermission.denied) { - debugLog('[GPS] Permission denied by user'); - _updateStatus(GpsStatus.permissionDenied); - return false; - } - - debugLog('[GPS] Permission granted: $permission'); - return true; - } - /// Check if "Always" location permission is granted Future hasAlwaysPermission() async { final permission = await Geolocator.checkPermission(); @@ -293,9 +385,15 @@ class GpsService { /// Request "Always" location permission for background mode /// On iOS, this triggers the second permission dialog after "When In Use" is granted - /// On Android 10+, this triggers the "Allow all the time" dialog + /// Android never asks: its session service keeps GPS running in the + /// background with "While in use" permission /// Returns true if permission is granted, false otherwise Future requestAlwaysPermission() async { + if (Platform.isAndroid) { + debugLog('[GPS] Always permission is iOS only'); + return false; + } + debugLog('[GPS] Requesting Always location permission'); final current = await Geolocator.checkPermission(); @@ -313,19 +411,10 @@ class GpsService { return false; } - // Platform-specific request - if (Platform.isAndroid) { - // Android: Use permission_handler to request locationAlways - // This triggers "Allow all the time" dialog on Android 10+ - final status = await Permission.locationAlways.request(); - debugLog('[GPS] Android always permission result: $status'); - return status.isGranted; - } else { - // iOS: Use Geolocator for the upgrade dialog - final permission = await Geolocator.requestPermission(); - debugLog('[GPS] iOS permission result: $permission'); - return permission == LocationPermission.always; - } + // iOS: Use Geolocator for the upgrade dialog + final permission = await Geolocator.requestPermission(); + debugLog('[GPS] iOS permission result: $permission'); + return permission == LocationPermission.always; } /// Check if location services are enabled @@ -336,9 +425,25 @@ class GpsService { /// Start watching position /// Note: This only CHECKS permissions, does not REQUEST them. /// Permission requests are handled by the disclosure flow in MainScaffold. - Future startWatching() async { + /// + /// A [stopWatching] or a newer call during any await below wins: this call + /// then ends without storing a stream or touching the status. + /// + /// [keepTracking] is for restarting a watcher that was running a moment ago + /// (the app returning from the background). It leaves the airborne latch + /// and the altitude tracker alone, so Connect is not re-armed mid-flight, + /// and skips the one-off position read, which can show Google's accuracy + /// dialog again (#595). The stream starts as usual. + Future startWatching({bool keepTracking = false}) async { debugLog('[GPS] startWatching() called, current status: $_status'); - resetAirborne(); + final generation = ++_watchGeneration; + _watchRequested = true; + if (!keepTracking) { + resetAirborne(); + _altitude.reset(); + } + await _loadAndroidLocationManagerChoice(); + if (_isSuperseded(generation)) return; // Ensure only one active position stream subscription exists. // startWatching() can be called multiple times (e.g. after permission flow). @@ -346,15 +451,20 @@ class GpsService { debugLog( '[GPS] Existing position subscription found, restarting watcher'); await _positionSubscription?.cancel(); + // Checked before the field is cleared: a newer start may have stored + // its own stream by now. + if (_isSuperseded(generation)) return; _positionSubscription = null; } // Check if location services are enabled first (system-level setting) final serviceEnabled = await isLocationServiceEnabled(); + if (_isSuperseded(generation)) return; debugLog('[GPS] Location services check: enabled=$serviceEnabled'); if (!serviceEnabled) { debugLog( '[GPS] Location services DISABLED at system level - user must enable in Settings'); + _watchRequested = false; _updateStatus(GpsStatus.disabled); return; } @@ -366,6 +476,7 @@ class GpsService { if (!kIsWeb) { // Check permissions (don't request - disclosure flow handles that) final permission = await Geolocator.checkPermission(); + if (_isSuperseded(generation)) return; final hasPermission = permission == LocationPermission.always || permission == LocationPermission.whileInUse; debugLog( @@ -378,6 +489,18 @@ class GpsService { debugLog( '[GPS] Permission not granted - waiting for disclosure flow'); } + _watchRequested = false; + _updateStatus(GpsStatus.permissionDenied); + return; + } + // Google Play: no location is read before the disclosure is agreed + // to, even when the permission was granted some other way. + final agreed = await LocationConsent.hasAgreed(); + if (_isSuperseded(generation)) return; + if (!agreed) { + debugLog('[GPS] Location disclosure not agreed yet - ' + 'waiting for disclosure flow'); + _watchRequested = false; _updateStatus(GpsStatus.permissionDenied); return; } @@ -391,6 +514,9 @@ class GpsService { // Cancel any existing subscription to prevent orphaned listeners // (e.g. restartGpsAfterPermission() racing with _initialize()) await _positionSubscription?.cancel(); + // Last await before the stream is created and stored just below, so a + // call that passes this check cannot be overtaken before it stores. + if (_isSuperseded(generation)) return; _positionSubscription = null; _updateStatus(GpsStatus.searching); @@ -398,12 +524,14 @@ class GpsService { // Configure location settings for position stream // Note: No timeLimit - we want continuous GPS tracking even when stationary // The distanceFilter handles update frequency (10m for RX batch checks at 25m) - _positionSubscription = Geolocator.getPositionStream( - locationSettings: const LocationSettings( - accuracy: LocationAccuracy.high, - distanceFilter: - 10, // Trigger every 10m movement (check RX batches at 25m) - ), + // No `AndroidSettings(useMSLAltitude: true)`: the altitude reference rule + // in fix_altitude.dart relies on the plugin never substituting an NMEA + // sea level value. Enabling it would invalidate the pre Android 14 + // ellipsoid label. The 10 m distance filter triggers the RX batch checks + // (at 25 m). + late final StreamSubscription subscription; + subscription = Geolocator.getPositionStream( + locationSettings: _streamSettings(), ).listen( (position) { debugLog( @@ -418,43 +546,141 @@ class GpsService { return; } _lastPosition = position; + _altitude.track(position); trackAirborne(position); + recordRecentFix(position); _positionController.add(position); // GPS signal acquired _updateStatus(GpsStatus.locked); }, - onError: (error) { + onError: (Object error) async { debugError('[GPS SERVICE] Position stream error: $error'); + if (await _switchToAndroidLocationManagerIfDeclined( + error, generation, keepTracking)) { + return; + } + // A restart replaced this stream while the check above awaited: the + // error is the old stream's and must not mark the new one disabled. + if (!identical(_positionSubscription, subscription)) return; _updateStatus(GpsStatus.disabled); }, ); + _positionSubscription = subscription; + + // A quiet restart leaves out the one-off read: it can show Google's + // accuracy dialog again, and the stream delivers the first fix anyway. + if (keepTracking) return; // Get initial position debugLog('[GPS] Requesting initial position (15s timeout)...'); try { final position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, + forceAndroidLocationManager: _useAndroidLocationManager, timeLimit: const Duration(seconds: 15), ); + if (_isSuperseded(generation)) return; debugLog( '[GPS] Initial position acquired: ${position.latitude.toStringAsFixed(5)}, ' '${position.longitude.toStringAsFixed(5)} (accuracy: ${position.accuracy.toStringAsFixed(1)}m)'); _lastPosition = position; + _altitude.track(position); + recordRecentFix(position); // Note: Don't emit via _positionController here — the stream listener // at line 198 already fires with the initial position, so emitting here // would cause duplicate position events (~0.15ms apart). _updateStatus(GpsStatus.locked); } catch (e) { + // This one-off read shows its own copy of Google's dialog, and its + // decline switches GPS just like the stream's. + if (_isSuperseded(generation)) return; + if (await _switchToAndroidLocationManagerIfDeclined( + e, generation, keepTracking)) { + return; + } debugLog( '[GPS] Initial position request failed: $e (will wait for stream updates)'); // Will receive updates from stream } } - /// Stop watching position + /// Reads the saved location service choice, once per run (Android only). + Future _loadAndroidLocationManagerChoice() async { + if (_androidLocationManagerLoaded || kIsWeb || !Platform.isAndroid) return; + _androidLocationManagerLoaded = true; + try { + final prefs = await SharedPreferences.getInstance(); + if (prefs.getBool(_androidLocationManagerKey) == true) { + _useAndroidLocationManager = true; + debugLog('[GPS] Using the Android location service (Google Location ' + 'Accuracy was declined on an earlier run)'); + } + } catch (e) { + debugWarn('[GPS] Could not read the location service choice: $e'); + } + } + + /// Moves GPS to Android's location service when [error] is a declined + /// Google "Location Accuracy" dialog, saves the choice and restarts the + /// watcher. True when this or another caller made the switch for this + /// error, so the caller must not mark GPS disabled. + /// + /// [generation] belongs to the startWatching() call that met [error]. If a + /// stop or a newer start came during an await here, nothing is switched or + /// restarted, and the result is true so the caller leaves GPS alone: the + /// overtaking call owns it now. [keepTracking] is passed on to the restart. + Future _switchToAndroidLocationManagerIfDeclined( + Object error, int generation, bool keepTracking) async { + final isAndroid = !kIsWeb && Platform.isAndroid; + if (!isAndroid || _useAndroidLocationManager) return false; + if (error is! LocationServiceDisabledException) return false; + var deviceLocationOn = false; + try { + deviceLocationOn = await Geolocator.isLocationServiceEnabled(); + } catch (_) {} + // Checked before the switch is recorded: a stale error must not set it + // with no restart, or a newer stream's own decline would find it set and + // mark GPS disabled. + if (_isSuperseded(generation)) return true; + // The stream and the first one-off read can be declined together: + // whichever finishes the check second finds the switch already made. + if (_useAndroidLocationManager) return true; + if (!shouldUseAndroidLocationManager( + isAndroid: isAndroid, + alreadyUsing: false, + error: error, + deviceLocationOn: deviceLocationOn)) { + return false; + } + _useAndroidLocationManager = true; + debugWarn('[GPS] Google Location Accuracy declined with device location ' + 'on: using the Android location service from now on'); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_androidLocationManagerKey, true); + } catch (e) { + debugWarn('[GPS] Could not save the location service choice: $e'); + } + if (_isSuperseded(generation)) return true; + await startWatching(keepTracking: keepTracking); + return true; + } + + /// True when a stopWatching() or a newer startWatching() came after the + /// call that took [generation]. That call must then return at once. + bool _isSuperseded(int generation) { + if (generation == _watchGeneration) return false; + debugLog('[GPS] startWatching() superseded'); + return true; + } + + /// Stop watching position. Wins over a startWatching() still in flight: + /// that call ends without storing a stream. void stopWatching() { debugLog('[GPS] stopWatching() called'); + _watchGeneration++; + _watchRequested = false; _positionSubscription?.cancel(); _positionSubscription = null; } @@ -564,6 +790,71 @@ class GpsService { return null; // Valid } + /// Fixes seen recently, oldest first, capped at [_recentFixCap]. Feeds + /// [bestRecentZoneCheckFix], so a coarse fix that lands just after a good + /// one cannot stand in for it at a zone check or the connect /auth. + final List _recentFixes = []; + static const int _recentFixCap = 30; + + /// Remember a real fix for [bestRecentZoneCheckFix]. Called wherever a fix + /// becomes [lastPosition] (stream, initial read, fresh read, simulator). + void recordRecentFix(Position position) { + _recentFixes.add(position); + if (_recentFixes.length > _recentFixCap) _recentFixes.removeAt(0); + } + + /// Whether [position] is accurate enough for the server's zone check and + /// /auth (50 m). Age is NOT part of this: the server stamps those requests + /// with the send time, and a stationary phone's stream goes quiet, so an + /// old but accurate fix is still the right one to send. + static bool isAccurateForZoneCheck(Position position) => + position.accuracy <= maxAccuracyMetersForZoneCheck; + + /// Pure pick behind [bestRecentZoneCheckFix]: the NEWEST fix in [fixes] + /// that is accurate enough for a zone check and no older than + /// [maxGpsAgeForManualPing] at [now], or null when there is none. Newest + /// rather than most accurate, because the phone may have moved since. + static Position? pickZoneCheckFix(Iterable fixes, DateTime now) { + Position? best; + for (final fix in fixes) { + if (!isAccurateForZoneCheck(fix)) continue; + if (now.difference(fix.timestamp) > maxGpsAgeForManualPing) continue; + if (best == null || !fix.timestamp.isBefore(best.timestamp)) best = fix; + } + return best; + } + + /// The newest recent fix good enough for a zone check or /auth, or null. + Position? bestRecentZoneCheckFix({DateTime? now}) => + pickZoneCheckFix(_recentFixes, now ?? DateTime.now()); + + /// Wait at most [timeout] for a fix good enough for a zone check or /auth. + /// Returns a recent one at once when there is one; otherwise takes the + /// first accurate fix from the stream or from one fresh hardware read + /// (the stream is quiet while the phone stands still). Null on timeout. + Future waitForZoneCheckFix(Duration timeout) async { + final recent = bestRecentZoneCheckFix(); + if (recent != null) return recent; + + final completer = Completer(); + void offer(Position? fix) { + if (completer.isCompleted || fix == null) return; + if (isAccurateForZoneCheck(fix)) completer.complete(fix); + } + + final sub = positionStream.listen(offer); + final timer = Timer(timeout, () { + if (!completer.isCompleted) completer.complete(null); + }); + unawaited(getFreshPosition(timeout: timeout).then(offer)); + try { + return await completer.future; + } finally { + timer.cancel(); + await sub.cancel(); + } + } + /// Request a fresh GPS position from the hardware for auto-ping accuracy. /// On mobile, this forces a warm-start GPS read (typically < 1 second when /// GPS is already streaming). Falls back to lastPosition on timeout/error. @@ -577,6 +868,7 @@ class GpsService { try { final position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, + forceAndroidLocationManager: _useAndroidLocationManager, timeLimit: timeout, ); debugLog( @@ -588,7 +880,9 @@ class GpsService { return _lastPosition; } _lastPosition = position; + _altitude.track(position); trackAirborne(position); + recordRecentFix(position); return position; } catch (e) { debugLog('[GPS] Fresh position request failed, using cached: $e'); @@ -596,35 +890,6 @@ class GpsService { } } - /// Get current position (single request) - Future getCurrentPosition() async { - if (!await requestPermissions()) { - debugLog('[GPS] getCurrentPosition failed: permission denied'); - return null; - } - - if (!await isLocationServiceEnabled()) { - debugLog('[GPS] getCurrentPosition failed: location services disabled'); - return null; - } - - try { - final position = await Geolocator.getCurrentPosition( - desiredAccuracy: LocationAccuracy.high, - timeLimit: const Duration(seconds: 15), - ); - if (!isValidLatLng(position.latitude, position.longitude)) { - debugWarn( - '[GPS] getCurrentPosition returned invalid coords: lat=${position.latitude}, lon=${position.longitude}'); - return null; - } - return position; - } catch (e) { - debugLog('[GPS] getCurrentPosition failed: $e'); - return null; - } - } - /// Calculate distance between two positions in meters static double distanceBetween( double startLat, @@ -651,6 +916,7 @@ class GpsService { // Stop real GPS stopWatching(); resetAirborne(); + _altitude.reset(); // Configure and start simulator simulator.configure( @@ -669,7 +935,9 @@ class GpsService { return; } _lastPosition = position; + _altitude.track(position, simulated: true); trackAirborne(position); + recordRecentFix(position); _positionController.add(position); // Simulator position acquired @@ -683,7 +951,9 @@ class GpsService { final seed = simulator.currentPosition; if (seed != null && isValidLatLng(seed.latitude, seed.longitude)) { _lastPosition = seed; + _altitude.track(seed, simulated: true); trackAirborne(seed); + recordRecentFix(seed); _positionController.add(seed); } @@ -724,6 +994,7 @@ class GpsService { /// Dispose of resources void dispose() { + _altitude.reset(); stopWatching(); simulator.dispose(); _simulatorSubscription?.cancel(); diff --git a/lib/services/idle_session.dart b/lib/services/idle_session.dart new file mode 100644 index 00000000..1b313b40 --- /dev/null +++ b/lib/services/idle_session.dart @@ -0,0 +1,24 @@ +/// Whether nothing in the app would use a live API session right now. +/// +/// Read by the scheduled keepalive when the server answers `session_expired`: +/// an idle app lets the session lapse instead of minting a replacement that +/// would never see a ping (an Android process frozen in the background after +/// a stopped mode, resumed later). Anything running, stopping, starting, in +/// flight, held open or waiting to upload counts as busy, and recovery then +/// runs exactly as before. +bool sessionIsIdle({ + required bool autoPingEnabled, + required bool autoPingStarting, + required bool pendingDisable, + required bool pingSending, + required bool pingInProgress, + required bool repeaterAdminOpen, + required int queuedItems, +}) => + !autoPingEnabled && + !autoPingStarting && + !pendingDisable && + !pingSending && + !pingInProgress && + !repeaterAdminOpen && + queuedItems == 0; diff --git a/lib/services/link_decision.dart b/lib/services/link_decision.dart index d7ecb97f..d996b570 100644 --- a/lib/services/link_decision.dart +++ b/lib/services/link_decision.dart @@ -48,3 +48,31 @@ LinkFlowDecision decideLinkFlow({ if (promptedThisAppSession) return LinkFlowDecision.skip; return LinkFlowDecision.prompt; } + +/// What the link flow does with a failed radio sign. +enum SignFailureAction { + /// Count a strike towards "this firmware cannot sign" (two persist it). + strike, + + /// A transient failure: back off with the usual retry ladder, no strike. + backoff, + + /// Give up quietly for this attempt. + silent, +} + +/// Maps a `SignException` code to what the link flow does with it. `busy` +/// means scope discovery held the radio for the whole wait, which says +/// nothing about the firmware, so it never counts as an `unsupported` strike. +SignFailureAction signFailureAction(String code) => switch (code) { + 'unsupported' => SignFailureAction.strike, + 'busy' => SignFailureAction.backoff, + _ => SignFailureAction.silent, + }; + +/// Whether a failed sign was the radio refusing part way: it took +/// CMD_SIGN_START, then answered ERR (`err`). On MeshCore-Solo and mishmesh +/// fork firmware that is a memory fault only a reboot clears, so a manual +/// link says to reboot instead of "try again later". A stray ERR from another +/// command can land here too; rebooting does no harm then. +bool signFailureNeedsRadioReboot(String code) => code == 'err'; diff --git a/lib/services/live_activity/live_activity_heard.dart b/lib/services/live_activity/live_activity_heard.dart index 8f40bd28..0efdb2e0 100644 --- a/lib/services/live_activity/live_activity_heard.dart +++ b/lib/services/live_activity/live_activity_heard.dart @@ -4,11 +4,12 @@ import 'live_activity_models.dart'; /// The Live Activity's heard rows, read from the map's Top Heard box. /// -/// One source for the map, the watch and the Live Activity: [top] is the -/// latest ping's top three by SNR exactly as the map overlay stores them, and -/// [rxSlot] the best passive observation of the current interval. The order is -/// the map's too, ping rows first and the RX row trailing, never a global SNR -/// sort, so the card's first rows are always the box's first rows. +/// One source for the map, the watch and the Live Activity: [top] is the first +/// three of the latest ping's rows by SNR, in the order the map overlay stores +/// them (the in-app box may show more of that list), and [rxSlot] the best +/// passive observation of the current interval. The order is the map's too, +/// ping rows first and the RX row trailing, never a global SNR sort, so the +/// card's first rows are always the box's first rows. /// /// The one place this departs from the map is a repeater that is both a ping /// row and the RX slot: the map draws it twice, this returns it once, because @@ -22,10 +23,15 @@ import 'live_activity_models.dart'; /// dimmed, so a silent ping never reads as an old result left on screen. /// A fresh RX observation during such a cycle is the only current thing, so it /// is shown on its own. +/// +/// [topHeardIds] is every repeater the latest ping heard (upper-case display +/// IDs), not only the [top] rows shown. The "HEARD NOW" total counts them, plus +/// the RX repeater only when the ping did not hear it, so an RX repeater the +/// ping ranked below the shown rows is not counted twice. ({List repeaters, int totalCount, bool isCurrent}) buildLiveActivityHeard({ required List<({String repeaterId, double snr, OverlayPingType type})> top, - required int topTotalCount, + required Set topHeardIds, required ({String repeaterId, double snr})? rxSlot, required DateTime? topAt, required DateTime? rxAt, @@ -65,7 +71,7 @@ import 'live_activity_models.dart'; } } - var totalCount = topIsCurrent ? topTotalCount : 0; + var totalCount = topIsCurrent ? topHeardIds.length : 0; if (rxIsCurrent && rxSlot != null && rxSlot.snr.isFinite) { final id = rxSlot.repeaterId.toUpperCase(); if (shown.add(id)) { @@ -78,8 +84,8 @@ import 'live_activity_models.dart'; snrColor: ExternalSurfaceGeoBuilder.snrColor(rxSlot.snr), )); } - final pingHeardIt = top.any((row) => row.repeaterId.toUpperCase() == id); - if (!pingHeardIt) totalCount++; + final pingCountedIt = topIsCurrent && topHeardIds.contains(id); + if (!pingCountedIt) totalCount++; } if (totalCount < repeaters.length) totalCount = repeaters.length; diff --git a/lib/services/location_consent.dart b/lib/services/location_consent.dart new file mode 100644 index 00000000..debda8d4 --- /dev/null +++ b/lib/services/location_consent.dart @@ -0,0 +1,36 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +/// Whether the person has agreed to the location disclosure on this install. +/// Google Play wants it agreed before the app reads any location, and shown +/// again right before every system location prompt. +/// +/// Kept apart from the dialog (`PermissionDisclosureService`) so GpsService +/// can check it without importing UI code. +class LocationConsent { + LocationConsent._(); + + /// Set when the person taps Agree. The key predates the Agree button, so + /// Continue on the old dialog counts as agreeing. + static const String _agreedKey = 'location_disclosure_shown'; + + /// True once the location disclosure has been agreed to. Until then the + /// app reads no location, even when the permission is already granted + /// (review devices can install with it granted). + static Future hasAgreed() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getBool(_agreedKey) ?? false; + } + + static Future markAgreed() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_agreedKey, true); + } + + /// Whether the disclosure must come up now: always before a system prompt, + /// and until it has been agreed to even when no prompt is next. + static bool needsDisclosure({ + required bool agreed, + required bool aboutToRequest, + }) => + !agreed || aboutToRequest; +} diff --git a/lib/services/meshcore/channel_service.dart b/lib/services/meshcore/channel_service.dart index 56f04c0a..bc74d753 100644 --- a/lib/services/meshcore/channel_service.dart +++ b/lib/services/meshcore/channel_service.dart @@ -112,124 +112,100 @@ class ChannelService { return result; } - /// Create #wardriving channel on the device - /// - /// Finds first empty channel slot and creates the channel with SHA-256 key - /// - /// @param connection - Active MeshCore connection - /// @returns ChannelInfo for the created channel - /// @throws Exception if no empty slots or creation fails - static Future createWardrivingChannel( - MeshCoreConnection connection) async { - debugLog('[CHANNEL] Attempting to create channel: $wardrivingChannelName'); - - // Get all channels - final channels = await connection.getChannels(); - debugLog('[CHANNEL] Retrieved ${channels.length} channels'); - - // Find first empty channel slot - int? emptyIdx; - for (var i = 0; i < channels.length; i++) { - if (channels[i].name.isEmpty) { - emptyIdx = i; - debugLog('[CHANNEL] Found empty channel slot at index: $emptyIdx'); - break; - } - } + /// How long to wait before reading a failed channel slot a second time. + static const Duration slotRetryDelay = Duration(milliseconds: 200); - // Throw error if no free slots - if (emptyIdx == null) { - debugError('[CHANNEL] No empty channel slots available'); - throw Exception( - 'No empty channel slots available. Please free a channel slot on your companion first.', - ); - } + /// Highest slot index the command byte can carry. A radio that answered + /// every index without ever saying ERR_CODE_NOT_FOUND would otherwise keep + /// the scan going forever. + static const int _maxSlotIndex = 255; - // Derive the channel key from the channel name - final channelKey = CryptoService.deriveChannelKey(wardrivingChannelName); + /// Shown when the slot list could not be read in full. Kept clear of the + /// words "timeout" and "timed out" so the connection screen shows it as is. + static const String incompleteScanMessage = + 'Could not read the channel list from your radio. Please reconnect.'; - // Create the channel - debugLog( - '[CHANNEL] Creating channel $wardrivingChannelName at index $emptyIdx'); - await connection.setChannel(emptyIdx, wardrivingChannelName, channelKey); - debugLog( - '[CHANNEL] Channel $wardrivingChannelName created successfully at index $emptyIdx'); - - // Return channel info - return ChannelInfo( - channelIndex: emptyIdx, - name: wardrivingChannelName, - secret: channelKey, - ); - } + /// Shown when the radio answers the channel create with ERR. + static const String createFailedMessage = + 'Your radio could not create the #wardriving channel. Please reconnect.'; /// Ensure #wardriving channel exists (find or create) /// - /// Optimized to scan channels one-by-one and stop early when found + /// Reads the advertised number of slots. MeshCore and ZephCore report the + /// same capacity field but return different errors beyond that boundary. + /// Without a usable capacity, falls back to ERR_CODE_NOT_FOUND as the end. + /// An empty slot is a normal reply with an empty name. Any failure within + /// the advertised range is read once more; a second failure fails setup, + /// because creating a channel after an incomplete scan could duplicate a + /// #wardriving sitting past the failed slot. + /// + /// A slot holding the #wardriving key under another name counts as the + /// existing channel and is used as is (never renamed). /// /// @param connection - Active MeshCore connection /// @returns ChannelInfo for the wardriving channel static Future ensureWardrivingChannel( MeshCoreConnection connection) async { debugLog('[CHANNEL] Looking up channel: $wardrivingChannelName'); + final wardrivingKey = CryptoService.deriveChannelKey(wardrivingChannelName); - // Scan ALL channels to find #wardriving or first empty slot - // Full scan prevents duplicates from orphaned channels after unexpected disconnects + final maxChannels = connection.deviceInfo?.maxChannels; int? firstEmptySlot; var channelIdx = 0; - while (true) { + while (maxChannels == null || channelIdx < maxChannels) { + if (channelIdx > _maxSlotIndex) { + debugError('[CHANNEL] Radio answered past slot $_maxSlotIndex without ' + 'ending the list, not creating a channel'); + throw Exception(incompleteScanMessage); + } + + final ChannelInfo channel; try { - // Retry mechanism for first channel (sometimes gets spurious OK responses) - ChannelInfo? channel; - if (channelIdx == 0) { - // First channel might timeout due to spurious OK responses - // Retry once if it fails - try { - channel = await connection.getChannel(channelIdx); - } catch (e) { - debugLog( - '[CHANNEL] First getChannel failed (likely spurious OK), retrying: $e'); - await Future.delayed(const Duration(milliseconds: 100)); - channel = await connection.getChannel(channelIdx); - } - } else { - channel = await connection.getChannel(channelIdx); + final read = await _readSlot(connection, channelIdx, + allowEndOfList: maxChannels == null); + if (read == null) { + // ERR_CODE_NOT_FOUND: the radio's end of list. + debugLog('[CHANNEL] End of channel list at index $channelIdx'); + break; } + channel = read; + } on _SlotReadFailed { + debugError('[CHANNEL] Slot $channelIdx failed twice, channel scan ' + 'incomplete, not creating a channel'); + throw Exception(incompleteScanMessage); + } - // Found existing #wardriving channel - return immediately! - if (channel.name == wardrivingChannelName) { - debugLog( - '[CHANNEL] Found existing channel at index ${channel.channelIndex} (scanned ${channelIdx + 1} channels)'); - return channel; - } + if (channel.name == wardrivingChannelName) { + debugLog( + '[CHANNEL] Found existing channel at index ${channel.channelIndex} (scanned ${channelIdx + 1} channels)'); + return channel; + } - // Track first empty slot for creating channel if needed - if (channel.name.isEmpty && firstEmptySlot == null) { - firstEmptySlot = channelIdx; - debugLog('[CHANNEL] Found empty slot at index $firstEmptySlot'); - // Continue scanning ALL remaining channels to find orphaned #wardriving - // This prevents duplicates after unexpected disconnects where channel wasn't deleted - } + if (channel.name.isNotEmpty && _sameKey(channel.secret, wardrivingKey)) { + debugLog('[CHANNEL] Slot $channelIdx "${channel.name}" holds the ' + '$wardrivingChannelName key, using it as the wardriving channel'); + return channel; + } - channelIdx++; - } catch (e) { - // Error getting channel (likely reached end) - debugLog('[CHANNEL] Scan stopped at channel $channelIdx (error: $e)'); - break; + if (channel.name.isEmpty && firstEmptySlot == null) { + // The reply's own index, never the loop counter: it is the slot the + // radio actually described. + firstEmptySlot = channel.channelIndex; + debugLog('[CHANNEL] Found empty slot at index $firstEmptySlot'); + // Keep scanning: an orphaned #wardriving left by an unexpected + // disconnect may sit further down, and must not be duplicated. } + + channelIdx++; + } + + if (maxChannels != null) { + debugLog('[CHANNEL] Read all $maxChannels advertised channel slots'); } - // #wardriving not found - create it at first empty slot if (firstEmptySlot == null) { - if (channelIdx == 0) { - // Couldn't read any channels — BLE dropped, not a channel issue - debugError('[CHANNEL] BLE connection lost during channel scan'); - throw Exception( - 'BLE connection lost during channel setup. Please try connecting again.', - ); - } debugError( - '[CHANNEL] No empty channel slots found in first $channelIdx channels'); + '[CHANNEL] No empty channel slots found in $channelIdx channels'); throw Exception( 'No empty channel slots available. Please free a channel slot on your companion first.', ); @@ -237,19 +213,63 @@ class ChannelService { debugLog( '[CHANNEL] #wardriving not found in $channelIdx channels, creating at index $firstEmptySlot'); - final channelKey = CryptoService.deriveChannelKey(wardrivingChannelName); - await connection.setChannel( - firstEmptySlot, wardrivingChannelName, channelKey); + try { + await connection.setChannel( + firstEmptySlot, wardrivingChannelName, wardrivingKey); + } on CommandErrorException catch (e) { + debugError('[CHANNEL] Radio refused to create $wardrivingChannelName ' + 'at index $firstEmptySlot: $e'); + throw Exception(createFailedMessage); + } debugLog( '[CHANNEL] Channel $wardrivingChannelName created successfully at index $firstEmptySlot'); return ChannelInfo( channelIndex: firstEmptySlot, name: wardrivingChannelName, - secret: channelKey, + secret: wardrivingKey, ); } + /// Reads one slot, retrying once after [slotRetryDelay]. + /// + /// Without advertised capacity, ERR_CODE_NOT_FOUND ends the list. Within + /// advertised capacity it is a failed read, just like any other error. + /// Throws [_SlotReadFailed] when both attempts fail. + static Future _readSlot( + MeshCoreConnection connection, int channelIdx, + {required bool allowEndOfList}) async { + for (var attempt = 1; attempt <= 2; attempt++) { + try { + final channel = await connection.getChannel(channelIdx); + if (channel.channelIndex == channelIdx) return channel; + debugWarn('[CHANNEL] Slot $channelIdx read answered for slot ' + '${channel.channelIndex} (attempt $attempt)'); + } on CommandErrorException catch (e) { + if (allowEndOfList && e.isNotFound) return null; + debugWarn( + '[CHANNEL] Slot $channelIdx read failed (attempt $attempt): $e'); + } catch (e) { + debugWarn( + '[CHANNEL] Slot $channelIdx read failed (attempt $attempt): $e'); + } + if (attempt == 1) { + debugLog('[CHANNEL] Retrying slot $channelIdx in ' + '${slotRetryDelay.inMilliseconds} ms'); + await Future.delayed(slotRetryDelay); + } + } + throw const _SlotReadFailed(); + } + + static bool _sameKey(Uint8List a, Uint8List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + /// Delete #wardriving channel on disconnect /// /// @param connection - Active MeshCore connection @@ -269,6 +289,11 @@ class ChannelService { } } +/// A channel slot that could not be read on either attempt. +class _SlotReadFailed implements Exception { + const _SlotReadFailed(); +} + /// Internal class to store pre-computed channel data class _ChannelData { final Uint8List key; diff --git a/lib/services/meshcore/connection.dart b/lib/services/meshcore/connection.dart index f170db72..f2662118 100644 --- a/lib/services/meshcore/connection.dart +++ b/lib/services/meshcore/connection.dart @@ -2,6 +2,9 @@ import 'dart:async'; import 'dart:math'; import 'dart:typed_data'; +import 'package:clock/clock.dart'; +import 'package:flutter/foundation.dart' show visibleForTesting; + import '../../models/connection_state.dart'; import '../../models/device_model.dart'; import '../../utils/debug_logger_io.dart'; @@ -12,6 +15,7 @@ import 'channel_service.dart'; import 'crypto_service.dart'; import 'packet_parser.dart'; import 'protocol_constants.dart'; +import 'scope_lease.dart'; /// How long a repeater-admin command waits for an in-flight noise floor or /// battery poll to settle before it writes anyway. @@ -21,12 +25,27 @@ import 'protocol_constants.dart'; /// never trips it. const Duration kPollDrainTimeout = Duration(seconds: 6); +/// How long a reply stays owed in the reply ledger after its write returns. +const Duration kReplyOwedExpiry = Duration(seconds: 10); + +/// How long a contact stream may go without a frame before scope discovery +/// is suspended for the rest of the connection. +const Duration kContactsStreamSilence = Duration(seconds: 60); + +/// How long [MeshCoreConnection.sign] waits for scope discovery to let go of +/// the radio before it fails with `busy`. +const Duration kSignScopeWait = Duration(seconds: 15); + /// Response from device query command class DeviceQueryResponse { /// Companion FIRMWARE_VER_CODE (byte 1 of RESP_CODE_DEVICE_INFO). /// Describes companion API capabilities, independent of the release string. final int protocolVersion; final String manufacturer; + + /// Number of channel slots advertised in device-info byte 3. + /// Null when the parsed format has no capacity or reports zero. + final int? maxChannels; final String? firmwareBuildDate; // Added in protocol v8 final String? firmwareVersionString; // e.g. "v1.14.0-9f1a3ea" (v7+, 20-byte C-string) @@ -36,6 +55,7 @@ class DeviceQueryResponse { const DeviceQueryResponse({ required this.protocolVersion, required this.manufacturer, + this.maxChannels, this.firmwareBuildDate, this.firmwareVersionString, this.pathHashMode, @@ -130,6 +150,8 @@ class SelfInfo { /// * `bad_signature_length` — the radio returned something other than 64 bytes /// * `err` — the radio answered ERR mid-sign /// * `aborted` — the connection closed while a sign was in flight +/// * `busy` (transient): scope discovery held the radio for the whole wait; +/// the link flow retries it with its usual backoff class SignException implements Exception { final String code; final String message; @@ -154,6 +176,21 @@ class RadioErrorException implements Exception { String toString() => 'RadioErrorException($command, code $errorCode)'; } +/// Thrown into a pending query (stats, channel info, device query, export +/// contact, get time) when the radio answers ERR. Carries the firmware's +/// error code so a caller can tell the end of a list (ERR_CODE_NOT_FOUND) +/// from a fault, and reads in logs exactly as the plain exception it replaced. +class CommandErrorException implements Exception { + final int errorCode; // ErrorCodes.* + + const CommandErrorException(this.errorCode); + + bool get isNotFound => errorCode == ErrorCodes.notFound; + + @override + String toString() => 'Exception: Command error (code $errorCode)'; +} + /// Thrown into every pending repeater-admin completer when the connection /// closes mid-command (the `_abortPendingSign` pattern). class RadioAbortedException implements Exception { @@ -169,6 +206,78 @@ class _AdminCommandToken { const _AdminCommandToken(this.name); } +/// A send whose own bare OK or ERR the connection claims. +enum _OwnReplyKind { tx, discovery, channel } + +/// One pending claim on the next OK or ERR, queued as its frame goes out. +class _OwnReplyClaim { + final _OwnReplyKind kind; + + /// Completes when the reply arrives, the claim expires, or it is released. + final Completer reply = Completer(); + Timer? expiry; + + /// True once the radio answered with OK or ERR (not expired or released). + bool answered = false; + + /// The ERR code the radio answered with, null on OK or no answer. + int? errorCode; + + _OwnReplyClaim(this.kind); + + String get label => switch (kind) { + _OwnReplyKind.tx => 'TX send', + _OwnReplyKind.discovery => 'discovery request', + _OwnReplyKind.channel => 'channel write', + }; + + void settle() { + expiry?.cancel(); + expiry = null; + if (!reply.isCompleted) reply.complete(); + } +} + +/// How many reply frames one outbound command earns from the companion +/// firmware (`examples/companion_radio/MyMesh.cpp`, `handleCmdFrame`). +class CommandReplyShape { + /// Reply frames owed: normally one, zero for the commands that reboot or + /// wipe the radio. + final int replies; + + /// The reply is push 0x8B (self telemetry), not a code below 0x80. + final bool selfTelemetry; + + /// CMD_GET_CONTACTS: one initial reply, then a stream tracked on its own. + final bool opensContactStream; + + const CommandReplyShape( + {this.replies = 1, + this.selfTelemetry = false, + this.opensContactStream = false}); +} + +/// Where a CMD_GET_CONTACTS stream stands: written but not started, +/// streaming, or neither. +enum ContactsStreamState { none, requested, open } + +/// One reply the radio still owes, oldest first in the ledger. +class _OwedReply { + final int command; + final bool selfTelemetry; + final bool opensContactStream; + + /// Written by a scope lease. Only these keep Manage waiting once the + /// lease has ended: ordinary traffic owes replies too, and never did. + final bool scopeOwned; + Timer? expiry; + + _OwedReply(this.command, + {required this.selfTelemetry, + required this.opensContactStream, + this.scopeOwned = false}); +} + /// The parsed RESP_CODE_SENT frame: [flood:1][tag:4][est_timeout_ms:u32]. class SentInfo { final bool flood; @@ -217,6 +326,11 @@ class ContactRecord { final int outPathLen; final Uint8List outPath; // always 64 bytes final String name; + + /// The 32 name bytes exactly as the radio sent them (null for a record + /// built here). Written back verbatim, so a restore is byte-exact even for + /// a name that is not valid UTF-8 or carries bytes past its NUL. + final Uint8List? rawName; final int lastAdvert; final int latMicro; final int lonMicro; @@ -233,6 +347,7 @@ class ContactRecord { required int latMicro, required int lonMicro, required int lastMod, + Uint8List? rawName, }) { if (publicKey.length != 32) { throw ArgumentError.value( @@ -242,6 +357,10 @@ class ContactRecord { throw ArgumentError.value( outPath.length, 'outPath.length', 'must be exactly 64 bytes'); } + if (rawName != null && rawName.length != 32) { + throw ArgumentError.value( + rawName.length, 'rawName.length', 'must be exactly 32 bytes'); + } return ContactRecord._( publicKey: publicKey, type: type, @@ -253,6 +372,7 @@ class ContactRecord { latMicro: latMicro, lonMicro: lonMicro, lastMod: lastMod, + rawName: rawName, ); } @@ -267,6 +387,7 @@ class ContactRecord { required this.latMicro, required this.lonMicro, required this.lastMod, + this.rawName, }); /// A flood-route repeater contact with the MeshMapper name and position. @@ -299,17 +420,24 @@ class ContactRecord { 'Contact frame carries ${reader.remainingBytesCount} bytes, ' 'expected $payloadLength'); } + final publicKey = reader.readBytes(32); + final type = reader.readByte(); + final flags = reader.readByte(); + final outPathLen = reader.readByte(); + final outPath = reader.readBytes(64); + final rawName = Uint8List.fromList(reader.readBytes(32)); return ContactRecord( - publicKey: reader.readBytes(32), - type: reader.readByte(), - flags: reader.readByte(), - outPathLen: reader.readByte(), - outPath: reader.readBytes(64), - name: reader.readCString(32), + publicKey: publicKey, + type: type, + flags: flags, + outPathLen: outPathLen, + outPath: outPath, + name: BufferReader(rawName).readCString(32), lastAdvert: reader.readUInt32LE(), latMicro: reader.readInt32LE(), lonMicro: reader.readInt32LE(), lastMod: reader.readUInt32LE(), + rawName: rawName, ); } @@ -354,6 +482,23 @@ class ContactRecord { latMicro: latMicro, lonMicro: lonMicro, lastMod: lastMod, + rawName: rawName, + ); + + /// The same record, byte for byte, with only `out_path_len` replaced. The + /// scope request borrows a zero-hop route with `withOutPathLen(0)`. + ContactRecord withOutPathLen(int outPathLen) => ContactRecord( + publicKey: publicKey, + type: type, + flags: flags, + outPathLen: outPathLen, + outPath: outPath, + name: name, + lastAdvert: lastAdvert, + latMicro: latMicro, + lonMicro: lonMicro, + lastMod: lastMod, + rawName: rawName, ); Uint8List toFrame(int commandCode) { @@ -364,7 +509,12 @@ class ContactRecord { w.writeByte(flags); w.writeByte(outPathLen); w.writeBytes(outPath); - w.writeCString(name, 32); + final raw = rawName; + if (raw != null) { + w.writeBytes(raw); + } else { + w.writeCString(name, 32); + } w.writeUInt32LE(lastAdvert); w.writeUInt32LE(latMicro.toUnsigned(32)); w.writeUInt32LE(lonMicro.toUnsigned(32)); @@ -411,13 +561,29 @@ class MeshCoreConnection { // Completers for command responses Completer? _deviceQueryCompleter; Completer? _selfInfoCompleter; - Completer? _sentCompleter; Completer? _setTimeCompleter; Completer? _channelInfoCompleter; + + /// The slot [_channelInfoCompleter] asked for. A CHANNEL_INFO for any other + /// slot is a late reply to an earlier read and is not this request's answer. + int? _channelInfoRequestedIdx; Completer? _statsCompleter; Completer? _exportContactCompleter; Completer? _getTimeCompleter; + // TX pings and discovery requests are answered with a bare OK or ERR (never + // RESP_CODE_SENT), in command order. Each send queues a claim as its frame + // reaches the wire, and the oldest claim takes the next OK or ERR: after a + // pending sign, before the repeater-admin and time-sync owners. Without the + // claim that reply went to whichever OK waiter happened to exist. + final List<_OwnReplyClaim> _ownReplyClaims = []; + + /// How long a TX or discovery claim waits for its OK or ERR before it + /// expires, so an unanswered send cannot swallow a later command's reply. + /// Tests shorten it. + @visibleForTesting + Duration ownReplyTimeout = const Duration(seconds: 3); + // Repeater-admin commands (contacts, login, binary request, reset path). // One at a time: the companion keeps a single pending request and a login // clears it (clearPendingReqs), so overlapping two would lose a reply. @@ -433,6 +599,9 @@ class MeshCoreConnection { Timer? _adminLateResponseTimer; Completer>? _contactsCompleter; List _contactsBuffer = []; + // Re-arms the running getContacts call's silence timer. Called on every + // CONTACTS_START and CONTACT frame, so a long list keeps its read alive. + void Function()? _contactsProgress; /// The radio's contact list as this connection last saw it, keyed by the /// full public key hex, in the radio's order. Lives exactly as long as @@ -476,6 +645,23 @@ class MeshCoreConnection { bool _isFetchingNoiseFloor = false; int _noiseFloorFailCount = 0; + /// True while noise floor polling runs at [noiseFloorBackoffInterval] + /// after [_noiseFloorFailLimit] failures in a row. + bool _noiseFloorBackedOff = false; + + /// Consecutive failures before polling slows to the backoff interval. + static const int _noiseFloorFailLimit = 3; + + /// Normal noise floor poll interval. Tests shorten it. + @visibleForTesting + Duration noiseFloorPollInterval = const Duration(seconds: 5); + + /// Slower poll interval used after repeated failures, so a radio that is + /// briefly busy (an Android GATT busy run, a second app on the link) costs a + /// few samples rather than the rest of the session. Tests shorten it. + @visibleForTesting + Duration noiseFloorBackoffInterval = const Duration(seconds: 30); + // Battery tracking int? _lastBatteryMilliVolts; // millivolts or null if not supported Timer? _batteryTimer; @@ -490,6 +676,69 @@ class MeshCoreConnection { Completer? _statsRequestSettled; Completer? _batteryRequestSettled; + // ---- Scope discovery: reply ledger, contact stream, lease and listen ---- + // + // The ledger holds one entry per reply frame the radio owes for commands + // already written (see [_replyShape]). It is bookkeeping for the scope + // lease only: it changes no dispatch outside a lease. + final List<_OwedReply> _repliesOwed = []; + + /// How long an owed reply stays in the ledger after its write returns. + /// Tests shorten it. + @visibleForTesting + Duration replyOwedExpiry = kReplyOwedExpiry; + + ContactsStreamState _contactsStream = ContactsStreamState.none; + Timer? _contactsStreamWatchdog; + + // A contact stream that went silent: scope discovery stays off until the + // connection is rebuilt. + bool _scopeSuspended = false; + + // An owed reply expired unanswered: the app can no longer tell which later + // reply answers which command, so scope discovery stays off until the + // connection is rebuilt. + bool _replySyncLost = false; + + // A reboot or reset was written: the radio is going away, so no lease is + // admitted on this connection object again (a reconnect builds a new one). + bool _radioRestarting = false; + + // A send to a repeater that is not a saved contact came back + // ERR_CODE_TABLE_FULL: the connected companion firmware (a bug fixed in + // v1.17.0's 8 reserved transient slots) needs a contact-table slot for + // CMD_SEND_ANON_REQ and has none free. Sticky for the life of the + // connection; a reconnect builds a new instance and clears it. + bool _scopeCannotAskNonContacts = false; + + // The live lease, its admin-slot token and the gate every other write + // waits at while it is held. + ScopeLease? _lease; + _AdminCommandToken? _leaseToken; + Completer? _leaseGate; + int _leaseGateWaiters = 0; + void Function(Uint8List frame)? _leaseReplyWaiter; + + // The admin slot's owner during the answer wait that follows a lease. + _AdminCommandToken? _scopeListenToken; + Completer? _scopeAnswerCompleter; + DateTime? _binaryResponseReceivedAt; + + // Bumped by every teardown, so an admission in progress can tell. + int _scopeEpoch = 0; + + // Completed when scope work lets go of the radio (lease and listen both + // over); a sign waiting at its entry listens for it. + Completer? _scopeIdle; + int _signWaiters = 0; + + /// How long [sign] waits for scope discovery before failing `busy`. Tests + /// shorten it. + @visibleForTesting + Duration signScopeWait = kSignScopeWait; + + late final _ScopeLeaseHostAdapter _scopeHost = _ScopeLeaseHostAdapter(this); + /// How long an admin command keeps the slot after timing out with its bare /// OK still owed. Tests shorten it; nothing in the app passes it. final Duration _adminLateResponseBackstop; @@ -709,6 +958,13 @@ class MeshCoreConnection { } catch (e) { debugError('[CONN] Connection failed: $e'); _updateStep(ConnectionStep.error); + // A disposed connection was abandoned or superseded: whoever disposed + // it owns the transport now, which may already carry a newer link. + if (_disposed) { + debugLog('[CONN] Connection was superseded, leaving the transport ' + 'to its new owner'); + rethrow; + } // Clean up BLE connection on failure try { await _transport.disconnect(); @@ -727,10 +983,19 @@ class MeshCoreConnection { // Channel deletion is a gated write; a live sign would park it behind the // sign timeout while BLE is still up. Abort the sign first. _abortPendingSign(); + _abortScopeWork('channel deletion'); _abortPendingAdmin(); final channel = _wardrivingChannel; if (channel != null) { - await ChannelService.deleteWardrivingChannel(this, channel.channelIndex); + if (channel.name == ChannelService.wardrivingChannelName) { + await ChannelService.deleteWardrivingChannel( + this, channel.channelIndex); + } else { + // A channel the user saved under their own name with the #wardriving + // key was reused, not created, so it stays on the radio. + debugLog('[CHANNEL] Keeping reused channel "${channel.name}" at ' + 'index ${channel.channelIndex} (not created by MeshMapper)'); + } _wardrivingChannel = null; } } @@ -739,7 +1004,10 @@ class MeshCoreConnection { try { debugLog('[CONN] Disconnecting'); _abortPendingSign(); + _abortScopeWork('disconnect'); _abortPendingAdmin(); + _releaseOwnReplies(); + _resetReplyLedger(); // Stop noise floor polling _stopNoiseFloorPolling(); @@ -772,10 +1040,23 @@ class MeshCoreConnection { // A RESP_SIGNATURE payload is 64 bytes of Ed25519 signature over the // portal's login nonce, and debug logs are uploadable to the bug-report // endpoint — so this one frame is logged by length only, never as hex. + // A CONTACT reply (a contact list stream, a scope lookup) and a new + // advert push open with a full 32-byte public key, and keys are logged by + // their 8-hex prefix only: the key past its first 4 bytes is redacted. // Every other frame keeps the full hexdump. - final frameDump = frame[0] == ResponseCodes.signature - ? 'SIGNATURE payload redacted' - : _hexDump(frame); + final String frameDump; + if (frame[0] == ResponseCodes.signature) { + frameDump = 'SIGNATURE payload redacted'; + } else if ((frame[0] == ResponseCodes.contact || + frame[0] == PushCodes.newAdvert) && + frame.length > 5) { + final keyEnd = frame.length < 33 ? frame.length : 33; + frameDump = '${_hexDump(Uint8List.sublistView(frame, 0, 5))} ' + '[key redacted]' + '${keyEnd < frame.length ? ' ${_hexDump(Uint8List.sublistView(frame, keyEnd))}' : ''}'; + } else { + frameDump = _hexDump(frame); + } try { final reader = BufferReader(frame); @@ -790,6 +1071,18 @@ class MeshCoreConnection { '[CONN] Frame 0x${responseCode.toRadixString(16).padLeft(2, '0')} ' '($responseCode), ${frame.length} bytes: $frameDump'); + // The reply ledger sees every frame first. While a lease command + // awaits its reply, the next reply frame is the lease's, exactly once, + // before the sign, own-reply, admin and legacy owners are consulted. + final isReply = _accountReply(responseCode); + final leaseWaiter = _leaseReplyWaiter; + if (isReply && responseCode < 0x80 && leaseWaiter != null) { + _leaseReplyWaiter = null; + debugLog('[SCOPES] Reply code $responseCode taken by the scope lease'); + leaseWaiter(frame); + return; + } + switch (responseCode) { case ResponseCodes.ok: { @@ -805,6 +1098,7 @@ class MeshCoreConnection { if (!signOk.isCompleted) signOk.complete(); break; } + if (_claimOwnReply(null)) break; final adminOk = _adminOkCompleter; if (adminOk != null) { final owner = _adminOkOwner; @@ -853,6 +1147,7 @@ class MeshCoreConnection { )) { break; } + if (_claimOwnReply(errorCode)) break; // Time sync: error code 6 (ERR_CODE_ILLEGAL_ARG) means "no sync needed" — treat as success if (_setTimeCompleter != null) { if (errorCode == 6) { @@ -872,7 +1167,14 @@ class MeshCoreConnection { // lane only when nothing else is waiting: the noise floor poll runs // every 5s and a login can wait up to 60s, and a poller's ERR must // not kill that login with the wrong sentence. - if (_statsCompleter == null && + // + // Scope work holds no untagged command of its own while it owns + // the slot (a lease command's ERR is taken above, and the answer + // wait is ended only by its tagged push, a cancel, its timer or a + // disconnect), so an ERR here belongs to someone else and must not + // clear the tagged answer the scope listen is waiting for. + if (!_scopeOwnsSlot && + _statsCompleter == null && _channelInfoCompleter == null && _deviceQueryCompleter == null && _exportContactCompleter == null && @@ -881,7 +1183,7 @@ class MeshCoreConnection { _adminCommandInFlight?.name ?? 'admin', errorCode)); } // Complete any pending completers with error - final errException = Exception('Command error (code $errorCode)'); + final errException = CommandErrorException(errorCode); _statsCompleter?.completeError(errException); _statsCompleter = null; _channelInfoCompleter?.completeError(errException); @@ -996,12 +1298,14 @@ class MeshCoreConnection { break; } _contactsBuffer = []; + _contactsProgress?.call(); final count = reader.remainingBytesCount >= 4 ? reader.readUInt32LE() : -1; debugLog('[CONN] Contact list starting ($count contacts)'); break; case ResponseCodes.contact: if (_contactsCompleter == null) break; + _contactsProgress?.call(); try { _contactsBuffer.add(ContactRecord.parse(reader)); } on FormatException catch (e) { @@ -1034,6 +1338,22 @@ class MeshCoreConnection { completer.complete(List.unmodifiable(_contactCache.values)); break; } + // Known frames the app deliberately ignores: it never reads its + // inbox or keeps a contact UI, so these pushes and message-sync + // replies carry nothing it uses. The frame line above already + // records them, so they stay quiet here. + case PushCodes.advert: + case PushCodes.newAdvert: + case PushCodes.msgWaiting: + case PushCodes.sendConfirmed: + case PushCodes.contactDeleted: + case PushCodes.contactsFull: + case ResponseCodes.noMoreMessages: + case ResponseCodes.contactMsgRecv: + case ResponseCodes.contactMsgRecvV3: + case ResponseCodes.channelMsgRecvV3: + case ResponseCodes.advertPath: + break; default: // Log unhandled response codes (like JS implementation) debugLog( @@ -1204,6 +1524,14 @@ class MeshCoreConnection { /// Tear down an in-flight repeater-admin command on disconnect/dispose. void _abortPendingAdmin() { + // The slot may belong to scope discovery (its lease or answer wait), + // which the teardown paths end first through [_abortScopeWork]. An admin + // abort from anywhere else (the Manage sheet closing) leaves it alone. + if (_scopeOwnsSlot) { + debugLog('[CONN] Admin abort skipped: the slot belongs to scope ' + 'discovery'); + return; + } final wasPending = _failPendingAdmin(const RadioAbortedException()); _adminCommandInFlight = null; if (wasPending) debugLog('[CONN] Aborted in-flight repeater admin command'); @@ -1216,6 +1544,245 @@ class MeshCoreConnection { /// an untagged reply is being drained after its caller timed out. bool get hasPendingAdminCommand => _adminCommandInFlight != null; + // ============================================ + // Scope discovery lease + // ============================================ + + /// True while a scope lease holds the radio. + bool get isScopeLeaseActive => _lease != null; + + /// True while the radio still owes a reply to a command a scope lease + /// wrote. Replies owed to ordinary traffic (the pollers, a flood scope + /// write) do not count: the admin lane has always coped with those. + bool get hasScopeReplyDebt => _repliesOwed.any((e) => e.scopeOwned); + + /// Scope discovery owns the radio: a lease is held, or a reply is still + /// owed for a command one wrote. What Manage waits for. + bool get isScopeRadioBusy => _lease != null || hasScopeReplyDebt; + + /// Fired synchronously whenever [isScopeRadioBusy] flips, and only then: + /// a lease granted or ended, or the last scope-owned reply retired, + /// expired or cleared. Wired to a plain provider notify so Manage + /// re-reads the flag the moment the radio frees up. + void Function()? onScopeRadioBusyChanged; + bool _scopeRadioBusyReported = false; + + void _reportScopeRadioBusy() { + final busy = isScopeRadioBusy; + if (busy == _scopeRadioBusyReported) return; + _scopeRadioBusyReported = busy; + debugLog('[SCOPES] Radio ${busy ? 'held' : 'free'} for Manage'); + onScopeRadioBusyChanged?.call(); + } + + /// True during the answer wait that follows a lease (the admin slot is + /// held by the scope listen). + bool get isScopeListenActive => + _scopeListenToken != null && + identical(_adminCommandInFlight, _scopeListenToken); + + /// True once a contact stream went silent, an owed reply expired + /// unanswered, or a reboot or reset was written; no lease is admitted for + /// the rest of this connection. + bool get isScopeDiscoverySuspended => + _scopeSuspended || _replySyncLost || _radioRestarting; + + /// True once a send to a repeater that is not a saved contact came back + /// ERR_CODE_TABLE_FULL: this connection will not ask a non-contact again + /// until reconnected. A saved contact is unaffected and is still asked + /// normally. + bool get scopeCannotAskNonContacts => _scopeCannotAskNonContacts; + + /// Fired once, synchronously, the moment [scopeCannotAskNonContacts] flips + /// from false to true. Wired to a plain provider notify (the Settings + /// tile's note), never `mapRevision` (Rule 9). + void Function()? onScopeCannotAskNonContactsChanged; + + bool get _scopeOwnsSlot { + final owner = _adminCommandInFlight; + return owner != null && + (identical(owner, _leaseToken) || identical(owner, _scopeListenToken)); + } + + bool get _scopeBusyForSign => _lease != null || isScopeListenActive; + + /// Asks for a short exclusive hold on the radio for one scope request. + /// + /// Drains the pollers, then waits up to [admissionWait] (both inside that + /// one deadline) until the admin slot is free, no sign runs or waits, no + /// contact stream is open and no reply is owed. The grant is decided in one + /// synchronous step, which also re-reads [cancel]. Resolves null (with the + /// reason logged) when it is not admitted in time, [cancel] fires first, + /// the connection goes away, or scope discovery is suspended. + Future acquireScopeLease( + {required Duration admissionWait, + required ScopeCancelToken cancel}) async { + final epoch = _scopeEpoch; + final refused = _scopeHardRefusal(cancel, epoch); + if (refused != null) { + debugLog('[SCOPES] Lease not admitted: $refused'); + return null; + } + final deadline = Completer(); + final deadlineTimer = Timer(admissionWait, deadline.complete); + try { + // The drain alone may run to kPollDrainTimeout; the admission deadline + // bounds it. + await Future.any([ + _drainPollsForAdminCommand('scopeLease'), + deadline.future, + cancel.whenCancelled, + ]); + while (true) { + final hard = _scopeHardRefusal(cancel, epoch); + if (hard != null) { + debugLog('[SCOPES] Lease not admitted: $hard'); + return null; + } + final busy = _scopeBusyReason(); + if (busy == null) return _grantScopeLease(cancel); + if (deadline.isCompleted) { + debugLog('[SCOPES] Lease not admitted within ' + '${admissionWait.inMilliseconds}ms: $busy'); + return null; + } + await Future.any([ + Future.delayed(const Duration(milliseconds: 20)), + deadline.future, + cancel.whenCancelled, + ]); + } + } finally { + deadlineTimer.cancel(); + } + } + + String? _scopeHardRefusal(ScopeCancelToken cancel, int epoch) { + if (_disposed) return 'connection disposed'; + if (epoch != _scopeEpoch) return 'connection closed'; + if (cancel.isCancelled) return 'cancelled'; + if (_scopeSuspended) return 'suspended after a silent contact stream'; + if (_replySyncLost) return 'suspended after an owed reply expired'; + if (_radioRestarting) return 'a reboot or reset was sent to the radio'; + return null; + } + + String? _scopeBusyReason() { + final owner = _adminCommandInFlight; + if (owner != null) return 'admin slot held by ${owner.name}'; + if (_signInProgress || _signWaiters > 0) return 'sign in progress'; + if (_contactsStream != ContactsStreamState.none) { + return 'contact stream ${_contactsStream.name}'; + } + if (_repliesOwed.isNotEmpty) { + return '${_repliesOwed.length} repl${_repliesOwed.length == 1 ? 'y' : 'ies'} owed'; + } + if (_leaseGateWaiters > 0) return 'writes still queued'; + return null; + } + + ScopeLease _grantScopeLease(ScopeCancelToken cancel) { + // Never const: each lease needs its own token, compared by identity. + // ignore: prefer_const_constructors + final token = _AdminCommandToken('scopeLease'); + _adminCommandInFlight = token; + _leaseToken = token; + _leaseGate = Completer(); + final lease = ScopeLease(host: _scopeHost, cancel: cancel); + _lease = lease; + debugLog('[SCOPES] Lease granted'); + _reportScopeRadioBusy(); + return lease; + } + + /// Ends [lease] (see [ScopeLeaseHost.endLease]). + void _endScopeLease(ScopeLease lease, {required bool listen}) { + if (!identical(_lease, lease)) return; + _lease = null; + _leaseReplyWaiter = null; + final token = _leaseToken; + _leaseToken = null; + if (listen && identical(_adminCommandInFlight, token)) { + // ignore: prefer_const_constructors + final listenToken = _AdminCommandToken('scopeListen'); + _scopeListenToken = listenToken; + _adminCommandInFlight = listenToken; + } else { + if (token != null) _endAdminCommand(token); + _disarmScopeAnswer(); + } + final gate = _leaseGate; + _leaseGate = null; + if (gate != null && !gate.isCompleted) gate.complete(); + debugLog('[SCOPES] Lease released' + '${listen ? ', waiting for the answer' : ''}' + '${_repliesOwed.isEmpty ? '' : ' (${_repliesOwed.length} reply owed)'}'); + if (!isScopeListenActive) _notifyScopeIdle(); + _reportScopeRadioBusy(); + } + + /// Ends the answer wait and frees the admin slot. + void _endScopeListen() { + _disarmScopeAnswer(); + final token = _scopeListenToken; + _scopeListenToken = null; + if (token != null) _endAdminCommand(token); + if (_lease == null) _notifyScopeIdle(); + } + + Future _armScopeAnswer() { + final completer = Completer(); + _scopeAnswerCompleter = completer; + _binaryResponseCompleter = completer; + _binaryResponseTag = null; + return completer.future.then((body) => + (body: body, receivedAt: _binaryResponseReceivedAt ?? clock.now())); + } + + void _disarmScopeAnswer() { + final completer = _scopeAnswerCompleter; + if (completer == null) return; + _scopeAnswerCompleter = null; + if (identical(_binaryResponseCompleter, completer)) { + _binaryResponseCompleter = null; + _binaryResponseTag = null; + } + } + + /// Teardown: ends any lease with [ScopeAborted] and any answer wait, and + /// bumps the epoch so an admission in progress grants nothing. + void _abortScopeWork(String why) { + _scopeEpoch++; + final lease = _lease; + final listening = isScopeListenActive; + if (lease == null && !listening) return; + debugLog('[SCOPES] Scope work aborted ($why)'); + lease?.abortForDisconnect(); + final answer = _scopeAnswerCompleter; + if (answer != null && !answer.isCompleted) { + answer.completeError(const RadioAbortedException()); + } + _endScopeListen(); + } + + Future _waitForScopeIdle(Duration limit) { + final idle = (_scopeIdle ??= Completer()).future; + final done = Completer(); + final timer = Timer(limit, () { + if (!done.isCompleted) done.complete(); + }); + idle.then((_) { + if (!done.isCompleted) done.complete(); + }); + return done.future.whenComplete(timer.cancel); + } + + void _notifyScopeIdle() { + final idle = _scopeIdle; + _scopeIdle = null; + if (idle != null && !idle.isCompleted) idle.complete(); + } + /// Tear down an in-flight sign on disconnect/dispose. /// /// Releasing the gate here is what keeps disconnect fast: the wardriving @@ -1241,7 +1808,8 @@ class MeshCoreConnection { void _onDeviceInfoResponse(BufferReader reader) { // Protocol format changed in v7/v8: // v1-v6: protoVer (1) + manufacturer C-string (64) + publicKey (32) - // v7+: firmwareVer (1) + reserved (6) + buildDate C-string (12) + manufacturerModel string (rest) + // v7+: firmwareVer (1), maxContacts/2 (1), maxChannels (1), BLE PIN (4), + // buildDate (12), model (40), then optional version and capability fields. // Note: Some v7 firmware (e.g., RAK4631) uses the new format final firmwareVer = reader.readByte(); @@ -1249,7 +1817,11 @@ class MeshCoreConnection { if (firmwareVer >= 7) { // Protocol v7+ format - reader.readBytes(6); // skip reserved bytes + reader.readByte(); // max contacts / 2 + final channelCapacity = reader.readByte(); + final maxChannels = channelCapacity > 0 ? channelCapacity : null; + reader.readBytes(4); // BLE PIN + debugLog('[CONN] Channel capacity: ${maxChannels ?? "unknown"}'); final buildDate = reader.readCString(12); // e.g. "04-Jan-2026" // Read manufacturer model as CString(40) — fixed-length null-terminated @@ -1284,6 +1856,7 @@ class MeshCoreConnection { final response = DeviceQueryResponse( protocolVersion: firmwareVer, manufacturer: manufacturerModel, + maxChannels: maxChannels, firmwareBuildDate: buildDate, firmwareVersionString: firmwareVersionString, pathHashMode: pathHashMode, @@ -1372,8 +1945,9 @@ class MeshCoreConnection { } } - /// RESP_CODE_SENT. The legacy completer (channel messages) is void; the - /// repeater-admin completer wants the parsed [flood:1][tag:4][est:u32]. + /// RESP_CODE_SENT. The repeater-admin completer wants the parsed + /// [flood:1][tag:4][est:u32]. Channel messages are answered with OK or ERR + /// instead (see [_claimOwnReply]). void _onSentResponse(BufferReader reader) { SentInfo? info; if (reader.remainingBytesCount >= 9) { @@ -1382,8 +1956,6 @@ class MeshCoreConnection { final est = reader.readUInt32LE(); info = SentInfo(flood: flood, tag: tag, estTimeoutMs: est); } - _sentCompleter?.complete(); - _sentCompleter = null; final admin = _adminSentCompleter; _adminSentCompleter = null; if (admin != null && !admin.isCompleted) { @@ -1418,8 +1990,22 @@ class MeshCoreConnection { void _onChannelInfoResponse(BufferReader reader) { final info = ChannelInfo.fromReader(reader); - _channelInfoCompleter?.complete(info); + final completer = _channelInfoCompleter; + if (completer == null) { + debugLog('[CONN] Ignoring unrequested CHANNEL_INFO for slot ' + '${info.channelIndex}'); + return; + } + if (info.channelIndex != _channelInfoRequestedIdx) { + // A late reply to a read that already timed out. Taking it would put + // every later answer one slot behind its request. + debugLog('[CONN] Ignoring CHANNEL_INFO for slot ${info.channelIndex} ' + 'while waiting for slot $_channelInfoRequestedIdx'); + return; + } + completer.complete(info); _channelInfoCompleter = null; + _channelInfoRequestedIdx = null; } void _onRawDataPush(BufferReader reader) { @@ -1540,6 +2126,7 @@ class MeshCoreConnection { } _binaryResponseCompleter = null; _binaryResponseTag = null; + _binaryResponseReceivedAt = clock.now(); final data = reader.readRemainingBytes(); debugLog('[CONN] BINARY_RESPONSE ${data.length} bytes'); completer.complete(data); @@ -1648,19 +2235,329 @@ class MeshCoreConnection { /// setFloodScope, setChannel, setPathHashMode, setAdvertName and setTxPower — /// letting one of those onto the wire mid-sign means its OK is consumed as /// the chunk ack and the handshake desynchronises. Sign's own frames pass - /// [isSignFrame] and bypass the gate. - Future _write(Uint8List bytes, {bool isSignFrame = false}) async { - if (!isSignFrame) { - final gate = _signGate; - if (gate != null && !gate.isCompleted) { - final code = bytes.isNotEmpty ? bytes[0] : -1; - debugLog('[CONN] Queuing command $code behind an in-progress sign'); - // The gate future NEVER completes with an error, so a queued command - // is delayed, never failed. - await gate.future; + /// [isSignFrame] and bypass the gate. [onWire] runs synchronously just + /// before the frame is handed to the transport, after any gate wait. + /// + /// While a scope lease is held, every write not issued by that [lease] + /// waits at the lease gate the same way, and goes out in order once the + /// lease is released. A lease write is checked against its lease right + /// before the transport write, so a cancelled or ended lease never puts + /// another byte on the air; it then resolves false. + /// + /// Every frame that goes out is entered in the reply ledger (see + /// [_replyShape]) before the transport write starts; the expiry of each + /// entry starts when that write returns. + Future _write(Uint8List bytes, + {bool isSignFrame = false, + void Function()? onWire, + ScopeLease? lease}) async { + final code = bytes.isNotEmpty ? bytes[0] : -1; + while (true) { + if (!isSignFrame) { + final gate = _signGate; + if (gate != null && !gate.isCompleted) { + debugLog('[CONN] Queuing command $code behind an in-progress sign'); + // The gate future NEVER completes with an error, so a queued + // command is delayed, never failed. + await gate.future; + continue; + } } + if (lease == null) { + final gate = _leaseGate; + if (gate != null && !gate.isCompleted) { + debugLog('[CONN] Queuing command $code behind a scope lease'); + _leaseGateWaiters++; + try { + await gate.future; + } finally { + _leaseGateWaiters--; + } + continue; + } + } + break; + } + // After the gate waits, which dispose() releases: a disposed connection + // was abandoned or superseded, and the transport may already carry a + // newer connection whose replies this frame would steal. + if (_disposed) { + debugLog('[CONN] Command $code not written: connection disposed'); + throw const RadioAbortedException(); + } + if (lease != null && (!lease.active || lease.cancelled)) { + debugLog('[SCOPES] Command $code not written: the lease has ended'); + return false; + } + onWire?.call(); + final shape = _replyShape(bytes); + final owed = <_OwedReply>[ + for (var i = 0; i < shape.replies; i++) + _OwedReply(code, + selfTelemetry: shape.selfTelemetry, + opensContactStream: shape.opensContactStream, + scopeOwned: lease != null), + ]; + _repliesOwed.addAll(owed); + if (shape.replies == 0 && !_radioRestarting) { + // Reboot, factory reset or a CLI reboot: the radio answers nothing and + // goes away. No lease until the connection is rebuilt. + _radioRestarting = true; + debugWarn('[SCOPES] Command $code restarts the radio; scope discovery ' + 'off until reconnect'); + } + if (shape.opensContactStream) { + _setContactsStream(ContactsStreamState.requested); + } + // APP_START stops the firmware's contact iterator without an END. + final cancelsStream = code == CommandCodes.appStart && + _contactsStream == ContactsStreamState.open; + try { + await _transport.write(bytes); + } catch (_) { + // CompanionTransport cannot say whether a throwing write went out + // before it failed, so every throw is ambiguous: the ledger entries + // stay (and expire as usual) and a contact stream stays requested, so + // a CONTACTS_START that does arrive opens it, and a stream that never + // comes trips the silence rule instead of letting a lease in. + _armReplyExpiry(owed); + rethrow; + } + _armReplyExpiry(owed); + if (cancelsStream && _contactsStream == ContactsStreamState.open) { + debugLog('[CONN] APP_START ended the open contact stream'); + _setContactsStream(ContactsStreamState.none); + } + return true; + } + + /// The reply table: how many reply frames [frame] earns. Pure. + static CommandReplyShape _replyShape(Uint8List frame) { + if (frame.isEmpty) return const CommandReplyShape(); + final payload = frame.sublist(1); + bool startsWith(String text) { + final t = text.codeUnits; + if (payload.length < t.length) return false; + for (var i = 0; i < t.length; i++) { + if (payload[i] != t[i]) return false; + } + return true; + } + + switch (frame[0]) { + case CommandCodes.getContacts: + return const CommandReplyShape(opensContactStream: true); + case CommandCodes.sendTelemetryReq: + // Only the 4-byte form is the self request, answered by push 0x8B. + return frame.length == 4 + ? const CommandReplyShape(selfTelemetry: true) + : const CommandReplyShape(); + case CommandCodes.reboot: + return startsWith('reboot') + ? const CommandReplyShape(replies: 0) + : const CommandReplyShape(); + case CommandCodes.factoryReset: + return startsWith('reset') + ? const CommandReplyShape(replies: 0) + : const CommandReplyShape(); + case CommandCodes.runCliCommand: + if (frame.length < 3) return const CommandReplyShape(); + final nul = payload.indexOf(0); + var text = + String.fromCharCodes(nul < 0 ? payload : payload.sublist(0, nul)); + // The firmware accepts an optional two-character prefix, "xx|". + if (text.length > 4 && text[2] == '|') text = text.substring(3); + return text == 'reboot' + ? const CommandReplyShape(replies: 0) + : const CommandReplyShape(); + default: + return const CommandReplyShape(); + } + } + + /// [_replyShape], for the fixture tests. + @visibleForTesting + static CommandReplyShape replyShapeOf(Uint8List frame) => _replyShape(frame); + + /// Writes [frame] as is, through the one funnel. Tests use it for commands + /// the app has no method for. + @visibleForTesting + Future debugWriteRaw(Uint8List frame) => _write(frame); + + /// Replies still owed by the radio, for tests. + @visibleForTesting + int get repliesOwedCount => _repliesOwed.length; + + /// Where the contact stream stands, for tests. + @visibleForTesting + ContactsStreamState get contactsStreamState => _contactsStream; + + void _armReplyExpiry(List<_OwedReply> owed) { + for (final entry in owed) { + if (!_repliesOwed.contains(entry)) continue; + entry.expiry?.cancel(); + entry.expiry = Timer(replyOwedExpiry, () { + if (_repliesOwed.remove(entry)) { + _reportScopeRadioBusy(); + debugLog('[CONN] No reply to command ${entry.command} within ' + '${replyOwedExpiry.inSeconds}s, dropped from the reply ledger'); + // The reply may still come, and nothing says which later frame + // answers which command: a stale ERR_NOT_FOUND or CONTACT could be + // taken as a new lookup's answer and skip the zero-hop borrow. + if (!_replySyncLost) { + _replySyncLost = true; + debugWarn('[SCOPES] Replies out of step after command ' + '${entry.command} went unanswered; scope discovery ' + 'suspended until reconnect'); + } + } + }); + } + } + + /// Counts [code] against the ledger. Returns true when the frame is a + /// reply (so a lease waiting on one may take it). + /// + /// A reply is any frame below 0x80, plus push 0x8B when the oldest entry is + /// a self-telemetry request. A streamed CONTACT or END_OF_CONTACTS is never + /// a reply: it only moves the stream state. + bool _accountReply(int code) { + if (code == ResponseCodes.endOfContacts) { + if (_contactsStream != ContactsStreamState.none) { + _setContactsStream(ContactsStreamState.none); + } + return false; + } + if (code == ResponseCodes.contact && + _contactsStream != ContactsStreamState.none) { + _setContactsStream(_contactsStream); + return false; + } + final isReply = code < 0x80 || + (code == PushCodes.telemetryResponse && + _repliesOwed.isNotEmpty && + _repliesOwed.first.selfTelemetry); + if (!isReply) return false; + if (code == ResponseCodes.contactsStart && + _contactsStream == ContactsStreamState.requested) { + _setContactsStream(ContactsStreamState.open); + } + if (_repliesOwed.isEmpty) return true; + final entry = _repliesOwed.removeAt(0); + entry.expiry?.cancel(); + if (entry.scopeOwned) _reportScopeRadioBusy(); + if (entry.opensContactStream && + code != ResponseCodes.contactsStart && + _contactsStream == ContactsStreamState.requested) { + // The initial reply was not CONTACTS_START (an ERR such as BAD_STATE): + // no stream follows. + _setContactsStream(ContactsStreamState.none); + } + return true; + } + + /// Moves the stream to [state]. Any state but none (re)arms the silence + /// watchdog, so calling it with the current state marks a frame. + void _setContactsStream(ContactsStreamState state) { + _contactsStream = state; + _contactsStreamWatchdog?.cancel(); + _contactsStreamWatchdog = null; + if (state == ContactsStreamState.none) return; + _contactsStreamWatchdog = Timer(kContactsStreamSilence, () { + _contactsStreamWatchdog = null; + if (_contactsStream == ContactsStreamState.none || _scopeSuspended) { + return; + } + // A lost START or END, or a frame that never arrived. Not cleared: + // the firmware may still be streaming, so scope discovery stays off. + _scopeSuspended = true; + debugWarn('[SCOPES] Contact stream ${_contactsStream.name} and silent ' + 'for ${kContactsStreamSilence.inSeconds}s; scope discovery ' + 'suspended until reconnect'); + }); + } + + /// Clears the ledger and the stream state (disconnect and dispose). + void _resetReplyLedger() { + for (final entry in _repliesOwed) { + entry.expiry?.cancel(); + } + _repliesOwed.clear(); + _reportScopeRadioBusy(); + _contactsStreamWatchdog?.cancel(); + _contactsStreamWatchdog = null; + _contactsStream = ContactsStreamState.none; + _scopeSuspended = false; + _replySyncLost = false; + } + + /// Queues a claim on the next OK or ERR for a send about to hit the wire. + _OwnReplyClaim _armOwnReply(_OwnReplyKind kind, {Duration? timeout}) { + final claim = _OwnReplyClaim(kind); + final wait = timeout ?? ownReplyTimeout; + claim.expiry = Timer(wait, () { + if (_ownReplyClaims.remove(claim)) { + debugWarn('[CONN] No reply to ${claim.label} within ' + '${wait.inMilliseconds}ms'); + } + claim.settle(); + }); + _ownReplyClaims.add(claim); + return claim; + } + + /// Sends [data] with a claim on its own OK or ERR. The claim is dropped + /// again when the write itself fails. + Future<_OwnReplyClaim> _sendClaimingReply( + BufferWriter data, _OwnReplyKind kind, + {void Function()? onWire, Duration? timeout}) async { + _OwnReplyClaim? claim; + try { + await _write(data.toBytes(), onWire: () { + onWire?.call(); + claim = _armOwnReply(kind, timeout: timeout); + }); + } catch (_) { + final armed = claim; + if (armed != null) { + _ownReplyClaims.remove(armed); + armed.settle(); + } + rethrow; + } + return claim!; + } + + /// Hands an OK ([errorCode] null) or an ERR to the oldest pending TX or + /// discovery claim. Returns false when no claim is pending. + bool _claimOwnReply(int? errorCode) { + if (_ownReplyClaims.isEmpty) return false; + final claim = _ownReplyClaims.removeAt(0); + claim.answered = true; + claim.errorCode = errorCode; + claim.settle(); + if (errorCode == null) { + debugLog('[CONN] OK claimed by ${claim.label}'); + } else { + // Logged only for TX and discovery: the send's return and the ping flow + // are unchanged. A channel write reads the code and throws. + debugWarn('[CONN] ${switch (claim.kind) { + _OwnReplyKind.tx => 'TX send', + _OwnReplyKind.discovery => 'Discovery request', + _OwnReplyKind.channel => 'Channel write', + }} rejected by radio (error code $errorCode)'); + } + return true; + } + + /// Settles every pending TX or discovery claim, so no send is left waiting + /// on a link that is going away. + void _releaseOwnReplies() { + final claims = List<_OwnReplyClaim>.of(_ownReplyClaims); + _ownReplyClaims.clear(); + for (final claim in claims) { + claim.settle(); } - await _transport.write(bytes); } /// Write frame to device @@ -1677,11 +2574,26 @@ class MeshCoreConnection { /// its frame reach the wire long after that deadline, with nothing left to /// check by then. Awaiting this first moves the wait to a point where /// abandoning is still free and leaves no half-built transmission behind. + /// + /// A held scope lease parks writes the same way (for at most its 4 s + /// deadline), so it is waited out here too. Future awaitWritableState() async { - final gate = _signGate; - if (gate == null || gate.isCompleted) return; - debugLog('[CONN] Caller waiting out an in-progress sign before deciding'); - await gate.future; + while (true) { + final gate = _signGate; + if (gate != null && !gate.isCompleted) { + debugLog( + '[CONN] Caller waiting out an in-progress sign before deciding'); + await gate.future; + continue; + } + final leaseGate = _leaseGate; + if (leaseGate != null && !leaseGate.isCompleted) { + debugLog('[CONN] Caller waiting out a scope lease before deciding'); + await leaseGate.future; + continue; + } + return; + } } // ============================================ @@ -1808,6 +2720,7 @@ class MeshCoreConnection { Future getChannel(int channelIdx) async { debugLog('[CONN] getChannel($channelIdx) - sending request'); _channelInfoCompleter = Completer(); + _channelInfoRequestedIdx = channelIdx; // Save reference to future BEFORE writing command to avoid race condition // where response arrives and nulls completer before we can access the future @@ -1830,14 +2743,37 @@ class MeshCoreConnection { ); } - /// Set channel - Future setChannel(int channelIdx, String name, Uint8List secret) async { + /// How long a channel delete waits for its OK during disconnect. Short on + /// purpose: teardown must not stall on a radio that stays quiet. + static const Duration channelDeleteReplyTimeout = + Duration(milliseconds: 1500); + + /// Set channel and await the radio's OK or ERR. + /// + /// The firmware answers CMD_SET_CHANNEL with a bare OK, or ERR on a bad + /// index or name. The reply is claimed like a TX send's (FIFO among own + /// claims), so an OK arriving for this write is never left for another + /// consumer. Throws [CommandErrorException] on ERR. When no reply arrives + /// within [replyTimeout] (default [ownReplyTimeout]) it logs and returns, + /// as setDeviceTime does: the write may still have landed. + Future setChannel(int channelIdx, String name, Uint8List secret, + {Duration? replyTimeout}) async { final data = BufferWriter(); data.writeByte(CommandCodes.setChannel); data.writeByte(channelIdx); data.writeCString(name, 32); data.writeBytes(secret); - await _sendToRadio(data); + final claim = await _sendClaimingReply(data, _OwnReplyKind.channel, + timeout: replyTimeout); + await claim.reply.future; + final errorCode = claim.errorCode; + if (errorCode != null) { + throw CommandErrorException(errorCode); + } + if (!claim.answered) { + debugWarn('[CHANNEL] No OK for channel write at index $channelIdx, ' + 'continuing'); + } } /// Set flood scope for regional packet filtering @@ -1860,7 +2796,8 @@ class MeshCoreConnection { /// Delete channel by setting it to empty Future deleteChannel(int channelIdx) async { - await setChannel(channelIdx, '', Uint8List(16)); + await setChannel(channelIdx, '', Uint8List(16), + replyTimeout: channelDeleteReplyTimeout); } /// Get all channels (queries until error) @@ -1914,28 +2851,25 @@ class MeshCoreConnection { /// Send channel text message (for TX pings) /// Reference: sendCommandSendChannelTxtMsg in connection.js + /// + /// [onWire] runs once the frame is past every write gate (sign, scope + /// lease), immediately before the transport write. Future sendChannelTextMessage( - int txtType, int channelIdx, int senderTimestamp, String text) async { - _sentCompleter = Completer(); - - // Save reference to future BEFORE sending command to avoid race condition - final future = _sentCompleter!.future; - + int txtType, int channelIdx, int senderTimestamp, String text, + {void Function()? onWire}) async { final data = BufferWriter(); data.writeByte(CommandCodes.sendChannelTxtMsg); data.writeByte(txtType); data.writeByte(channelIdx); data.writeUInt32LE(senderTimestamp); data.writeString(text); - await _sendToRadio(data); - // Wait for sent confirmation (with timeout) - await future.timeout( - const Duration(seconds: 3), - onTimeout: () { - // Ignore timeout - message may still be sent - }, - ); + // The firmware answers with OK, or ERR on a bad channel index, never with + // RESP_CODE_SENT. Wait for that reply (normally a few milliseconds); the + // claim gives up after [ownReplyTimeout], as the message may still be sent. + final claim = + await _sendClaimingReply(data, _OwnReplyKind.tx, onWire: onWire); + await claim.reply.future; } /// Send a pre-composed TX body to the #wardriving channel. @@ -1944,7 +2878,11 @@ class MeshCoreConnection { /// so the exact same string is used for both TxTracker echo matching and the /// actual transmission. /// Power is not included in the mesh message — it is sent per-ping in the API payload. - Future sendPing(String message) async { + /// + /// [onWire] runs when the frame actually goes out, after any wait behind a + /// sign or a scope lease and before the transport write, so echo tracking + /// armed there is live for the transmission and timed from it. + Future sendPing(String message, {void Function()? onWire}) async { final channel = _wardrivingChannel; if (channel == null) { throw Exception('Wardriving channel not initialized'); @@ -1953,7 +2891,8 @@ class MeshCoreConnection { debugLog('[CONN] Sending ping: $message'); final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; await sendChannelTextMessage( - TxtTypes.plain, channel.channelIndex, timestamp, message); + TxtTypes.plain, channel.channelIndex, timestamp, message, + onWire: onWire); } /// Send discovery request to find nearby repeaters/rooms @@ -1966,8 +2905,11 @@ class MeshCoreConnection { /// - Bytes 3-6: random tag (4 bytes) /// - Bytes 7-10: timestamp = 0 (discover all) /// - /// Returns the 4-byte tag used for matching responses - Future sendDiscoveryRequest() async { + /// Returns the 4-byte tag used for matching responses, and [sentAt]: the + /// moment the frame was handed to the transport, after any sign or lease + /// gate wait and before the (acknowledged) transport write. That is local + /// command submission, not the radio's own transmission. + Future<({Uint8List tag, DateTime sentAt})> sendDiscoveryRequest() async { // Generate random 4-byte tag final random = Random.secure(); final tag = Uint8List.fromList([ @@ -1987,9 +2929,13 @@ class MeshCoreConnection { DiscoveryConstants.typeFilterRepeaterRoom); // 0x0C = REPEATER | ROOM data.writeBytes(tag); // 4-byte random tag data.writeUInt32LE(0); // timestamp = 0 (discover all) - await _sendToRadio(data); + // Claim the OK or ERR so it cannot complete another command's waiter. + // Nothing waits on it. + DateTime? sentAt; + await _sendClaimingReply(data, _OwnReplyKind.discovery, + onWire: () => sentAt = clock.now()); - return tag; + return (tag: tag, sentAt: sentAt ?? clock.now()); } /// Send trace path to a specific repeater (targeted ping / zero-hop trace) @@ -2072,10 +3018,29 @@ class MeshCoreConnection { } /// Read the radio's whole contact list (CMD_GET_CONTACTS with since = 0). - Future> getContacts( - {Duration timeout = const Duration(seconds: 20)}) async { + /// + /// The wait follows the stream rather than a fixed total: it times out + /// after [silenceTimeout] with no frame of the list, or at [timeout] + /// overall. The radio streams about one contact per 60 ms, so a 350 entry + /// table takes over 21 s, and a fixed 20 s cut it off every time. + Future> getContacts({ + Duration silenceTimeout = const Duration(seconds: 5), + Duration timeout = const Duration(seconds: 120), + }) async { final token = _beginAdminCommand('getContacts'); final completer = Completer>(); + Timer? silence; + void armSilence() { + silence?.cancel(); + silence = Timer(silenceTimeout, () { + if (completer.isCompleted) return; + debugWarn('[CONN] getContacts: radio silent for ' + '${silenceTimeout.inMilliseconds}ms ' + '(${_contactsBuffer.length} contacts received)'); + completer.completeError(TimeoutException('getContacts timed out')); + }); + } + try { await _drainPollsForAdminCommand('getContacts'); _contactsCompleter = completer; @@ -2086,12 +3051,16 @@ class MeshCoreConnection { ..writeByte(CommandCodes.getContacts) ..writeUInt32LE(since); await _sendToRadio(data); + _contactsProgress = armSilence; + armSilence(); return await completer.future.timeout(timeout, onTimeout: () { _contactsCompleter = null; _contactsBuffer = []; throw TimeoutException('getContacts timed out'); }); } finally { + silence?.cancel(); + if (identical(_contactsProgress, armSilence)) _contactsProgress = null; // A write that threw before completer.future was ever awaited leaves // this call's completer registered with no listener. Clear it here // (only if it is still the one this call installed - a later call may @@ -2373,6 +3342,27 @@ class MeshCoreConnection { if (_disposed) { throw StateError('Cannot sign on a disposed connection'); } + // A sign's chunk OKs are bare, so it cannot share the radio with a scope + // lease, and it must not start during the answer wait that follows one. + // Wait for scope work to let go, then re-check and arm synchronously. + if (_scopeBusyForSign) { + _signWaiters++; + debugLog('[CONN] sign: waiting for scope discovery to release the radio'); + try { + await _waitForScopeIdle(signScopeWait); + } finally { + _signWaiters--; + } + if (_disposed) { + throw StateError('Cannot sign on a disposed connection'); + } + if (_scopeBusyForSign) { + debugWarn('[CONN] sign: radio still held by scope discovery after ' + '${signScopeWait.inSeconds}s'); + throw const SignException( + 'busy', 'The radio is busy with scope discovery'); + } + } if (_signInProgress) { throw StateError('A sign is already in progress'); } @@ -2499,15 +3489,34 @@ class MeshCoreConnection { _noiseFloorTimer?.cancel(); _isFetchingNoiseFloor = false; _noiseFloorFailCount = 0; + _noiseFloorBackedOff = false; // Get initial reading immediately _fetchNoiseFloor(); - _noiseFloorTimer = Timer.periodic(const Duration(seconds: 5), (_) async { + _scheduleNoiseFloorTimer(noiseFloorPollInterval); + + debugLog('[CONN] Started noise floor polling ' + '(${noiseFloorPollInterval.inSeconds}s interval)'); + } + + /// Starts noise floor polling outside the connect workflow, for tests. + @visibleForTesting + void debugStartNoiseFloorPolling() => _startNoiseFloorPolling(); + + /// Whether noise floor polling is running, for tests. + @visibleForTesting + bool get isNoiseFloorPolling => _noiseFloorTimer != null; + + /// Whether noise floor polling is backed off to the slower interval. + @visibleForTesting + bool get isNoiseFloorBackedOff => _noiseFloorBackedOff; + + void _scheduleNoiseFloorTimer(Duration interval) { + _noiseFloorTimer?.cancel(); + _noiseFloorTimer = Timer.periodic(interval, (_) async { await _fetchNoiseFloor(); }); - - debugLog('[CONN] Started noise floor polling (5s interval)'); } /// True while a repeater admin command holds the link. The two pollers @@ -2517,7 +3526,14 @@ class MeshCoreConnection { /// The poll simply skips a tick; the next one runs once the command ends. /// A poll that was ALREADY on the wire when the slot was claimed is waited /// out instead, by [_drainPollsForAdminCommand]. - bool get _pollsHeld => _adminCommandInFlight != null; + /// + /// Scope work holds the pollers only while its LEASE is held; during the + /// answer wait that follows, the slot is owned by a scope-listen token and + /// the pollers run as normal. + bool get _pollsHeld => + _lease != null || + (_adminCommandInFlight != null && + !identical(_adminCommandInFlight, _scopeListenToken)); Future _fetchNoiseFloor() async { if (_isFetchingNoiseFloor) return; // Skip if previous fetch still in flight @@ -2539,13 +3555,28 @@ class MeshCoreConnection { // line (once every 5 seconds, all session) pure duplication. await getNoiseFloor(); _noiseFloorFailCount = 0; // Reset on success + // Polling may have been stopped (disconnect) while this fetch was in + // flight; only a live poller returns to the normal interval. + if (_noiseFloorBackedOff && _noiseFloorTimer != null) { + _noiseFloorBackedOff = false; + _scheduleNoiseFloorTimer(noiseFloorPollInterval); + debugLog('[CONN] Noise floor fetch recovered, polling back to ' + '${noiseFloorPollInterval.inSeconds}s'); + } } catch (e) { _noiseFloorFailCount++; - debugLog('[CONN] Noise floor fetch failed ($_noiseFloorFailCount/3): $e'); - if (_noiseFloorFailCount >= 3) { - debugLog( - '[CONN] Noise floor polling stopped after 3 consecutive failures'); - _stopNoiseFloorPolling(); + debugLog('[CONN] Noise floor fetch failed ' + '($_noiseFloorFailCount/$_noiseFloorFailLimit): $e'); + // Back off rather than stop: a run of transient failures used to end + // polling for the rest of the session while battery polls kept working. + if (_noiseFloorFailCount >= _noiseFloorFailLimit && + !_noiseFloorBackedOff && + _noiseFloorTimer != null) { + _noiseFloorBackedOff = true; + _scheduleNoiseFloorTimer(noiseFloorBackoffInterval); + debugWarn('[CONN] Noise floor polling slowed to ' + '${noiseFloorBackoffInterval.inSeconds}s after ' + '$_noiseFloorFailLimit consecutive failures'); } } finally { _isFetchingNoiseFloor = false; @@ -2557,6 +3588,7 @@ class MeshCoreConnection { _noiseFloorTimer?.cancel(); _noiseFloorTimer = null; _isFetchingNoiseFloor = false; + _noiseFloorBackedOff = false; debugLog('[CONN] Stopped noise floor polling'); } @@ -2618,10 +3650,16 @@ class MeshCoreConnection { /// Dispose of resources void dispose() { _disposed = true; + // Not emitted (the stream closes below), but anything still holding this + // object, such as a PingService timer guard, must not read it as live. + _currentStep = ConnectionStep.disconnected; _stopNoiseFloorPolling(); _stopBatteryPolling(); _abortPendingSign(); + _abortScopeWork('dispose'); _abortPendingAdmin(); + _releaseOwnReplies(); + _resetReplyLedger(); _setTimeCompleter = null; _dataSubscription?.cancel(); _stepController.close(); @@ -2635,3 +3673,54 @@ class MeshCoreConnection { _pathUpdatedController.close(); } } + +/// Hands a [ScopeLease] the connection's private primitives, so the lease +/// logic can live in its own file without widening this class's API. +class _ScopeLeaseHostAdapter implements ScopeLeaseHost { + final MeshCoreConnection _c; + + _ScopeLeaseHostAdapter(this._c); + + @override + bool get repliesSettled => _c._repliesOwed.isEmpty; + + @override + Future writeForLease(ScopeLease lease, Uint8List frame) => + _c._write(frame, lease: lease); + + @override + void setLeaseReplyWaiter( + ScopeLease lease, void Function(Uint8List frame)? waiter) { + if (identical(_c._lease, lease)) _c._leaseReplyWaiter = waiter; + } + + @override + Future armScopeAnswer() => _c._armScopeAnswer(); + + @override + void setScopeAnswerTag(Uint8List tag) { + if (_c._scopeAnswerCompleter != null) _c._binaryResponseTag = tag; + } + + @override + void disarmScopeAnswer() => _c._disarmScopeAnswer(); + + @override + void endLease(ScopeLease lease, {required bool listen}) => + _c._endScopeLease(lease, listen: listen); + + @override + void endListen() => _c._endScopeListen(); + + @override + bool get cannotAskNonContacts => _c._scopeCannotAskNonContacts; + + @override + void markCannotAskNonContacts() { + if (_c._scopeCannotAskNonContacts) return; + _c._scopeCannotAskNonContacts = true; + debugLog('[SCOPES] Radio contact table full: no more asks to repeaters ' + 'that are not saved contacts on this connection'); + _c.onScopeCannotAskNonContactsChanged?.call(); + } +} diff --git a/lib/services/meshcore/crypto_service.dart b/lib/services/meshcore/crypto_service.dart index ea6f559b..7c6fc6b5 100644 --- a/lib/services/meshcore/crypto_service.dart +++ b/lib/services/meshcore/crypto_service.dart @@ -73,16 +73,16 @@ class CryptoService { /// Derive a 16-byte TransportKey from a scope/region name /// Same algorithm as channel key derivation: SHA-256(name)[0:16] - /// API returns names without '#' prefix (e.g., "ottawa") — we prepend it + /// API returns names without '#' prefix (e.g., "ottawa"), so we prepend it /// to match MeshCore's implicit hashtag region convention + /// Scope names are case-sensitive and must match the region configuration exactly static Uint8List deriveScopeKey(String scopeName) { final name = scopeName.startsWith('#') ? scopeName : '#$scopeName'; - final normalizedName = name.toLowerCase(); - final bytes = utf8.encode(normalizedName); + final bytes = utf8.encode(name); final digest = sha256.convert(bytes); final scopeKey = Uint8List.fromList(digest.bytes.sublist(0, 16)); debugLog( - '[CRYPTO] Scope key derived for "$normalizedName" (${scopeKey.length} bytes)'); + '[CRYPTO] Scope key derived for "$name" (${scopeKey.length} bytes)'); return scopeKey; } @@ -110,6 +110,13 @@ class CryptoService { return digest.bytes[0]; } + /// Whether [length] bytes of ciphertext can be AES-ECB decrypted: at least + /// one block and a whole number of 16-byte blocks. Anything else is a + /// malformed packet, so callers drop it before calling + /// [decryptChannelMessage]. + static bool isValidCiphertextLength(int length) => + length > 0 && length % 16 == 0; + /// Decrypt channel message using AES-ECB mode /// /// MeshCore uses AES-128-ECB for channel message encryption diff --git a/lib/services/meshcore/disc_tracker.dart b/lib/services/meshcore/disc_tracker.dart index e5a348be..b3424385 100644 --- a/lib/services/meshcore/disc_tracker.dart +++ b/lib/services/meshcore/disc_tracker.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:typed_data'; +import 'package:clock/clock.dart'; + import '../../utils/debug_logger_io.dart'; import 'packet_validator.dart'; import 'protocol_constants.dart'; @@ -17,6 +19,11 @@ class DiscTracker { Timer? _windowTimer; + /// This sweep's own tag and when its command was submitted to the radio. + /// Only a reply carrying [_ownTag] gets a reply time. + Uint8List? _ownTag; + DateTime? _sentAt; + /// Callback to check if a repeater should be ignored (carpeater filter) final bool Function(String repeaterId)? shouldIgnoreRepeater; @@ -49,10 +56,15 @@ class DiscTracker { /// Start tracking discovery responses /// - /// @param tag - 4-byte random tag (for logging purposes) + /// @param tag - this sweep's own 4-byte tag + /// @param sentAt - when the discovery command was submitted to the radio; + /// a reply carrying [tag] gets its time after this as + /// [DiscoveredNode.discoveryReplyAfter]. Replies to any other tag are + /// still accepted, without a reply time. /// @param windowDuration - How long to listen (default 7 seconds) void startTracking({ required Uint8List tag, + DateTime? sentAt, Duration windowDuration = const Duration(seconds: 7), }) { debugLog('[DISC] Starting discovery tracking'); @@ -62,6 +74,8 @@ class DiscTracker { isListening = true; startTime = DateTime.now(); nodes.clear(); + _ownTag = Uint8List.fromList(tag); + _sentAt = sentAt; // Start window timer _windowTimer?.cancel(); @@ -144,7 +158,20 @@ class DiscTracker { final remoteSnrRaw = rawBytes[2].toSigned(8); final remoteSnr = remoteSnrRaw / 4.0; - // Skip tag (bytes 3-6) - we accept any response during the window + // Any tag is accepted during the window (another phone's discovery + // included); only this sweep's own tag gets a reply time. + final sentAt = _sentAt; + final ownTag = _ownTag; + Duration? replyAfter; + if (sentAt != null && + ownTag != null && + ownTag.length == 4 && + rawBytes[3] == ownTag[0] && + rawBytes[4] == ownTag[1] && + rawBytes[5] == ownTag[2] && + rawBytes[6] == ownTag[3]) { + replyAfter = clock.now().difference(sentAt); + } // Extract public key (bytes 7-38) final pubkey = rawBytes.sublist(7, 39); @@ -205,7 +232,17 @@ class DiscTracker { localRssi: localRssi, remoteSnr: remoteSnr, pubkeyFull: pubkeyHex, + // Short ids can collide: a reply time only carries over within + // the same full key. + discoveryReplyAfter: replyAfter ?? + (existing.pubkeyFull == pubkeyHex + ? existing.discoveryReplyAfter + : null), ); + } else if (existing.discoveryReplyAfter == null && + replyAfter != null && + existing.pubkeyFull == pubkeyHex) { + nodes[repeaterId] = existing.withReplyAfter(replyAfter); } } else { // New node @@ -218,6 +255,7 @@ class DiscTracker { localRssi: localRssi, remoteSnr: remoteSnr, pubkeyFull: pubkeyHex, + discoveryReplyAfter: replyAfter, ); } @@ -247,7 +285,11 @@ class DiscoveredNode { final int localRssi; // RSSI as seen by local device (dBm) final double remoteSnr; // SNR as seen by remote node (dB) final String - pubkeyFull; // Full 32-byte public key as hex (local only, not sent to API) + pubkeyFull; // Full 32-byte public key as hex (sent to the API as public_key on the DISC item) + + /// How long after the discovery command was submitted this node's reply + /// to it arrived. Null for a reply to another phone's discovery. + final Duration? discoveryReplyAfter; DiscoveredNode({ required this.repeaterId, @@ -256,8 +298,20 @@ class DiscoveredNode { required this.localRssi, required this.remoteSnr, required this.pubkeyFull, + this.discoveryReplyAfter, }); + /// This node with [after] as its reply time. + DiscoveredNode withReplyAfter(Duration after) => DiscoveredNode( + repeaterId: repeaterId, + nodeType: nodeType, + localSnr: localSnr, + localRssi: localRssi, + remoteSnr: remoteSnr, + pubkeyFull: pubkeyFull, + discoveryReplyAfter: after, + ); + /// Get node type as display string String get nodeTypeName => nodeType == DiscoveryConstants.nodeTypeRepeater ? 'REPEATER' : 'ROOM'; diff --git a/lib/services/meshcore/packet_metadata.dart b/lib/services/meshcore/packet_metadata.dart index 268b3f3e..74cc388f 100644 --- a/lib/services/meshcore/packet_metadata.dart +++ b/lib/services/meshcore/packet_metadata.dart @@ -3,6 +3,17 @@ import 'dart:typed_data'; import '../../utils/debug_logger_io.dart'; import 'protocol_constants.dart'; +/// Thrown by [PacketMetadata.fromLogRxData] when the bytes end before the +/// header, path length or path they announce. A truncated packet off the +/// air is routine, so callers skip it quietly instead of logging an error. +class PacketTooShortException implements Exception { + final String message; + const PacketTooShortException(this.message); + + @override + String toString() => 'Packet too short: $message'; +} + /// Packet metadata extracted from BLE LogRxData events /// Reference: parseRxPacketMetadata() in wardrive.js (lines 3155-3195) class PacketMetadata { @@ -72,6 +83,10 @@ class PacketMetadata { .join(' '); debugLog('[RX PARSE] RAW Packet (${raw.length} bytes): $rawHex'); + if (raw.isEmpty) { + throw const PacketTooShortException('empty packet'); + } + // Extract header byte from raw[0] final int header = raw[0]; final int routeType = header & PacketHeader.routeMask; @@ -87,6 +102,11 @@ class PacketMetadata { pathLengthOffset = 5; } + if (pathLengthOffset >= raw.length) { + throw PacketTooShortException( + 'path length offset $pathLengthOffset exceeds packet length ${raw.length}'); + } + // Extract raw pathLen byte and decode multi-byte path encoding // pathHashSize = (pathLen >> 6) + 1 → 1, 2, 3, or 4 // pathHashCount = pathLen & 63 → 0-63 hops @@ -109,8 +129,8 @@ class PacketMetadata { // Extract encrypted payload after path data final int payloadOffset = pathDataOffset + pathByteLen; if (payloadOffset > raw.length) { - throw RangeError( - 'Packet too short: payload offset $payloadOffset exceeds packet length ${raw.length}'); + throw PacketTooShortException( + 'payload offset $payloadOffset exceeds packet length ${raw.length}'); } final Uint8List encryptedPayload = raw.sublist(payloadOffset); diff --git a/lib/services/meshcore/packet_validator.dart b/lib/services/meshcore/packet_validator.dart index e02ac529..887512d3 100644 --- a/lib/services/meshcore/packet_validator.dart +++ b/lib/services/meshcore/packet_validator.dart @@ -110,6 +110,14 @@ class PacketValidator { final encryptedMessage = metadata.encryptedPayload.sublist(3); debugLog('[RX FILTER] Encrypted message: ${encryptedMessage.length} bytes'); + // AES-ECB needs whole 16-byte blocks; a ragged length is a malformed + // packet, not a decryption error. + if (!CryptoService.isValidCiphertextLength(encryptedMessage.length)) { + debugLog('[RX FILTER] ❌ DROPPED: ciphertext length ' + '${encryptedMessage.length} is not a multiple of 16'); + return ValidationResult.failed('bad ciphertext length'); + } + final decryptedBytes = CryptoService.decryptChannelMessage( encryptedMessage, channelInfo.key, diff --git a/lib/services/meshcore/protocol_constants.dart b/lib/services/meshcore/protocol_constants.dart index b023da22..8ec83721 100644 --- a/lib/services/meshcore/protocol_constants.dart +++ b/lib/services/meshcore/protocol_constants.dart @@ -63,6 +63,8 @@ class CommandCodes { static const int sendRawData = 25; static const int sendLogin = 26; static const int sendStatusReq = 27; + /// CMD_GET_CONTACT_BY_KEY: [30][pubkey 32] -> RESP_CODE_CONTACT or ERR NOT_FOUND. + static const int getContactByKey = 30; static const int getChannel = 31; static const int setChannel = 32; static const int signStart = 33; @@ -75,8 +77,27 @@ class CommandCodes { static const int sendTelemetryReq = 39; static const int setFloodScope = 54; // 0x36 - CMD_SET_FLOOD_SCOPE static const int getStats = 56; // 0x38 + /// CMD_SEND_ANON_REQ: [57][pubkey 32][request]. Non-contact targets need + /// firmware code 13+. Answered by PUSH_CODE_BINARY_RESPONSE (0x8C). + static const int sendAnonReq = 57; static const int sendBinaryReq = 50; + + /// CMD_FACTORY_RESET: [51]["reset"]. Never sent by the app; listed so the + /// reply ledger knows it answers nothing (the radio drops the link first). + static const int factoryReset = 51; static const int setPathHashMode = 61; // 0x3D - CMD_SET_PATH_HASH_MODE + + /// CMD_RUN_CLI_COMMAND: [66][text], answered by one CLI reply, except + /// `reboot`, which answers nothing. Never sent by the app. + static const int runCliCommand = 66; +} + +/// Anonymous request types for CMD_SEND_ANON_REQ +class AnonRequestTypes { + AnonRequestTypes._(); + + /// Repeater regions (scope list) request. Direct route only on the repeater. + static const int regions = 0x01; } /// Response codes received from device @@ -99,9 +120,12 @@ class ResponseCodes { static const int deviceInfo = 13; static const int privateKey = 14; static const int disabled = 15; + static const int contactMsgRecvV3 = 16; + static const int channelMsgRecvV3 = 17; static const int channelInfo = 18; static const int signStart = 19; static const int signature = 20; + static const int advertPath = 22; // 0x16 static const int stats = 24; // 0x18 } @@ -124,6 +148,8 @@ class PushCodes { static const int binaryResponse = 0x8C; static const int controlData = 0x8E; // PUSH_CODE_CONTROL_DATA (discovery response) + static const int contactDeleted = 0x8F; + static const int contactsFull = 0x90; } /// Text message types diff --git a/lib/services/meshcore/rx_logger.dart b/lib/services/meshcore/rx_logger.dart index 60536e8c..52761c4c 100644 --- a/lib/services/meshcore/rx_logger.dart +++ b/lib/services/meshcore/rx_logger.dart @@ -2,8 +2,10 @@ import 'dart:async'; import 'dart:math'; import '../../utils/debug_logger_io.dart'; +import '../fix_altitude.dart'; import 'packet_metadata.dart'; import 'packet_validator.dart'; +import 'protocol_constants.dart'; /// Passive RX logger for continuous wardriving observations /// Reference: handleRxLogging() + handleRxBatching() in wardrive.js (lines 3812-4140) @@ -23,9 +25,10 @@ class RxLogger { /// Callback for immediate observation (fires before batching, for real-time UI) final void Function(RxObservation)? onObservation; - /// GPS location provider. `alt` is meters or null when the phone did not - /// know its altitude; it rides along to the API entry, nothing else reads it. - final ({double lat, double lon, double? alt})? Function() getGpsLocation; + /// GPS location provider. [altitude] is the fix's labelled altitude, or + /// unknown; it rides along to the API entry, nothing else reads it. + final ({double lat, double lon, FixAltitude altitude})? Function() + getGpsLocation; /// Function to check if a repeater ID should be ignored /// Returns true if the repeater should be filtered out @@ -66,11 +69,12 @@ class RxLogger { isWardriving = true; } - /// Stop passive RX wardriving and flush all batches - void stopWardriving({String trigger = 'user_stop'}) { + /// Stop passive RX wardriving and flush all batches. Returns the flush, so + /// a caller about to upload the queue can wait for the batches to land. + Future stopWardriving({String trigger = 'user_stop'}) { debugLog('[RX LOG] Stopping passive RX wardriving: trigger=$trigger'); isWardriving = false; - flushAllBatches(trigger: trigger); + return flushAllBatches(trigger: trigger); } /// Handle incoming packet for passive logging @@ -92,6 +96,18 @@ class RxLogger { return false; } + // A direct packet's path is the route it still has to travel (each + // repeater removes itself as it forwards), not the hops it came + // through, so its last hop is not who we heard. Crediting or blaming + // it named a repeater kilometres away as a carpeater when a nearby + // radio sent a login request routed through it. + if (metadata.routeType == RouteType.direct || + metadata.routeType == RouteType.reserved2) { + debugLog( + '[RX LOG] Ignoring: direct-routed packet (path is its remaining route)'); + return false; + } + bool carpeaterStripped = false; String repeaterId; double? reportedSnr = metadata.snr; @@ -197,7 +213,7 @@ class RxLogger { header: metadata.header, lat: gpsLocation.lat, lon: gpsLocation.lon, - alt: gpsLocation.alt, + altitude: gpsLocation.altitude, timestamp: DateTime.now(), metadata: metadata, displayHops: displayHops, @@ -250,7 +266,7 @@ class RxLogger { required int? rssi, required int pathLength, required int header, - required ({double lat, double lon, double? alt}) currentLocation, + required ({double lat, double lon, FixAltitude altitude}) currentLocation, required PacketMetadata metadata, required List displayHops, }) async { @@ -270,7 +286,7 @@ class RxLogger { header: header, lat: currentLocation.lat, lon: currentLocation.lon, - alt: currentLocation.alt, + altitude: currentLocation.altitude, timestamp: DateTime.now(), metadata: metadata, displayHops: displayHops, @@ -308,7 +324,7 @@ class RxLogger { header: header, lat: buffer.firstLocation.lat, // Keep original location lon: buffer.firstLocation.lon, // Keep original location - alt: buffer.firstLocation.alt, // and its altitude + altitude: buffer.firstLocation.altitude, // and its altitude timestamp: DateTime.now(), metadata: metadata, displayHops: displayHops, @@ -411,7 +427,7 @@ class RxLogger { repeaterId: repeaterId, lat: best.lat, lon: best.lon, - alt: best.alt, + altitude: best.altitude, snr: best.snr, rssi: best.rssi, pathLength: best.pathLength, @@ -503,7 +519,7 @@ class RxLogger { /// Batch buffer for a single repeater class RxBatch { - final ({double lat, double lon, double? alt}) firstLocation; + final ({double lat, double lon, FixAltitude altitude}) firstLocation; RxObservation bestObservation; Timer? timeoutTimer; @@ -524,8 +540,8 @@ class RxObservation { final double lat; final double lon; - /// Altitude in meters at [lat],[lon], null when unknown. - final double? alt; + /// The labelled altitude at [lat],[lon], unknown when not proved. + final FixAltitude altitude; final DateTime timestamp; final PacketMetadata metadata; @@ -541,7 +557,7 @@ class RxObservation { required this.header, required this.lat, required this.lon, - this.alt, + this.altitude = const FixAltitude.unknown(), required this.timestamp, required this.metadata, this.displayHops = const [], @@ -554,8 +570,8 @@ class RxApiEntry { final double lat; final double lon; - /// Altitude in meters at [lat],[lon], null when unknown. - final double? alt; + /// The labelled altitude at [lat],[lon], unknown when not proved. + final FixAltitude altitude; final double? snr; // Null for CARpeater pass-through final int? rssi; // Null for CARpeater pass-through final int pathLength; @@ -570,7 +586,7 @@ class RxApiEntry { required this.repeaterId, required this.lat, required this.lon, - this.alt, + this.altitude = const FixAltitude.unknown(), this.snr, this.rssi, required this.pathLength, diff --git a/lib/services/meshcore/scope_lease.dart b/lib/services/meshcore/scope_lease.dart new file mode 100644 index 00000000..48293621 --- /dev/null +++ b/lib/services/meshcore/scope_lease.dart @@ -0,0 +1,650 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; + +import '../../utils/debug_logger_io.dart'; +import '../scope_discovery/scope_runner.dart' show ScopeLeaseHandle; +import 'buffer_utils.dart'; +import 'connection.dart' show ContactRecord; +import 'protocol_constants.dart'; + +/// How long one lease may hold the radio, counted from the grant. Covers +/// everything the lease does: earlier restores, the lookup, the borrow, the +/// send, SENT and this ask's restore. +const Duration kScopeLeaseHold = Duration(seconds: 4); + +/// The least time left before the lease deadline for which a new command (or +/// a restore) is still written. +const Duration kScopeLeaseMinCommandTime = Duration(milliseconds: 500); + +/// The longest the answer wait may run, counted from SENT. +const Duration kScopeAnswerWaitCap = Duration(seconds: 7); + +/// Added to the radio's `est_timeout` when the caller gives no answer wait. +const Duration kScopeAnswerFallbackMargin = Duration(seconds: 1); + +/// The scope runner's cancellation: Stop, force disable, the hard stop or a +/// disconnect. Checked when a lease is granted and before every write the +/// lease makes. +class ScopeCancelToken { + final Completer _cancelled = Completer(); + + /// True once [cancel] has run. + bool get isCancelled => _cancelled.isCompleted; + + /// Fires the token. Idempotent. + void cancel() { + if (!_cancelled.isCompleted) _cancelled.complete(); + } + + /// Completes (never with an error) when the token fires. + Future get whenCancelled => _cancelled.future; +} + +/// What one scope request came to. Nothing in the request throws: every +/// failure is one of these. +/// +/// [borrowedFrom] is the contact record as read when its route was borrowed +/// for the send, and [restoreOwed] is true while that record has not been +/// written back (the caller keeps it for the next lease). +sealed class ScopeRequestOutcome { + final bool restoreOwed; + final ContactRecord? borrowedFrom; + + const ScopeRequestOutcome({this.restoreOwed = false, this.borrowedFrom}); +} + +/// The repeater answered. [body] is the reply with the tag removed, the +/// repeater's 4-byte clock still at the front. [receivedAt] is when the push +/// arrived. +final class ScopeAnswered extends ScopeRequestOutcome { + final Uint8List body; + final DateTime receivedAt; + + const ScopeAnswered(this.body, this.receivedAt, + {super.restoreOwed, super.borrowedFrom}); +} + +/// The request went out and no matching answer arrived in time. +final class ScopeNoAnswer extends ScopeRequestOutcome { + const ScopeNoAnswer({super.restoreOwed, super.borrowedFrom}); +} + +/// The radio flooded the request instead of sending it direct. +final class ScopeFlooded extends ScopeRequestOutcome { + const ScopeFlooded({super.restoreOwed, super.borrowedFrom}); +} + +/// The radio answered a step with ERR [code]. +final class ScopeRadioError extends ScopeRequestOutcome { + final int code; + + /// True when this was ERR_CODE_TABLE_FULL answering a send to a repeater + /// the lookup just found is not a saved contact: the connection-level + /// "cannot ask non-contacts" flag was set (or already set) because of + /// this ask. False for every other ERR, including the same code answering + /// a saved contact. + final bool nonContactTableFull; + + const ScopeRadioError(this.code, + {this.nonContactTableFull = false, + super.restoreOwed, + super.borrowedFrom}); +} + +/// The repeater was not a saved contact and this connection cannot ask +/// non-contacts (a send already came back ERR_CODE_TABLE_FULL for one on +/// this connection). Nothing beyond the lookup was written for this ask. +final class ScopeNonContactRefused extends ScopeRequestOutcome { + const ScopeNonContactRefused(); +} + +/// A local stop: `hold_cap` (the lease deadline), `malformed_sent`, +/// `write_failed` or `reply_owed` (a reply that was not the one expected). +final class ScopeLocalFailure extends ScopeRequestOutcome { + final String why; + + const ScopeLocalFailure(this.why, {super.restoreOwed, super.borrowedFrom}); +} + +/// Cancelled, or the connection went away. +final class ScopeAborted extends ScopeRequestOutcome { + const ScopeAborted({super.restoreOwed, super.borrowedFrom}); +} + +/// The tagged answer push: the body after the tag, and when it arrived. +typedef ScopeAnswerPush = ({Uint8List body, DateTime receivedAt}); + +/// The connection-side primitives a [ScopeLease] runs on. Implemented by +/// `MeshCoreConnection` only; nothing else should call these. +abstract interface class ScopeLeaseHost { + /// True when no reply is owed for any command already written. + bool get repliesSettled; + + /// Writes [frame] for [lease], past the lease gate. Resolves false when the + /// lease ended or was cancelled before the frame reached the transport; + /// throws when the transport write throws. + Future writeForLease(ScopeLease lease, Uint8List frame); + + /// Hands the next reply frame (code below 0x80) to [waiter], exactly once, + /// ahead of every other owner. Null clears it. + void setLeaseReplyWaiter( + ScopeLease lease, void Function(Uint8List frame)? waiter); + + /// Arms the answer slot before the send is written. + Future armScopeAnswer(); + + /// Installs the tag the answer must carry (called inside the SENT dispatch). + void setScopeAnswerTag(Uint8List tag); + + /// Drops the answer slot and its tag, so a late answer is ignored. + void disarmScopeAnswer(); + + /// Ends [lease]: opens the gate, resumes the pollers. With [listen] the + /// admin slot passes to a scope-listen token for the answer wait; without + /// it the slot is freed and the answer slot disarmed. + void endLease(ScopeLease lease, {required bool listen}); + + /// Ends the answer wait: disarms the answer slot and frees the admin slot. + void endListen(); + + /// True once a send to a repeater not among this connection's saved + /// contacts came back ERR_CODE_TABLE_FULL (a companion firmware bug: the + /// radio needs a contact-table slot for `CMD_SEND_ANON_REQ` and has none + /// free, fixed in v1.17.0's 8 reserved transient slots). Sticky for the + /// life of the connection. + bool get cannotAskNonContacts; + + /// Records that this connection cannot ask a repeater that is not a saved + /// contact. Idempotent. + void markCannotAskNonContacts(); +} + +enum _LeaseEnd { released, holdCap, cancelled, disconnected } + +sealed class _Reply { + const _Reply(); +} + +final class _Frame extends _Reply { + final Uint8List frame; + const _Frame(this.frame); +} + +final class _Ended extends _Reply { + final _LeaseEnd why; + const _Ended(this.why); +} + +final class _NotWritten extends _Reply { + final String why; + const _NotWritten(this.why); +} + +final class _WriteFailed extends _Reply { + final Object error; + const _WriteFailed(this.error); +} + +/// A short exclusive hold on the radio for one scope ask. +/// +/// The radio's OK, ERR, CONTACT and SENT replies carry no correlation, so +/// while a lease is held every other command waits at a gate and every reply +/// is the lease's. The lease writes one command at a time and waits for its +/// reply before the next. It ends at [kScopeLeaseHold] after the grant +/// whatever is in flight (a stalled transport write included), on cancel, on +/// disconnect, or when [requestScopes] has its SENT and restore in. +/// +/// Created only by `MeshCoreConnection.acquireScopeLease`. +class ScopeLease implements ScopeLeaseHandle { + final ScopeLeaseHost _host; + final ScopeCancelToken _cancel; + final DateTime _deadline; + Timer? _deadlineTimer; + + bool _active = true; + _LeaseEnd? _endReason; + Completer<_Reply>? _pending; + bool _tagArmed = false; + final List _unrestored = []; + + /// Grants a lease that holds for [hold]. Connection use only. + ScopeLease( + {required ScopeLeaseHost host, + required ScopeCancelToken cancel, + Duration hold = kScopeLeaseHold}) + : _host = host, + _cancel = cancel, + _deadline = clock.now().add(hold) { + _deadlineTimer = Timer(hold, _onDeadline); + unawaited(cancel.whenCancelled.then((_) => _onCancel())); + } + + /// True until the lease is released, runs out, is cancelled or aborted. + bool get active => _active; + + /// True once the runner's cancel token has fired. + bool get cancelled => _cancel.isCancelled; + + /// Records whose borrowed route has not been written back yet, oldest + /// first. A record joins before its borrow is written and leaves only when + /// its restore's OK arrives. + @override + List get unrestored => List.unmodifiable(_unrestored); + + /// Asks the repeater [pubkey] for its scopes with [request]: look it up, + /// borrow a zero-hop route when it has another one, send, restore, then + /// release the lease and wait for the tagged answer outside it. + /// + /// The answer wait is [answerWait] (or the radio's estimate plus 1 s when + /// null), at most [kScopeAnswerWaitCap], counted from SENT and never past + /// [notAfter]. [onSent] fires with that wait once the answer tag is armed. + @override + Future requestScopes(Uint8List pubkey, Uint8List request, + {required Duration? answerWait, + required DateTime notAfter, + void Function(Duration wait)? onSent}) async { + ContactRecord? borrowed; + try { + return await _request(pubkey, request, answerWait, notAfter, onSent, + (record) => borrowed = record); + } catch (e) { + debugError('[SCOPES] Scope request failed unexpectedly: $e'); + _end(_LeaseEnd.released); + _host.endListen(); + return ScopeAborted(restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + } + + Future _request( + Uint8List pubkey, + Uint8List request, + Duration? answerWait, + DateTime notAfter, + void Function(Duration wait)? onSent, + void Function(ContactRecord record) noteBorrow) async { + final label = _prefix(pubkey); + if (!_active) return _stopped(_Ended(_endReason!), null); + + // Stage 1: is the repeater a contact, and with which route? + final lookup = await _exchange( + Uint8List.fromList([CommandCodes.getContactByKey, ...pubkey])); + if (lookup is! _Frame) return _stopped(lookup, null); + ContactRecord? contact; + final lf = lookup.frame; + if (lf[0] == ResponseCodes.contact) { + try { + contact = ContactRecord.parse(BufferReader(lf.sublist(1))); + } on FormatException catch (e) { + debugWarn('[SCOPES] Lookup for $label returned a short contact: $e'); + return _localFailure('reply_owed', null); + } + if (!_sameBytes(contact.publicKey, pubkey)) { + debugWarn('[SCOPES] Lookup for $label answered with contact ' + '${_prefix(contact.publicKey)}, not accepted'); + return _localFailure('reply_owed', null); + } + } else if (lf[0] == ResponseCodes.err) { + final code = lf.length > 1 ? lf[1] : 0; + if (code != ErrorCodes.notFound) { + debugWarn('[SCOPES] Lookup for $label refused (error code $code)'); + return _radioError(code, null); + } + debugLog('[SCOPES] $label is not a contact, sending direct'); + } else { + debugWarn('[SCOPES] Lookup for $label answered with code ${lf[0]}'); + return _localFailure('reply_owed', null); + } + + if (contact == null && _host.cannotAskNonContacts) { + debugLog('[SCOPES] $label is not a contact and this connection cannot ' + 'ask non-contacts (contact table full), skipping the send'); + _end(_LeaseEnd.released); + return const ScopeNonContactRefused(); + } + + // Borrow a zero-hop route unless it already has one. + ContactRecord? borrowed; + if (contact != null && !(contact.hasRoute && contact.routeHopCount == 0)) { + if (!_active || _cancel.isCancelled) { + return _stopped(_Ended(_endReason ?? _LeaseEnd.cancelled), null); + } + borrowed = contact; + noteBorrow(contact); + _addUnrestored(contact); + debugLog('[SCOPES] Borrowing a zero-hop route to $label ' + '(out_path_len 0x${contact.outPathLen.toRadixString(16)})'); + final r = await _exchange( + contact.withOutPathLen(0).toFrame(CommandCodes.addUpdateContact)); + if (r is! _Frame) return _stopped(r, borrowed); + if (r.frame[0] != ResponseCodes.ok) { + final isErr = r.frame[0] == ResponseCodes.err; + final code = isErr && r.frame.length > 1 ? r.frame[1] : 0; + debugWarn('[SCOPES] Borrow for $label answered with code ' + '${r.frame[0]}${isErr ? ' (error code $code)' : ''}'); + await _restore(borrowed); + return isErr + ? _radioError(code, borrowed) + : _localFailure('reply_owed', borrowed); + } + } + + // Stage 2: send, and arm the answer tag inside the SENT dispatch. + final answer = _host.armScopeAnswer(); + // The answer can land while the restore is still in flight; keep it so + // an answer that beat its deadline is never thrown away. + ScopeAnswerPush? received; + unawaited(answer.then((a) => received = a, onError: (_) => null)); + int? estTimeoutMs; + bool flood = false; + DateTime? sentAt; + final send = await _exchange( + Uint8List.fromList([CommandCodes.sendAnonReq, ...pubkey, ...request]), + onSync: (f) { + if (f[0] != ResponseCodes.sent || f.length < 10) return; + flood = f[1] != 0; + estTimeoutMs = f[6] | (f[7] << 8) | (f[8] << 16) | (f[9] << 24); + sentAt = clock.now(); + if (!flood) { + _host.setScopeAnswerTag(Uint8List.fromList(f.sublist(2, 6))); + _tagArmed = true; + } + }); + if (send is! _Frame) { + _host.disarmScopeAnswer(); + return _stopped(send, borrowed); + } + final sf = send.frame; + if (sf[0] != ResponseCodes.sent || estTimeoutMs == null) { + _host.disarmScopeAnswer(); + final isErr = sf[0] == ResponseCodes.err; + final code = isErr && sf.length > 1 ? sf[1] : 0; + debugWarn('[SCOPES] Send to $label answered with code ${sf[0]}' + '${isErr ? ' (error code $code)' : ''}'); + if (borrowed != null) await _restore(borrowed); + if (isErr) { + final nonContactTableFull = contact == null && + code == ErrorCodes.tableFull && + await _confirmContactNotAllocated(pubkey, label); + if (nonContactTableFull) _host.markCannotAskNonContacts(); + return _radioError(code, borrowed, + nonContactTableFull: nonContactTableFull); + } + return _localFailure( + sf[0] == ResponseCodes.sent ? 'malformed_sent' : 'reply_owed', + borrowed); + } + if (flood) { + debugLog('[SCOPES] Request to $label was flooded, not waiting'); + _host.disarmScopeAnswer(); + if (borrowed != null) await _restore(borrowed); + _end(_LeaseEnd.released); + return ScopeFlooded(restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + if (!_active && _endReason != _LeaseEnd.holdCap) { + // Cancelled or disconnected in the gap after SENT: no wait. + return ScopeAborted(restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + + var wait = answerWait ?? + Duration(milliseconds: estTimeoutMs!) + kScopeAnswerFallbackMargin; + if (wait > kScopeAnswerWaitCap) wait = kScopeAnswerWaitCap; + if (wait.isNegative) wait = Duration.zero; + onSent?.call(wait); + debugLog( + '[SCOPES] Request to $label sent, waiting ${wait.inMilliseconds}ms ' + '(est ${estTimeoutMs}ms)'); + + // The radio built and queued the packet inside the send command, so the + // borrowed route can go back now, while the lease is still held. + if (borrowed != null) await _restore(borrowed); + + // Stage 3: release the lease, then wait for the answer outside it. + if (_active) { + _end(_LeaseEnd.released, listen: true); + } else if (_endReason != _LeaseEnd.holdCap) { + // Cancelled or disconnected during the restore: no wait. + return ScopeAborted(restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + // A deadline during the restore still hands the slot to the listen. + + var waitEnd = sentAt!.add(wait); + if (notAfter.isBefore(waitEnd)) waitEnd = notAfter; + final early = received; + final Object result; + if (early != null && !early.receivedAt.isAfter(waitEnd)) { + result = early; + } else { + result = await _awaitAnswer(answer, waitEnd.difference(clock.now())); + } + _host.endListen(); + switch (result) { + case ScopeAnswerPush(:final body, :final receivedAt): + debugLog('[SCOPES] Answer from $label (${body.length} bytes)'); + return ScopeAnswered(body, receivedAt, + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + case _LeaseEnd.cancelled || _LeaseEnd.disconnected: + debugLog('[SCOPES] Answer wait for $label ended early'); + return ScopeAborted( + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + default: + debugLog('[SCOPES] No answer from $label'); + return ScopeNoAnswer( + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + } + + /// Waits for the tagged answer, the cancel token, a disconnect or + /// [remaining]. Resolves with the push, or a [_LeaseEnd] (released means + /// the wait ran out). + Future _awaitAnswer( + Future answer, Duration remaining) { + if (_cancel.isCancelled) return Future.value(_LeaseEnd.cancelled); + if (remaining <= Duration.zero) return Future.value(_LeaseEnd.released); + final done = Completer(); + void settle(Object value) { + if (!done.isCompleted) done.complete(value); + } + + final timer = Timer(remaining, () => settle(_LeaseEnd.released)); + answer.then(settle, onError: (_) => settle(_LeaseEnd.disconnected)); + _cancel.whenCancelled.then((_) => settle(_LeaseEnd.cancelled)); + return done.future.whenComplete(timer.cancel); + } + + /// Writes [original] back byte for byte. Resolves true when its OK + /// arrives; otherwise the record stays in [unrestored] for a later lease. + @override + Future restore(ContactRecord original) async { + if (!_active) return false; + _addUnrestored(original); + return _restore(original); + } + + Future _restore(ContactRecord original) async { + final r = await _exchange(original.toFrame(CommandCodes.addUpdateContact)); + final label = _prefix(original.publicKey); + if (r is _Frame && r.frame[0] == ResponseCodes.ok) { + _unrestored + .removeWhere((c) => _sameBytes(c.publicKey, original.publicKey)); + debugLog('[SCOPES] Route to $label restored'); + return true; + } + final why = switch (r) { + _Frame(:final frame) => 'answered with code ${frame[0]}', + _Ended(:final why) => 'lease ended (${why.name})', + _NotWritten(:final why) => 'not written ($why)', + _WriteFailed(:final error) => 'write failed ($error)', + }; + debugWarn('[SCOPES] Restore of $label pending: $why'); + return false; + } + + /// Ends the lease now. Idempotent. A reply still owed stays in the + /// connection's ledger until it arrives or expires. + @override + Future release() async { + _end(_LeaseEnd.released); + } + + /// Connection use only: the link is going away. Settles any waiter with + /// [ScopeAborted] and drops the unrestored records with the connection. + void abortForDisconnect() { + _unrestored.clear(); + _end(_LeaseEnd.disconnected); + } + + // ---- internals ---- + + /// Writes one command and waits for its reply. Never awaits the write + /// itself: the deadline and the cancel token settle the wait without it. + Future<_Reply> _exchange(Uint8List frame, + {void Function(Uint8List frame)? onSync}) { + if (!_active) return Future.value(_Ended(_endReason!)); + if (_cancel.isCancelled) { + _end(_LeaseEnd.cancelled); + return Future.value(const _Ended(_LeaseEnd.cancelled)); + } + if (!_host.repliesSettled) { + return Future.value(const _NotWritten('reply_owed')); + } + if (_deadline.difference(clock.now()) < kScopeLeaseMinCommandTime) { + return Future.value(const _NotWritten('hold_cap')); + } + final pending = Completer<_Reply>(); + _pending = pending; + _host.setLeaseReplyWaiter(this, (reply) { + if (!identical(_pending, pending)) return; + _pending = null; + onSync?.call(reply); + pending.complete(_Frame(reply)); + }); + _host.writeForLease(this, frame).then((_) {}, onError: (Object e) { + if (!identical(_pending, pending)) return; + _pending = null; + _host.setLeaseReplyWaiter(this, null); + debugWarn('[SCOPES] Lease write of command ${frame[0]} failed: $e'); + pending.complete(_WriteFailed(e)); + }); + return pending.future; + } + + void _onDeadline() { + if (!_active) return; + debugWarn('[SCOPES] Lease hit its ${kScopeLeaseHold.inSeconds}s deadline, ' + 'releasing'); + _end(_LeaseEnd.holdCap, listen: _tagArmed); + } + + void _onCancel() { + if (!_active) return; + debugLog('[SCOPES] Lease cancelled, releasing'); + _end(_LeaseEnd.cancelled); + } + + void _end(_LeaseEnd why, {bool listen = false}) { + if (!_active) return; + _active = false; + _endReason = why; + _deadlineTimer?.cancel(); + _deadlineTimer = null; + final pending = _pending; + _pending = null; + _host.endLease(this, listen: listen); + if (pending != null && !pending.isCompleted) pending.complete(_Ended(why)); + } + + /// The outcome for a stage that ended without its reply. Always leaves the + /// lease released. + ScopeRequestOutcome _stopped(_Reply r, ContactRecord? borrowed) { + final ScopeRequestOutcome outcome; + switch (r) { + case _Ended(:final why): + outcome = why == _LeaseEnd.holdCap + ? ScopeLocalFailure('hold_cap', + restoreOwed: _owes(borrowed), borrowedFrom: borrowed) + : ScopeAborted( + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + case _NotWritten(:final why): + outcome = ScopeLocalFailure(why, + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + case _WriteFailed(): + outcome = ScopeLocalFailure('write_failed', + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + case _Frame(): + outcome = ScopeLocalFailure('reply_owed', + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + _end(_LeaseEnd.released); + return outcome; + } + + /// ERR_CODE_TABLE_FULL answers a non-contact's send for two different + /// reasons the firmware does not distinguish: the anon contact could not + /// be allocated (genuinely no free slot), or it WAS allocated and the send + /// itself failed for an unrelated, transient reason (an empty packet + /// pool: `BaseChatMesh::sendAnonReq` returns `MSG_SEND_FAILED` whenever its + /// own packet allocation fails, whatever `recipient` was). One more lookup + /// for the same key tells them apart, since `CMD_GET_CONTACT_BY_KEY` reads + /// the very table `addContact` just inserted into: found means the slot + /// exists, so this was not a table-full failure. True only when that + /// lookup answers ERR_CODE_NOT_FOUND; false when it finds the contact, + /// answers anything else, or there is no time left in the lease to even + /// ask (the lease deadline and reply-ledger rules are [_exchange]'s own). + Future _confirmContactNotAllocated( + Uint8List pubkey, String label) async { + final confirm = await _exchange( + Uint8List.fromList([CommandCodes.getContactByKey, ...pubkey])); + if (confirm is! _Frame) return false; + final cf = confirm.frame; + if (cf[0] == ResponseCodes.contact) { + debugLog('[SCOPES] $label: the anon contact was allocated, so ERR 3 ' + 'was a packet pool failure, not a full table'); + return false; + } + return cf[0] == ResponseCodes.err && + (cf.length > 1 ? cf[1] : 0) == ErrorCodes.notFound; + } + + ScopeRequestOutcome _localFailure(String why, ContactRecord? borrowed) { + _end(_LeaseEnd.released); + return ScopeLocalFailure(why, + restoreOwed: _owes(borrowed), borrowedFrom: borrowed); + } + + ScopeRequestOutcome _radioError(int code, ContactRecord? borrowed, + {bool nonContactTableFull = false}) { + _end(_LeaseEnd.released); + return ScopeRadioError(code, + nonContactTableFull: nonContactTableFull, + restoreOwed: _owes(borrowed), + borrowedFrom: borrowed); + } + + bool _owes(ContactRecord? borrowed) => + borrowed != null && + _unrestored.any((c) => _sameBytes(c.publicKey, borrowed.publicKey)); + + void _addUnrestored(ContactRecord record) { + if (_unrestored.any((c) => _sameBytes(c.publicKey, record.publicKey))) { + return; + } + _unrestored.add(record); + } + + static bool _sameBytes(Uint8List a, Uint8List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + + /// Public keys are logged as an 8-character prefix only. + static String _prefix(Uint8List key) => key + .take(4) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join() + .toUpperCase(); +} diff --git a/lib/services/meshcore/tx_tracker.dart b/lib/services/meshcore/tx_tracker.dart index eff8a38e..6bef3368 100644 --- a/lib/services/meshcore/tx_tracker.dart +++ b/lib/services/meshcore/tx_tracker.dart @@ -254,6 +254,12 @@ class TxTracker { try { final encryptedMessage = metadata.encryptedPayload.sublist(3); + if (!CryptoService.isValidCiphertextLength( + encryptedMessage.length)) { + debugLog('[MESSAGE_CORRELATION] ❌ REJECT: ciphertext length ' + '${encryptedMessage.length} is not a multiple of 16'); + return TxEchoResult.notEcho; + } final decryptedBytes = CryptoService.decryptChannelMessage( encryptedMessage, channelKey!, diff --git a/lib/services/meshcore/unified_rx_handler.dart b/lib/services/meshcore/unified_rx_handler.dart index b5946d21..10080203 100644 --- a/lib/services/meshcore/unified_rx_handler.dart +++ b/lib/services/meshcore/unified_rx_handler.dart @@ -115,6 +115,9 @@ class UnifiedRxHandler { // If neither active, packet is received but ignored // Listener stays on, just not processing for wardriving + } on PacketTooShortException catch (e) { + // Truncated packets are routine on air: skip without an error. + debugLog('[UNIFIED RX] Skipped short packet: ${e.message}'); } catch (error, stackTrace) { debugError('[UNIFIED RX] Error processing rx_log entry: $error'); debugError('[UNIFIED RX] Stack trace: $stackTrace'); diff --git a/lib/services/noise_floor_session_store.dart b/lib/services/noise_floor_session_store.dart new file mode 100644 index 00000000..867166f6 --- /dev/null +++ b/lib/services/noise_floor_session_store.dart @@ -0,0 +1,109 @@ +/// Storage for the History tab's recording sessions ([NoiseFloorSession]). +/// +/// A session used to reach Hive only when its mode ended, so an app killed +/// mid-drive lost the whole entry. The running session is now checkpointed +/// into the same box under its own id ([NoiseFloorCheckpoint]), and a launch +/// closes any checkpoint a kill left open ([loadStoredNoiseFloorSessions]). +/// The ended-session save puts the same id, so a checkpointed session is +/// stored once. +library; + +import 'package:hive/hive.dart'; + +import '../models/noise_floor_session.dart'; +import '../utils/debug_logger_io.dart'; + +/// How many ended sessions History keeps. +const int maxStoredNoiseFloorSessions = 10; + +/// The end of a session that was never ended (the app was killed): its last +/// sample or marker, whichever is later, or its start when it recorded +/// nothing. +DateTime interruptedNoiseFloorSessionEnd(NoiseFloorSession session) { + var end = session.startTime; + if (session.samples.isNotEmpty && + session.samples.last.timestamp.isAfter(end)) { + end = session.samples.last.timestamp; + } + for (final marker in session.markers) { + if (marker.timestamp.isAfter(end)) end = marker.timestamp; + } + return end; +} + +/// Reads the stored sessions at launch, newest first. A checkpoint left open +/// by a kill is closed at [interruptedNoiseFloorSessionEnd] and written back, +/// then the list is cut to [keep], deleting the oldest from [box]. +Future> loadStoredNoiseFloorSessions( + Box box, { + int keep = maxStoredNoiseFloorSessions, +}) async { + final sessions = box.values.toList(); + for (final session in sessions) { + if (!session.isActive) continue; + session.endTime = interruptedNoiseFloorSessionEnd(session); + await box.put(session.id, session); + debugLog('[GRAPH] Closed a session the app did not end: ' + '${session.durationDisplay}, ${session.samples.length} samples, ' + '${session.markers.length} markers'); + } + sessions.sort((a, b) => b.startTime.compareTo(a.startTime)); + while (sessions.length > keep) { + final oldest = sessions.removeLast(); + await box.delete(oldest.id); + debugLog('[GRAPH] Deleted oldest session: ${oldest.id}'); + } + return sessions; +} + +/// Saves an ended [session] and adds it to the front of [stored], keeping +/// [keep] sessions. A checkpoint of it already in [box] is overwritten (same +/// id), and an entry of it already in [stored] is replaced, never doubled. +Future saveEndedNoiseFloorSession( + Box? box, + List stored, + NoiseFloorSession session, { + int keep = maxStoredNoiseFloorSessions, +}) async { + await box?.put(session.id, session); + stored.removeWhere((s) => s.id == session.id); + stored.insert(0, session); + while (stored.length > keep) { + final oldest = stored.removeLast(); + await box?.delete(oldest.id); + debugLog('[GRAPH] Deleted oldest session: ${oldest.id}'); + } +} + +/// Writes the running session to Hive so a kill cannot lose it. +/// +/// Each write rewrites the whole session (a 5 hour drive is about 3600 +/// samples), so the caller writes on a timer of a few minutes and when the +/// app leaves the screen, never per sample, and a write with nothing new +/// since the last one is skipped. +class NoiseFloorCheckpoint { + String? _id; + int _samples = -1; + int _markers = -1; + + /// Writes [session] when it is still running and has something new since + /// the last write. True when it wrote. + Future write( + Box? box, NoiseFloorSession session) async { + if (box == null || !session.isActive) return false; + if (_id == session.id && + _samples == session.samples.length && + _markers == session.markers.length) { + return false; + } + final id = session.id; + final samples = session.samples.length; + final markers = session.markers.length; + await box.put(id, session); + // Noted only once written, so a failed write is tried again. + _id = id; + _samples = samples; + _markers = markers; + return true; + } +} diff --git a/lib/services/offline_session_export.dart b/lib/services/offline_session_export.dart new file mode 100644 index 00000000..ecaa61af --- /dev/null +++ b/lib/services/offline_session_export.dart @@ -0,0 +1,53 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart' show compute; + +import 'offline_session_service.dart'; + +/// The JSON an exported offline session file holds: the session's data +/// payload, pretty-printed with two-space indent. Every export path (the +/// single-session share, the web download and Export all) writes this, so the +/// files are the same whichever button made them. +String offlineSessionJson(Map data) => + const JsonEncoder.withIndent(' ').convert(data); + +/// Writes one export file per session into [dir] and returns them in the +/// order of [sessions]. +/// +/// Each file is named after its session (`2026-11-09.json`), the same name +/// the single-session export uses. A name already taken earlier in this export +/// gets ` (2)`, ` (3)` and so on before `.json`, so no session overwrites +/// another (the service can reuse a name after a delete). +/// +/// Only reads the sessions: nothing is deleted, changed or marked uploaded. +/// Encoding runs off the UI isolate ([compute]) so a large drive does not +/// stall the screen. +Future> writeOfflineSessionExports( + List sessions, + Directory dir, +) async { + final files = []; + final used = {}; + for (final session in sessions) { + final name = _uniqueName(session.filename, used); + used.add(name); + final json = await compute(offlineSessionJson, session.data); + final file = File('${dir.path}/$name'); + await file.writeAsString(json); + files.add(file); + } + return files; +} + +String _uniqueName(String filename, Set used) { + if (!used.contains(filename)) return filename; + final dot = filename.lastIndexOf('.'); + final stem = dot > 0 ? filename.substring(0, dot) : filename; + final ext = dot > 0 ? filename.substring(dot) : ''; + var n = 2; + while (used.contains('$stem ($n)$ext')) { + n++; + } + return '$stem ($n)$ext'; +} diff --git a/lib/services/offline_session_service.dart b/lib/services/offline_session_service.dart index db4c0789..186313ce 100644 --- a/lib/services/offline_session_service.dart +++ b/lib/services/offline_session_service.dart @@ -399,6 +399,33 @@ class OfflineSessionService { return remaining.length; } + /// Replace a session's whole ping list (not just a leading prefix) and + /// persist immediately. Used to strip rows the upload auth cannot accept + /// before any chunk is built, so the partial-upload cleanup that follows + /// (which removes a prefix by uploaded count) counts against the rows + /// that are actually sent. + Future replacePings( + String filename, List> pings) async { + final index = _sessions.indexWhere((s) => s.filename == filename); + if (index == -1) { + debugWarn('[OFFLINE] Session not found for ping replacement: $filename'); + return; + } + + final session = _sessions[index]; + final updatedData = Map.from(session.data); + updatedData['pings'] = pings; + updatedData['ping_count'] = pings.length; + + _sessions[index] = session.copyWith( + data: updatedData, + pingCount: pings.length, + ); + await _saveSessions(); + debugLog( + '[OFFLINE] Replaced pings for $filename: ${pings.length} remain'); + } + /// Get a session by filename OfflineSession? getSession(String filename) { try { diff --git a/lib/services/permission_disclosure_service.dart b/lib/services/permission_disclosure_service.dart index c6ca111a..3da4e0ee 100644 --- a/lib/services/permission_disclosure_service.dart +++ b/lib/services/permission_disclosure_service.dart @@ -1,27 +1,69 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; + +import 'location_consent.dart'; /// Service to handle Google Play prominent disclosure requirements /// Shows a disclosure dialog before requesting sensitive permissions class PermissionDisclosureService { - static const String _disclosureShownKey = 'location_disclosure_shown'; + /// A permission request that comes back denied faster than this was + /// answered by the OS, not by a person. After two refusals Android stops + /// showing the system dialog and (on some builds) still reports plain + /// `denied` rather than `permanentlyDenied`, so a fast denial is the only + /// sign that no dialog was shown and the app settings are the way forward. + static const Duration silentDenialThreshold = Duration(milliseconds: 500); - /// Check if the disclosure has been shown before - static Future hasShownDisclosure() async { - final prefs = await SharedPreferences.getInstance(); - return prefs.getBool(_disclosureShownKey) ?? false; - } + /// True when a request that came back still denied after [elapsed] was + /// answered without the system dialog ever being shown. + static bool deniedWithoutDialog(Duration elapsed) => + elapsed < silentDenialThreshold; - /// Mark the disclosure as shown - static Future markDisclosureShown() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.setBool(_disclosureShownKey, true); - } + /// The lead follows Google Play's wording for a location disclosure: the + /// word "location" and every feature that uses it, plus when each one runs. + /// Background use only happens while a radio is connected, so it says that + /// instead of "even when the app is closed or not in use". + static const String locationDisclosureLead = + 'MeshMapper collects and uses location data while the app is open, to ' + 'show you on the map and check which region you are in. While it is ' + 'connected to your radio, it also uses location to keep the radio ' + 'signed in and, while a wardriving mode runs, to tag your pings and map ' + 'coverage, including with the screen off or another app open. When you ' + 'disconnect and leave the app, MeshMapper stops using your location.'; + + /// The iOS "Always" dialog's lead. + static const String backgroundDisclosureLead = + 'MeshMapper collects location data in the background only while your ' + 'radio is connected, to keep tagging pings and mapping coverage during ' + 'a wardriving mode. When you disconnect, it stops.'; + + /// Android only: the foreground service's notification is the visible sign + /// that location is in use with the app out of sight. + static const String androidNotificationPoint = + 'A notification shows while your radio is connected.'; + + /// Where location leaves the phone, shown in both dialogs. + static const List sharingPoints = [ + 'While a mode is running, your pings are uploaded with their locations ' + 'to meshmapper.net and shown on public coverage maps.', + 'If you turn on Broadcast My Coordinates, your pings also carry your ' + 'location over the mesh radio.', + 'If you set up a Custom API Endpoint, your uploaded pings are also sent ' + 'there.', + 'Debug logs you choose to send include your recent locations.', + ]; + + /// The region check (`/status`), the connect `/auth` and the heartbeat: + /// the server checks the fix and stores only the region. + static const String noModePoint = + 'With no mode running, your location is only sent to meshmapper.net to ' + 'check your region and keep a connected radio signed in. The location ' + 'itself is not saved.'; - /// Show the prominent disclosure dialog - /// Always proceeds to system permission prompt after user taps Continue - static Future showLocationDisclosure(BuildContext context) async { - await showDialog( + /// Show the prominent disclosure. Google Play wants it before the app first + /// reads location and right before every system location prompt; callers + /// go on only when this returns true (Agree), which is also remembered. + static Future showLocationDisclosure(BuildContext context) async { + final result = await showDialog( context: context, barrierDismissible: false, builder: (context) => AlertDialog( @@ -30,52 +72,43 @@ class PermissionDisclosureService { Icon(Icons.location_on, color: Colors.blue), SizedBox(width: 12), Expanded( - child: Text('Location Access Required'), + child: Text('Location Data'), ), ], ), - content: const SingleChildScrollView( + content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - 'MeshMapper collects your location to:', - style: TextStyle(fontWeight: FontWeight.w600), - ), - SizedBox(height: 12), - _BulletPoint( - text: 'Track where you send pings on the mesh network'), - _BulletPoint(text: 'Map coverage areas for the community'), - _BulletPoint(text: 'Record which repeaters hear your device'), - SizedBox(height: 16), - Text( - 'Data Sharing', + const Text( + locationDisclosureLead, style: TextStyle(fontWeight: FontWeight.w600), ), - SizedBox(height: 8), - Text( - 'Your location data is uploaded to the MeshMapper API and displayed on public coverage maps at meshmapper.net to help the mesh radio community.', - style: TextStyle(fontSize: 14), - ), - SizedBox(height: 16), - Text( - 'You can use offline mode to store data locally without uploading.', + const SizedBox(height: 16), + const _SharingHeading(), + _BulletPoint(text: sharingPoints.first), + const _BulletPoint(text: noModePoint), + for (final point in sharingPoints.skip(1)) + _BulletPoint(text: point), + if (defaultTargetPlatform == TargetPlatform.android) + const _BulletPoint(text: androidNotificationPoint), + const SizedBox(height: 16), + const Text( + 'Offline Mode keeps your pings on this phone until you choose ' + 'to upload them.', style: TextStyle(fontSize: 13, fontStyle: FontStyle.italic), ), ], ), ), - actions: [ - FilledButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('Continue'), - ), - ], + actions: _agreeActions(context), ), ); - await markDisclosureShown(); + final agreed = result ?? false; + if (agreed) await LocationConsent.markAgreed(); + return agreed; } /// Show the background location disclosure (for "Always" permission) @@ -95,45 +128,59 @@ class PermissionDisclosureService { ), ], ), - content: const SingleChildScrollView( + content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - 'MeshMapper needs background location access to:', + const Text( + backgroundDisclosureLead, style: TextStyle(fontWeight: FontWeight.w600), ), - SizedBox(height: 12), - _BulletPoint( - text: - 'Continue tracking coverage while the app is minimized'), - _BulletPoint( - text: - 'Send automatic pings during extended wardriving sessions'), - SizedBox(height: 16), - Text( - 'This grants "always on" location access, but we only collect what\'s needed: tagging pings while wardriving and checking if you\'re in a supported zone.', + const SizedBox(height: 16), + const _SharingHeading(), + for (final point in sharingPoints) _BulletPoint(text: point), + const SizedBox(height: 12), + const Text( + 'This allows location access all the time. You can turn it ' + 'off in your device\'s Settings.', style: TextStyle(fontSize: 14), ), ], ), ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(false), - child: const Text('Not Now'), - ), - FilledButton( - onPressed: () => Navigator.of(context).pop(true), - child: const Text('Enable'), - ), - ], + actions: _agreeActions(context), ), ); return result ?? false; } + + static List _agreeActions(BuildContext context) => [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Not Now'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Agree'), + ), + ]; +} + +class _SharingHeading extends StatelessWidget { + const _SharingHeading(); + + @override + Widget build(BuildContext context) { + return const Padding( + padding: EdgeInsets.only(bottom: 8), + child: Text( + 'How your location is used and shared', + style: TextStyle(fontWeight: FontWeight.w600), + ), + ); + } } /// Helper widget for bullet points in disclosure dialog diff --git a/lib/services/ping_service.dart b/lib/services/ping_service.dart index 928006eb..ee10c232 100644 --- a/lib/services/ping_service.dart +++ b/lib/services/ping_service.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:typed_data'; +import 'package:clock/clock.dart'; +import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:geolocator/geolocator.dart'; import '../models/connection_state.dart'; @@ -13,11 +15,14 @@ import 'countdown_timer_service.dart'; import 'gps_service.dart'; import 'meshcore/connection.dart'; import 'meshcore/disc_tracker.dart'; +import 'meshcore/protocol_constants.dart' show DiscoveryConstants; +import 'meshcore/scope_lease.dart' show ScopeCancelToken; import 'meshcore/trace_tracker.dart'; import 'meshcore/tx_tracker.dart'; import 'meshcore/wire_tag_codec.dart'; import 'meshcore/unified_rx_handler.dart'; import 'recent_coverage_service.dart'; +import 'scope_discovery/scope_runner.dart'; import 'wakelock_service.dart'; /// Ping service for TX/RX ping orchestration @@ -116,6 +121,16 @@ class PingService { bool _pingInProgress = false; bool _sessionRecoveryInProgress = false; + /// Set when an auto TX (an Active tick or Hybrid's TX leg) bowed out at + /// the recovery hold. The bow-out re-arms the lane at a full interval so + /// it cannot die; when the hold releases, that leg is pulled in to + /// [heldTxReleaseDelay] instead, so a TX due during a session swap goes + /// out about a second after it rather than an interval later. + bool _txHeldByRecovery = false; + + /// How long after the recovery hold releases a TX it held goes out. + static const Duration heldTxReleaseDelay = Duration(seconds: 1); + /// Which auto session a send belongs to. Bumped by [forceDisableAutoPing], /// the one stop that clears [_pingInProgress] out from under a send that is /// still suspended on its fresh fix. Each lane captures it before that fetch @@ -126,6 +141,12 @@ class PingService { /// only re-read the mode then went out alongside the new session's own. int _sendEpoch = 0; + /// Set by [dispose]. The provider disposes this service on a radio drop + /// without a force disable first, so every scheduler and timer callback + /// checks it: a send still parked on its fresh fix or BLE write must not + /// re-arm a lane on a service nobody owns any more. + bool _disposed = false; + // Auto-ping mode bool _autoPingEnabled = false; bool _passiveModeEnabled = false; @@ -166,7 +187,11 @@ class PingService { /// /// Smart Pinging holds a ping back rather than dropping it. Only one is ever /// held: a later deferral overwrites an earlier one, so what goes out is - /// whatever was most recently due. + /// whatever was most recently due. The one exception is Hybrid, where a + /// held TX ping is never replaced by a discovery: a deferred discovery + /// leaves it held, and a discovery leg that finds the square not covered + /// sends the held TX in its place. A held discovery still goes out if a + /// fresh square comes before any TX ping is deferred. BankedPingType? _bankedPing; // Discovery tracking @@ -178,6 +203,20 @@ class PingService { Position? _lastDiscoveryPosition; // Track last discovery position for 25m check + /// The earliest the next discovery can go out, recorded whenever a timer + /// that leads to one is armed. A conservative bound for the scope runner's + /// hard stop only: it never changes when any timer fires. + DateTime? _earliestNextDiscoveryAt; + + /// The live scope runner, if a sweep's runner is still working. + ScopeRunner? _currentScopeRunner; + + /// Builds the scope runner for one discovery sweep, or returns null when + /// scope discovery is not active. Set by the provider. + ScopeRunner? Function( + {required DateTime hardStop, + required ScopeCancelToken cancel})? scopeRunnerFactory; + // Validation callbacks bool Function()? checkExternalAntennaConfigured; bool Function()? checkPowerLevelConfigured; @@ -188,11 +227,18 @@ class PingService { /// Callback to get the power level in watts (0.3, 0.6, 1.0, 2.0) from user preferences double Function()? getPowerLevel; - /// Smart Pinging: whether the cell under a fix already has recent coverage. - /// Consulted by the auto TX validator and the auto discovery path only. - /// Null (or [RecentCoverage.unknown]) never blocks. Wired by the provider - /// to [RecentCoverageService.isCovered]. - RecentCoverage Function(double lat, double lon)? checkRecentCoverage; + /// Smart Pinging: whether the cell under a fix already has recent coverage + /// for this kind of ping. Consulted by the auto TX validator and the auto + /// discovery path only. Null (or [RecentCoverage.unknown]) never blocks. + /// Wired by the provider to [RecentCoverageService.isCovered], asked per + /// kind: a TX asks with forTx true, a discovery with forTx false. + RecentCoverage Function(double lat, double lon, BankedPingType kind)? + checkRecentCoverage; + + /// Whether Smart Pinging is on with a known zone. Diagnostics only: an + /// inactive lookup answers [RecentCoverage.clear], so the send log needs + /// this to say why a ping went out. + bool Function()? isRecentCoverageActive; /// Fired once each time smart pinging holds a ping, with the fix that was /// validated and which kind of ping was held. The provider dedupes it on @@ -236,6 +282,11 @@ class PingService { /// Fires immediately when disc ping is created (like onTxPing) void Function(DiscLogEntry)? onDiscPing; + /// The entry [onDiscPing] published was never sent: the discovery write + /// failed. The listener withdraws it, so a request that never went on the + /// air is not drawn as a failed discovery. Nothing was queued for upload. + void Function(DiscLogEntry)? onDiscPingAborted; + /// Called in real-time when each node is discovered during tracking window /// Parameters: (DiscLogEntry discPing, DiscoveredNodeEntry nodeEntry, bool isNew) void Function(DiscLogEntry, DiscoveredNodeEntry, bool isNew)? @@ -328,11 +379,41 @@ class PingService { /// Get current auto-ping interval in milliseconds int get autoPingIntervalMs => _autoPingIntervalMs; + /// The earliest the next discovery can go out (see the field). + @visibleForTesting + DateTime? get earliestNextDiscoveryAt => _earliestNextDiscoveryAt; + + /// True while a sweep's scope runner is still working. + bool get isScopeRunnerActive => _currentScopeRunner != null; + + /// Stops the live scope runner at once: nothing more goes on the air for + /// it and its badge clears. Called by every stop path, and by the + /// provider for the paths that end a session without passing through + /// here (Offline Mode switch, zone transfer, disconnect). + void cancelScopeRunner(String reason) { + final runner = _currentScopeRunner; + if (runner == null) return; + // Cancel while it is still current, so its badge clears. + runner.cancel(reason); + _currentScopeRunner = null; + } + /// Hold new TX attempts while a replacement API session is being installed. /// Any TX already on air drains through its normal listening window first. void setSessionRecoveryInProgress(bool value) { _sessionRecoveryInProgress = value; debugLog('[SESSION] TX ${value ? 'held for session recovery' : 'released after session recovery'}'); + if (value) return; + final held = _txHeldByRecovery; + _txHeldByRecovery = false; + if (!held) return; + // A ping in flight will schedule its own next; the bow-out's full + // interval stays as the backstop for anything else. + if (!_autoPingEnabled || _passiveModeEnabled || _pingInProgress) return; + debugLog('[SESSION] Re-arming the TX held by the recovery in ' + '${heldTxReleaseDelay.inSeconds}s'); + _rescheduleAutoLane( + delayMs: heldTxReleaseDelay.inMilliseconds, heldTxLeg: true); } /// Wait until a transmitted TX has been queued with its original wire tag. @@ -398,7 +479,8 @@ class PingService { // here and the interval tick already fails open; 'clear' is also the // answer once Smart Pinging is off, which is why the provider drops the // bank when the lookup goes inactive. - if (checkRecentCoverage?.call(position.latitude, position.longitude) != + if (checkRecentCoverage?.call( + position.latitude, position.longitude, banked) != RecentCoverage.clear) { return false; } @@ -544,7 +626,8 @@ class PingService { // reads as held, not rate limited, and both Hybrid legs then agree. Banking // a too close ping is safe, since the release re-checks the 25 m rule // before it ever goes out. Only here (auto): manual pings always send. - if (checkRecentCoverage?.call(position.latitude, position.longitude) == + if (checkRecentCoverage?.call( + position.latitude, position.longitude, BankedPingType.tx) == RecentCoverage.covered) { return PingValidation.recentlyCovered; } @@ -557,7 +640,7 @@ class PingService { // Check cooldown (5 seconds between pings) final lastTx = _lastTxTime; if (lastTx != null) { - final elapsed = DateTime.now().difference(lastTx); + final elapsed = clock.now().difference(lastTx); if (elapsed < _autoPingCooldown) { return PingValidation.cooldownActive; } @@ -678,7 +761,7 @@ class PingService { // Check cooldown (5 seconds between pings) final lastTx = _lastTxTime; if (lastTx != null) { - final elapsed = DateTime.now().difference(lastTx); + final elapsed = clock.now().difference(lastTx); if (elapsed < _autoPingCooldown) { return PingValidation.cooldownActive; } @@ -692,7 +775,7 @@ class PingService { bool isInCooldown() { final lastTx = _lastTxTime; if (lastTx == null) return false; - final elapsed = DateTime.now().difference(lastTx); + final elapsed = clock.now().difference(lastTx); return elapsed < _autoPingCooldown; } @@ -700,7 +783,7 @@ class PingService { int getRemainingCooldownSeconds() { final lastTx = _lastTxTime; if (lastTx == null) return 0; - final elapsed = DateTime.now().difference(lastTx); + final elapsed = clock.now().difference(lastTx); final remaining = _autoPingCooldown - elapsed; return remaining.inSeconds.clamp(0, _autoPingCooldown.inSeconds); } @@ -769,7 +852,10 @@ class PingService { // provider only releases the gate in a finally, so a tick that lands // during recovery would end the lane for the rest of the session with // the mode flags still reading enabled. Manual pings arm nothing. - if (!manual) _rescheduleAutoLane(); + if (!manual) { + _txHeldByRecovery = true; + _rescheduleAutoLane(); + } return false; } @@ -805,6 +891,7 @@ class PingService { // while this is still true latches as pending with no window to // drain it. This lane is auto-only, so no manual check is needed. _pingInProgress = false; + _txHeldByRecovery = true; _rescheduleAutoLane(); return false; } @@ -920,6 +1007,10 @@ class PingService { _pingInProgress = false; return false; } + if (!manual) { + debugLog('[PING] Auto TX passed validation, smart ping: ' + '${_smartPingVerdict(position, BankedPingType.tx)}'); + } final txPowerDbm = _connection.deviceModel?.txPower ?? 22; // Build the on-air body ONCE (same string is used for TxTracker echo @@ -968,123 +1059,136 @@ class PingService { // Capture noise floor at ping time final noiseFloor = _connection.lastNoiseFloor; - // Create TX ping record FIRST so it's available for echo callbacks - final txPing = TxPing( - latitude: position.latitude, - longitude: position.longitude, - power: txPowerDbm, - timestamp: DateTime.now(), - deviceId: _deviceId, - heardRepeaters: [], // Will be populated dynamically as echoes arrive - ); + // Everything below runs in [goingOut], which the connection calls once + // the frame is past every write gate (a sign, a scope lease) and just + // before the transport write. A TX parked behind a lease for up to 4 s + // therefore neither spends its echo window waiting nor records a send + // time from before it went out, and tracking is still armed before the + // radio can hear an echo. + void goingOut() { + // A force teardown while the frame waited at a gate: the send still + // goes out, but it belongs to no session any more, and the shared + // tracker may already be following a newer session's ping. + if (epoch != _sendEpoch) return; + + // Create TX ping record FIRST so it's available for echo callbacks + final txPing = TxPing( + latitude: position.latitude, + longitude: position.longitude, + power: txPowerDbm, + timestamp: clock.now(), + deviceId: _deviceId, + heardRepeaters: [], // Will be populated dynamically as echoes arrive + ); - // Store reference for updating with heard repeaters - _lastTxPing = txPing; - debugLog('[PING] Created TxPing, ready for echo tracking'); - - // Notify immediately so TxLogEntry exists BEFORE echoes arrive - // This fixes timing issue where echoes arrived before onTxPing was called - onTxPing?.call(txPing); - - // Start TX echo tracking BEFORE sending ping (matches web client flow) - // Reference: startTxTracking() called before sendChannelTextMessage() in wardrive.js - final channelIndex = _connection.wardrivingChannelIndex; - final channelHash = _connection.wardrivingChannelHash; - final channelKey = _connection.wardrivingChannelKey; - - if (_txTracker != null && - channelIndex != null && - channelHash != null && - channelKey != null) { - debugLog('[PING] Starting TX echo tracking for: "$pingMessage"'); - - // Wire up real-time echo callback before starting tracking - final txTracker = _txTracker; - txTracker.onEchoReceived = (repeaterId, snr, rssi, isNew) { - debugLog( - '[PING] onEchoReceived callback fired: $repeaterId, SNR=$snr, RSSI=$rssi, isNew=$isNew'); - final txPing = _lastTxPing; - if (txPing != null) { - final repeater = HeardRepeater( - repeaterId: repeaterId, - snr: snr, - rssi: rssi, - seenCount: txTracker.repeaters[repeaterId]?.seenCount ?? 1, - ); + // Store reference for updating with heard repeaters + _lastTxPing = txPing; + debugLog('[PING] Created TxPing, ready for echo tracking'); + + // Notify immediately so TxLogEntry exists BEFORE echoes arrive + // This fixes timing issue where echoes arrived before onTxPing was called + onTxPing?.call(txPing); + + // Start TX echo tracking BEFORE sending ping (matches web client flow) + // Reference: startTxTracking() called before sendChannelTextMessage() in wardrive.js + final channelIndex = _connection.wardrivingChannelIndex; + final channelHash = _connection.wardrivingChannelHash; + final channelKey = _connection.wardrivingChannelKey; + + if (_txTracker != null && + channelIndex != null && + channelHash != null && + channelKey != null) { + debugLog('[PING] Starting TX echo tracking for: "$pingMessage"'); + + // Wire up real-time echo callback before starting tracking + final txTracker = _txTracker; + txTracker.onEchoReceived = (repeaterId, snr, rssi, isNew) { + debugLog( + '[PING] onEchoReceived callback fired: $repeaterId, SNR=$snr, RSSI=$rssi, isNew=$isNew'); + final txPing = _lastTxPing; + if (txPing != null) { + final repeater = HeardRepeater( + repeaterId: repeaterId, + snr: snr, + rssi: rssi, + seenCount: txTracker.repeaters[repeaterId]?.seenCount ?? 1, + ); + + if (isNew) { + // Add new repeater to the list + txPing.heardRepeaters.add(repeater); + debugLog( + '[PING] Real-time: Added new repeater $repeaterId (SNR: $snr) - total: ${txPing.heardRepeaters.length}'); + } else { + // Update existing repeater's SNR if better + final idx = txPing.heardRepeaters + .indexWhere((r) => r.repeaterId == repeaterId); + if (idx >= 0) { + txPing.heardRepeaters[idx] = repeater; + debugLog( + '[PING] Real-time: Updated repeater $repeaterId (SNR: $snr)'); + } + } - if (isNew) { - // Add new repeater to the list - txPing.heardRepeaters.add(repeater); + // Notify for real-time UI updates debugLog( - '[PING] Real-time: Added new repeater $repeaterId (SNR: $snr) - total: ${txPing.heardRepeaters.length}'); + '[PING] Calling onEchoReceived callback (callback=${onEchoReceived != null ? "SET" : "NULL"})'); + onEchoReceived?.call(txPing, repeater, isNew); + debugLog('[PING] onEchoReceived callback completed'); } else { - // Update existing repeater's SNR if better - final idx = txPing.heardRepeaters - .indexWhere((r) => r.repeaterId == repeaterId); - if (idx >= 0) { - txPing.heardRepeaters[idx] = repeater; - debugLog( - '[PING] Real-time: Updated repeater $repeaterId (SNR: $snr)'); - } + debugWarn('[PING] onEchoReceived: _lastTxPing is null!'); } + }; - // Notify for real-time UI updates + txTracker.onMultiHopEchoReceived = + (repeaterId, snr, rssi, pathHops, isNew) { debugLog( - '[PING] Calling onEchoReceived callback (callback=${onEchoReceived != null ? "SET" : "NULL"})'); - onEchoReceived?.call(txPing, repeater, isNew); - debugLog('[PING] onEchoReceived callback completed'); - } else { - debugWarn('[PING] onEchoReceived: _lastTxPing is null!'); - } - }; - - txTracker.onMultiHopEchoReceived = - (repeaterId, snr, rssi, pathHops, isNew) { - debugLog( - '[PING] Multi-hop echo: $repeaterId, SNR=$snr, hops=${pathHops.length}, isNew=$isNew'); - final txPing = _lastTxPing; - if (txPing != null) { - final repeater = HeardRepeater( - repeaterId: repeaterId, - snr: snr, - rssi: rssi, - seenCount: - txTracker.multiHopRepeaters[repeaterId]?.seenCount ?? 1, - pathHops: pathHops, - ); - - if (isNew) { - txPing.heardRepeaters.add(repeater); - } else { - final idx = txPing.heardRepeaters.indexWhere( - (r) => r.repeaterId == repeaterId && r.pathHops != null); - if (idx >= 0) { - txPing.heardRepeaters[idx] = repeater; + '[PING] Multi-hop echo: $repeaterId, SNR=$snr, hops=${pathHops.length}, isNew=$isNew'); + final txPing = _lastTxPing; + if (txPing != null) { + final repeater = HeardRepeater( + repeaterId: repeaterId, + snr: snr, + rssi: rssi, + seenCount: + txTracker.multiHopRepeaters[repeaterId]?.seenCount ?? 1, + pathHops: pathHops, + ); + + if (isNew) { + txPing.heardRepeaters.add(repeater); + } else { + final idx = txPing.heardRepeaters.indexWhere( + (r) => r.repeaterId == repeaterId && r.pathHops != null); + if (idx >= 0) { + txPing.heardRepeaters[idx] = repeater; + } } - } - onMultiHopEchoReceived?.call( - txPing, repeaterId, snr, rssi, pathHops, isNew); - } - }; + onMultiHopEchoReceived?.call( + txPing, repeaterId, snr, rssi, pathHops, isNew); + } + }; + + txTracker.startTracking( + payload: pingMessage, + channelIdx: channelIndex, + channelHash: channelHash, + channelKey: channelKey, + windowDuration: _rxListeningWindow, + ); + } else { + debugWarn( + '[PING] TX tracking not available - channel info missing or no tracker'); + } - txTracker.startTracking( - payload: pingMessage, - channelIdx: channelIndex, - channelHash: channelHash, - channelKey: channelKey, - windowDuration: _rxListeningWindow, - ); - } else { - debugWarn( - '[PING] TX tracking not available - channel info missing or no tracker'); + // Play transmit sound immediately before sending + _audioService?.playTransmitSound(); } - // Play transmit sound immediately before sending - _audioService?.playTransmitSound(); - - // Send ping via BLE (pre-composed body — wire tag or legacy coords) - await _connection.sendPing(pingMessage); + // Send ping via BLE (pre-composed body, wire tag or legacy coords) + await _connection.sendPing(pingMessage, onWire: goingOut); // A force teardown can land while BLE is awaiting its sent confirmation. // The radio may have accepted the packet, but this stale send must not @@ -1100,7 +1204,7 @@ class PingService { } // Mark ping time and position - _lastTxTime = DateTime.now(); + _lastTxTime = clock.now(); _gpsService.markPingPosition(position); // Start appropriate cooldown timer @@ -1227,6 +1331,7 @@ class PingService { // Queue TX entry with heard_repeats AFTER RX window ends final txTimestamp = _pendingTxTimestamp; if (txTimestamp != null) { + final fixAltitude = _gpsService.fixAltitudeOf(txPosition); _txWindowFinalizing = true; try { try { @@ -1240,7 +1345,9 @@ class PingService { power: getPowerLevel?.call(), pingCounter: _pendingTxPingCounter, wireTag: _pendingTxWireTag, - altitude: GpsService.altitudeOrNull(txPosition), + altitude: fixAltitude.meters, + altitudeRef: fixAltitude.wireReference, + altitudeAccuracy: fixAltitude.accuracy, ); debugLog('[PING] Queued TX entry with heard_repeats: $heardRepeats'); } catch (e) { @@ -1264,7 +1371,9 @@ class PingService { externalAntenna: getExternalAntenna?.call() ?? false, noiseFloor: _pendingTxNoiseFloor, power: getPowerLevel?.call(), - altitude: GpsService.altitudeOrNull(txPosition), + altitude: fixAltitude.meters, + altitudeRef: fixAltitude.wireReference, + altitudeAccuracy: fixAltitude.accuracy, ); } debugLog( @@ -1318,19 +1427,37 @@ class PingService { /// early with nothing armed ends the lane for the rest of the session while /// the mode flags still read enabled. Hybrid or Active is chosen exactly as /// the validation skip path chooses it. - void _rescheduleAutoLane() { + /// + /// [delayMs] replaces the interval (the held-TX re-arm). [heldTxLeg] names + /// the leg: in Hybrid the TX leg that bowed out is the one that runs, so + /// the alternation is unchanged. The flag is forced because the two + /// bow-out sites disagree on it: at the gate before the send it still + /// reads TX, while after the fresh fix the timer callback has already + /// flipped it to discovery when it dispatched the TX. + void _rescheduleAutoLane({int? delayMs, bool heldTxLeg = false}) { if (!_autoPingEnabled || _passiveModeEnabled) return; if (_hybridModeEnabled) { - _scheduleNextHybridPing(); + if (heldTxLeg) _nextPingIsDiscovery = false; + _scheduleNextHybridPing(delayMs: delayMs); } else { - _scheduleNextAutoPing(); + _scheduleNextAutoPing(delayMs: delayMs); } } + /// Why Smart Pinging let a send through, for the send log: 'inactive' + /// (off, or no zone), 'unknown' (no tile loaded here, fails open), 'clear' + /// or 'no lookup' (not wired). + String _smartPingVerdict(Position position, BankedPingType kind) { + final check = checkRecentCoverage; + if (check == null) return 'no lookup'; + if (isRecentCoverageActive?.call() == false) return 'inactive'; + return check(position.latitude, position.longitude, kind).name; + } + /// Schedule next auto ping after interval /// Reference: scheduleNextAutoPing() in wardrive.js - void _scheduleNextAutoPing() { - if (!_autoPingEnabled || _passiveModeEnabled) { + void _scheduleNextAutoPing({int? delayMs}) { + if (_disposed || !_autoPingEnabled || _passiveModeEnabled) { debugLog( '[ACTIVE MODE] Not scheduling next auto ping - auto mode not running or Passive Mode'); return; @@ -1341,12 +1468,12 @@ class PingService { _autoTimer?.cancel(); _autoTimer = null; - debugLog( - '[ACTIVE MODE] Scheduling next auto ping in ${_autoPingIntervalMs}ms'); + final waitMs = delayMs ?? _autoPingIntervalMs; + debugLog('[ACTIVE MODE] Scheduling next auto ping in ${waitMs}ms'); // Start countdown display (with skip reason if applicable) // The AutoPingTimer in countdown_timer_service.dart handles the display - onAutoPingScheduled?.call(_autoPingIntervalMs, _skipReason); + onAutoPingScheduled?.call(waitMs, _skipReason); // That callback runs synchronously and can stop auto mode (the idle // auto-stop hangs off it), which cancels _autoTimer. Re-check so we don't @@ -1358,7 +1485,8 @@ class PingService { } // Schedule the next ping - _autoTimer = Timer(Duration(milliseconds: _autoPingIntervalMs), () { + _autoTimer = Timer(Duration(milliseconds: waitMs), () { + if (_disposed) return; debugLog('[ACTIVE MODE] Auto ping timer fired'); // Guard: connection may have dropped since timer was scheduled @@ -1474,6 +1602,7 @@ class PingService { _autoPingEnabled = true; _passiveModeEnabled = passiveMode; _hybridModeEnabled = hybridMode; + _txHeldByRecovery = false; _targetedModeEnabled = targetedMode; _nextPingIsDiscovery = true; // Always start hybrid with discovery @@ -1598,6 +1727,9 @@ class PingService { debugLog('[PING] Ping in progress, queuing disable for after RX window'); _pendingDisable = true; _armPendingDisableTimeout(); + // The stop is accepted now, even though the ping drains later: the + // scope runner stops with it, before this returns. + cancelScopeRunner('stop'); return true; // Return true to indicate disable was accepted (pending) } @@ -1610,6 +1742,8 @@ class PingService { return false; } + cancelScopeRunner('stop'); + // Clear auto timer _autoTimer?.cancel(); _autoTimer = null; @@ -1738,7 +1872,9 @@ class PingService { // epoch move when it resumes and bows out without transmitting, leaving // the flag to whoever holds it by then. _sendEpoch++; + cancelScopeRunner('force disable'); _pingInProgress = false; + _txHeldByRecovery = false; if (!_txWindowFinalizing) { _cancelPendingTxWindow(); _completeTxWindowGate(); @@ -1760,6 +1896,14 @@ class PingService { await _wakelockService.disable(); } + /// Count one scope request a repeater answered. The scope runner lives on + /// the provider, but the count sits with the other session stats so it + /// resets with them. + void recordScopeAnswer() { + _stats = _stats.copyWith(scopeCount: _stats.scopeCount + 1); + onStatsUpdated?.call(_stats); + } + /// Reset statistics void resetStats() { _stats = const PingStats(); @@ -1857,6 +2001,9 @@ class PingService { // dispose() calls _endWindow() while listening, which does fire. _discoveryWindowCountdown.stop(); + cancelScopeRunner('discovery stopped'); + _earliestNextDiscoveryAt = null; + _discoveryTimer?.cancel(); _discoveryTimer = null; _controlDataSubscription?.cancel(); @@ -1913,6 +2060,8 @@ class PingService { // window is running, so the flag alone cannot tell an armed window from an // attempt that bowed out. The finally needs that distinction. var armedWindow = false; + // Set when a held TX ping takes this leg instead (Hybrid). + var handToTx = false; final epoch = _sendEpoch; try { @@ -1998,22 +2147,67 @@ class PingService { } // Smart Pinging: a covered square gets no discovery request either. - if (checkRecentCoverage?.call(position.latitude, position.longitude) == + if (checkRecentCoverage?.call(position.latitude, position.longitude, + BankedPingType.discovery) == RecentCoverage.covered) { _skipReason = skipReasonRecentlyCovered; - _bankedPing = BankedPingType.discovery; - debugLog( - '[DISC] Square recently covered, discovery deferred and banked'); + // A held TX ping keeps the slot (Hybrid): the first ping into a fresh + // square should be the one that can come back two-way. + if (_bankedPing == BankedPingType.tx) { + debugLog('[DISC] Square recently covered, discovery deferred, ' + 'banked TX ping kept'); + } else { + _bankedPing = BankedPingType.discovery; + debugLog( + '[DISC] Square recently covered, discovery deferred and banked'); + } _pingInProgress = false; - onPingDeferred?.call( - position.latitude, position.longitude, BankedPingType.discovery); + // Names what is actually held, so a square first entered on this leg + // while a TX is held reports the TX. + onPingDeferred?.call(position.latitude, position.longitude, + _bankedPing ?? BankedPingType.discovery); _scheduleNextDiscovery(); return; } + // A square can be clear for discovery while still covered for TX, so + // ask about TX separately before deciding what the bank does. + final txCovered = checkRecentCoverage?.call( + position.latitude, position.longitude, BankedPingType.tx) == + RecentCoverage.covered; + + // A held TX ping is never replaced by a discovery (Hybrid). The release + // check could not see this fix: the in-progress latch above refuses it, + // getFreshPosition() bypasses the stream, and it only releases on a + // definite 'clear' while this lane also proceeds on 'unknown'. So this + // leg goes to the TX instead, unless the square is still covered for + // TX. The send itself is dispatched from the finally, once the latch is + // cleared, since sendTxPing takes it again. + if (_hybridModeEnabled && + _bankedPing == BankedPingType.tx && + !txCovered && + _gpsService.canPingAtPosition(position)) { + debugLog('[DISC] Banked TX ping takes this leg, discovery not sent'); + _bankedPing = null; + _skipReason = null; + _pingInProgress = false; + handToTx = true; + return; + } + + debugLog('[DISC] Discovery passed checks, smart ping: ' + '${_smartPingVerdict(position, BankedPingType.discovery)}'); + // Clear skip reason since we're proceeding _skipReason = null; - _bankedPing = null; + // A held TX in a square still covered for TX keeps waiting for a clear + // one: this discovery does not stand in for it. + if (_bankedPing == BankedPingType.tx && txCovered) { + debugLog( + '[DISC] Square covered for TX only, discovery sent, banked TX kept'); + } else { + _bankedPing = null; + } // Signal "Sending..." to UI (the flag itself was latched above) onPingProgressChanged?.call(); @@ -2046,12 +2240,17 @@ class PingService { // Play transmit sound immediately before sending _audioService?.playTransmitSound(); + // The previous sweep's scope runner never overlaps this one's + // request: it stops right before the write. + cancelScopeRunner('next discovery'); + // Send discovery request and get tag - final tag = await _connection.sendDiscoveryRequest(); + final sent = await _connection.sendDiscoveryRequest(); - // Start tracking with the tag + // Start tracking with the tag, timing own replies from the send _discTracker?.startTracking( - tag: tag, + tag: sent.tag, + sentAt: sent.sentAt, windowDuration: _discoveryListeningWindow, ); @@ -2070,8 +2269,14 @@ class PingService { // discovery pings too, not just TX (#501) _gpsService.markActivityPosition(position); } catch (e) { - _pingInProgress = false; debugError('[DISC] Failed to send discovery request: $e'); + if (identical(_lastDiscPing, discPing)) _lastDiscPing = null; + onDiscPingAborted?.call(discPing); + // Torn down while the write was in flight (a force disable or a + // dispose on a radio drop): the lane is gone, so no retry, and the + // flag is left alone as on the fresh-fix bow-out (see _sendEpoch). + if (_disposed || epoch != _sendEpoch) return; + _pingInProgress = false; if (_pendingDisable) { await _executePendingDisable('discovery send failed'); return; @@ -2107,6 +2312,14 @@ class PingService { if (!armedWindow && epoch == _sendEpoch) _pingInProgress = false; if (!armedWindow && _pendingDisable) { await _executePendingDisable('discovery ended without window'); + } else if (handToTx && epoch == _sendEpoch) { + // The timer callback flipped the alternation past this leg when it + // dispatched it. The TX runs in its place, so the next leg is a + // discovery, as in maybeSendBankedPing(). The TX re-arms the lane + // from its own window or skip path. + _nextPingIsDiscovery = true; + debugLog('[PING] Releasing banked TX ping in place of a discovery'); + unawaited(_sendAutoPing()); } } } @@ -2130,13 +2343,17 @@ class PingService { // Use _lastDiscPing which was already created and added to log in _sendDiscoveryRequest final discoverySuccess = _lastDiscPing?.discoveredNodes.isNotEmpty ?? false; + // The sweep's DISC writes. Nothing waits on them unless a scope runner + // starts, which must not ask before they are safely queued. + final discWrites = >[]; + final fixAltitude = _gpsService.fixAltitudeOf(position); if (discoverySuccess) { debugLog('[DISC] Processing ${nodes.length} discovered nodes'); // Queue API payloads for each discovered node (uses nodes for pubkeyFull) for (final node in nodes) { - _apiQueue.enqueueDisc( + discWrites.add(_apiQueue.enqueueDisc( latitude: position.latitude, longitude: position.longitude, repeaterId: node.repeaterId, @@ -2149,8 +2366,10 @@ class PingService { externalAntenna: getExternalAntenna?.call() ?? false, noiseFloor: _pendingTxNoiseFloor, power: getPowerLevel?.call(), - altitude: GpsService.altitudeOrNull(position), - ); + altitude: fixAltitude.meters, + altitudeRef: fixAltitude.wireReference, + altitudeAccuracy: fixAltitude.accuracy, + )); } // Update stats @@ -2168,7 +2387,9 @@ class PingService { externalAntenna: getExternalAntenna?.call() ?? false, noiseFloor: _pendingTxNoiseFloor, power: getPowerLevel?.call(), - altitude: GpsService.altitudeOrNull(position), + altitude: fixAltitude.meters, + altitudeRef: fixAltitude.wireReference, + altitudeAccuracy: fixAltitude.accuracy, ); debugLog('[DISC] Discovery drop queued (no response)'); } @@ -2188,11 +2409,65 @@ class PingService { return; } _scheduleNextDiscovery(); + if (discoverySuccess) { + _maybeStartScopeRunner(nodes, position, discWrites); + } + } + + /// Starts this sweep's scope runner alongside the schedule just armed, + /// never ahead of it: nothing about the next ping waits on the runner. + void _maybeStartScopeRunner(List nodes, Position position, + List> discWrites) { + final factory = scopeRunnerFactory; + if (factory == null) return; + if (_pendingDisable || + !_autoPingEnabled || + (!_passiveModeEnabled && !_hybridModeEnabled)) { + return; + } + final earliest = _earliestNextDiscoveryAt; + if (earliest == null) return; + // Repeaters only: a room server is never asked. + final candidates = [ + for (final node in nodes) + if (node.nodeType == DiscoveryConstants.nodeTypeRepeater) + ( + keyHex: node.pubkeyFull.toUpperCase(), + repeaterId: node.repeaterId, + lat: position.latitude, + lon: position.longitude, + localRssi: node.localRssi, + localSnr: node.localSnr, + discoveryReplyAfter: node.discoveryReplyAfter, + ), + ]; + if (candidates.isEmpty) return; + + cancelScopeRunner('superseded'); + final cap = clock.now().add(ScopeRunner.maxRunnerLifetime); + final hardStop = earliest.isBefore(cap) ? earliest : cap; + final ScopeRunner? runner; + try { + runner = factory(hardStop: hardStop, cancel: ScopeCancelToken()); + } catch (e) { + debugError('[SCOPES] Could not build the scope runner: $e'); + return; + } + if (runner == null) return; + runner.isCurrent = () => identical(_currentScopeRunner, runner); + _currentScopeRunner = runner; + final discPersisted = Future.wait(discWrites).then((_) {}); + unawaited(runner + .run(candidates, discPersisted: discPersisted) + .whenComplete(() { + if (identical(_currentScopeRunner, runner)) _currentScopeRunner = null; + })); } /// Schedule next discovery request /// Uses fixed 30-second interval (repeaters only respond 4 times per 2 minutes) void _scheduleNextDiscovery() { + if (_disposed) return; // In hybrid mode, route to hybrid scheduler instead if (_hybridModeEnabled) { _scheduleNextHybridPing(); @@ -2207,10 +2482,11 @@ class PingService { _discoveryTimer?.cancel(); _discoveryTimer = Timer(_discoveryInterval, () { debugLog('[DISC] Discovery timer fired'); - if (_autoPingEnabled && _passiveModeEnabled) { + if (!_disposed && _autoPingEnabled && _passiveModeEnabled) { _sendDiscoveryRequest(); } }); + _earliestNextDiscoveryAt = clock.now().add(_discoveryInterval); // Notify callback for countdown display (30 seconds hardcoded for discovery) onAutoPingScheduled?.call(_discoveryInterval.inMilliseconds, _skipReason); @@ -2221,8 +2497,8 @@ class PingService { /// Schedule next hybrid ping (alternates discovery ↔ TX) /// Uses user-configured interval for both ping types - void _scheduleNextHybridPing() { - if (!_autoPingEnabled || !_hybridModeEnabled) return; + void _scheduleNextHybridPing({int? delayMs}) { + if (_disposed || !_autoPingEnabled || !_hybridModeEnabled) return; _autoTimer?.cancel(); _autoTimer = null; @@ -2232,7 +2508,7 @@ class PingService { final listenMs = _nextPingIsDiscovery ? _discoveryListeningWindow.inMilliseconds : _rxListeningWindow.inMilliseconds; - final waitMs = + final waitMs = delayMs ?? (_autoPingIntervalMs - listenMs).clamp(1000, _autoPingIntervalMs); final isNextDisc = _nextPingIsDiscovery; @@ -2247,8 +2523,17 @@ class PingService { return; } + // The earliest the next discovery leg can go out: this wait when it is + // the discovery leg, else this wait plus the wait the scheduler arms + // before a discovery leg (a skipped TX arms it with no RX window). + final discoveryLegWaitMs = (_autoPingIntervalMs - + _discoveryListeningWindow.inMilliseconds) + .clamp(1000, _autoPingIntervalMs); + _earliestNextDiscoveryAt = clock.now().add(Duration( + milliseconds: isNextDisc ? waitMs : waitMs + discoveryLegWaitMs)); + _autoTimer = Timer(Duration(milliseconds: waitMs), () { - if (!_autoPingEnabled || !_hybridModeEnabled) return; + if (_disposed || !_autoPingEnabled || !_hybridModeEnabled) return; if (_connection.currentStep != ConnectionStep.connected) { debugLog('[HYBRID] Not connected, ignoring timer'); return; @@ -2542,6 +2827,7 @@ class PingService { '[TRACE] Trace successful: localSnr=${result.localSnr}, remoteSnr=${result.remoteSnr}'); // Queue to API (only successful traces) + final fixAltitude = _gpsService.fixAltitudeOf(position); _apiQueue.enqueueTrace( latitude: position.latitude, longitude: position.longitude, @@ -2553,7 +2839,9 @@ class PingService { externalAntenna: getExternalAntenna?.call() ?? false, noiseFloor: _pendingTxNoiseFloor, power: getPowerLevel?.call(), - altitude: GpsService.altitudeOrNull(position), + altitude: fixAltitude.meters, + altitudeRef: fixAltitude.wireReference, + altitudeAccuracy: fixAltitude.accuracy, ); // Update stats @@ -2579,7 +2867,7 @@ class PingService { /// Schedule next targeted ping after interval void _scheduleNextTargetedPing() { - if (!_autoPingEnabled || !_targetedModeEnabled) { + if (_disposed || !_autoPingEnabled || !_targetedModeEnabled) { debugLog('[TRACE] Not in targeted mode, not scheduling next trace'); return; } @@ -2587,6 +2875,7 @@ class PingService { _targetedTimer?.cancel(); _targetedTimer = Timer(Duration(milliseconds: _autoPingIntervalMs), () { debugLog('[TRACE] Targeted ping timer fired'); + if (_disposed) return; if (_connection.currentStep != ConnectionStep.connected) { debugLog('[TRACE] Not connected, ignoring timer'); return; @@ -2634,6 +2923,17 @@ class PingService { /// Dispose of resources void dispose() { + // A send suspended on its fresh fix or BLE write resumes after this. The + // epoch bump makes it bow out, and the cleared modes and [_disposed] stop + // any skip or failure path from re-arming a timer (the provider disposes + // on a radio drop without a force disable first). + _disposed = true; + _sendEpoch++; + _autoPingEnabled = false; + _passiveModeEnabled = false; + _hybridModeEnabled = false; + _targetedModeEnabled = false; + _pendingDisable = false; if (!_txWindowFinalizing) { _cancelPendingTxWindow(); _completeTxWindowGate(); diff --git a/lib/services/portal_account_service.dart b/lib/services/portal_account_service.dart index 01261c51..52ed0b80 100644 --- a/lib/services/portal_account_service.dart +++ b/lib/services/portal_account_service.dart @@ -185,9 +185,10 @@ class PortalAward { /// The account-wide totals the portal's Overview tab shows (`me` -> `overview`). /// -/// The server sums points over each companion's primary, exactly as the -/// portal does, so a radio filed under a group counts once. The app never adds -/// up the per-companion points itself: that sum is wrong for grouped radios. +/// Each linked radio keeps its own points; the server sums them, adds any +/// credit tied to no radio, and takes the union of grid squares. The app never +/// adds up the per-companion points itself: that would miss the unattributed +/// credit and double count shared grid squares. class PortalOverview { final int points; final int weekly; @@ -314,12 +315,17 @@ class PortalLinkOutcome { /// this attempt did not happen. Null for every other outcome. final Duration? retryAfter; + /// The radio refused part way through signing the link request (see + /// `signFailureNeedsRadioReboot`). Only a manual link shows it. + final bool radioCouldNotSign; + const PortalLinkOutcome( this.status, { this.adoptionDeviceCount = 0, this.adoptedCount = 0, this.accountName, this.retryAfter, + this.radioCouldNotSign = false, }); } diff --git a/lib/services/precise_location_gate.dart b/lib/services/precise_location_gate.dart new file mode 100644 index 00000000..092b4499 --- /dev/null +++ b/lib/services/precise_location_gate.dart @@ -0,0 +1,237 @@ +/// The Precise Location check made when the user taps Connect. +/// +/// With iOS "Precise Location" off, or Android 12+ granting only approximate +/// location, the OS hands out fixes off by hundreds of metres to kilometres. +/// The server refuses every fix worse than 50 m (`gps_inaccurate`), so such a +/// session maps nothing. The connect is refused instead, after one chance to +/// turn precise location on (iOS: the temporary full accuracy prompt; Android: +/// one fine-location re-request, which shows the "precise" upgrade dialog). +/// +/// This only reads the accuracy authorisation and asks for it. It never +/// starts GPS or sends a location. +library; + +import 'package:flutter/foundation.dart'; +import 'package:geolocator/geolocator.dart'; + +import '../utils/debug_logger_io.dart'; + +/// Purpose key for `NSLocationTemporaryUsageDescriptionDictionary` in +/// `ios/Runner/Info.plist`. The plugin errors if the dictionary is missing. +const String preciseLocationPurposeKey = 'CoverageMapping'; + +/// Title of the dialog shown when a connect is refused. +const String preciseLocationDialogTitle = 'Precise Location needed'; + +/// Body of the dialog shown when a connect is refused. +const String preciseLocationDialogBody = + 'MeshMapper needs your precise location to map coverage. Approximate ' + 'location is off by too much for the map to use.'; + +/// Title of the zone check screen while only approximate location is granted. +const String preciseLocationOffTitle = 'Precise Location Is Off'; + +/// Body of the zone check screen while only approximate location is granted. +const String preciseLocationOffBody = + 'MeshMapper only has your approximate location, which is off by too much ' + 'to map coverage.\n\nTurn on Precise Location for MeshMapper in your ' + "phone's settings, then come back to the app."; + +/// What Siri says when the connect intent is refused for approximate location. +const String preciseLocationVoiceMessage = + 'MeshMapper needs Precise Location. Turn it on for MeshMapper in ' + 'Settings, then try again.'; + +/// Which platform rules apply to the check. +enum PreciseLocationPlatform { ios, android, web } + +/// What the connect should do next about location accuracy. +enum PreciseLocationStep { + /// The check does not apply (web, GPS simulator, no location permission). + skip, + + /// Precise location (or unreadable accuracy): carry on with the connect. + connect, + + /// iOS: ask for temporary full accuracy, then decide again. + askTemporaryFullAccuracy, + + /// Android: re-request fine location once, then decide again. + requestFineLocation, + + /// Still approximate: do not connect, explain and offer the settings. + block, +} + +/// Decides the next step of the Precise Location check. +/// +/// [locationGranted] false leaves the connect to the existing denied path. +/// [accuracy] null or `unknown` (the read failed) fails open. [alreadyAsked] +/// is true once the prompt has been shown this connect, so it is shown at +/// most once. [canPrompt] is false when no prompt can be shown (the app is +/// not on screen, or no screen has registered the Android re-request). +@visibleForTesting +PreciseLocationStep decidePreciseLocationStep({ + required PreciseLocationPlatform platform, + required bool simulatorEnabled, + required bool locationGranted, + required LocationAccuracyStatus? accuracy, + required bool alreadyAsked, + required bool canPrompt, +}) { + if (platform == PreciseLocationPlatform.web || simulatorEnabled) { + return PreciseLocationStep.skip; + } + if (!locationGranted) return PreciseLocationStep.skip; + if (accuracy != LocationAccuracyStatus.reduced) { + return PreciseLocationStep.connect; + } + if (alreadyAsked || !canPrompt) return PreciseLocationStep.block; + return platform == PreciseLocationPlatform.ios + ? PreciseLocationStep.askTemporaryFullAccuracy + : PreciseLocationStep.requestFineLocation; +} + +/// Runs [decidePreciseLocationStep] against the platform. +class PreciseLocationGate { + PreciseLocationGate({ + Future Function()? checkGranted, + Future Function()? readAccuracy, + Future Function()? requestTemporaryFullAccuracy, + }) : _checkGranted = checkGranted ?? _platformGranted, + _readAccuracy = readAccuracy ?? Geolocator.getLocationAccuracy, + _requestTemporaryFullAccuracy = requestTemporaryFullAccuracy ?? + (() => Geolocator.requestTemporaryFullAccuracy( + purposeKey: preciseLocationPurposeKey, + )); + + final Future Function() _checkGranted; + final Future Function() _readAccuracy; + final Future Function() _requestTemporaryFullAccuracy; + + static Future _platformGranted() async { + final permission = await Geolocator.checkPermission(); + return permission == LocationPermission.whileInUse || + permission == LocationPermission.always; + } + + /// Null when the read fails, which the decision treats as fail-open. + Future _tryReadAccuracy() async { + try { + return await _readAccuracy(); + } catch (e) { + debugWarn('[GPS] Precise location check: accuracy read failed, ' + 'allowing the connect: $e'); + return null; + } + } + + /// Whether location is granted but only approximate. False when the check + /// does not apply (web, GPS simulator, no permission) or a read fails. + /// Reads only, never prompts. + Future isApproximateOnly({ + required PreciseLocationPlatform platform, + required bool simulatorEnabled, + }) async { + if (platform == PreciseLocationPlatform.web || simulatorEnabled) { + return false; + } + try { + if (!await _checkGranted()) return false; + return await _readAccuracy() == LocationAccuracyStatus.reduced; + } catch (e) { + debugWarn('[GPS] Location accuracy read failed: $e'); + return false; + } + } + + /// The platform this build runs on, as the check sees it. + static PreciseLocationPlatform get currentPlatform { + if (kIsWeb) return PreciseLocationPlatform.web; + return defaultTargetPlatform == TargetPlatform.iOS + ? PreciseLocationPlatform.ios + : PreciseLocationPlatform.android; + } + + /// True when the connect may go ahead. + /// + /// [requestFineLocation] (Android) shows the location disclosure and + /// re-requests the permission; null means it cannot be shown now. [entry] + /// names the connect path in the log. + Future allowsConnect({ + required PreciseLocationPlatform platform, + required bool simulatorEnabled, + required bool canPrompt, + Future Function()? requestFineLocation, + required String entry, + }) async { + if (platform == PreciseLocationPlatform.web || simulatorEnabled) { + debugLog('[GPS] Precise location check skipped for $entry connect ' + '(${simulatorEnabled ? 'GPS simulator' : 'web'})'); + return true; + } + + bool granted; + try { + granted = await _checkGranted(); + } catch (e) { + debugWarn('[GPS] Precise location check: permission read failed: $e'); + granted = false; + } + + var asked = false; + var accuracy = granted ? await _tryReadAccuracy() : null; + while (true) { + final step = decidePreciseLocationStep( + platform: platform, + simulatorEnabled: simulatorEnabled, + locationGranted: granted, + accuracy: accuracy, + alreadyAsked: asked, + canPrompt: canPrompt && + (platform == PreciseLocationPlatform.ios || + requestFineLocation != null), + ); + switch (step) { + case PreciseLocationStep.skip: + debugLog('[GPS] Precise location check skipped for $entry connect ' + '(location not granted, left to the permission path)'); + return true; + case PreciseLocationStep.connect: + debugLog('[GPS] Precise location check for $entry connect: ' + '${accuracy?.name ?? 'unreadable'}' + '${asked ? ' after the prompt' : ''}, connecting'); + return true; + case PreciseLocationStep.askTemporaryFullAccuracy: + debugLog('[GPS] Location accuracy is reduced, showing the iOS ' + 'temporary precise location prompt'); + asked = true; + try { + accuracy = await _requestTemporaryFullAccuracy(); + debugLog('[GPS] Temporary precise location prompt returned ' + '${accuracy.name}'); + } catch (e) { + debugWarn('[GPS] Temporary precise location prompt failed: $e'); + // Counted as declined, not as unreadable (which fails open). + accuracy = LocationAccuracyStatus.reduced; + } + case PreciseLocationStep.requestFineLocation: + debugLog('[GPS] Location accuracy is reduced, re-requesting fine ' + 'location (Android precise upgrade)'); + asked = true; + try { + final shown = await requestFineLocation!(); + debugLog('[GPS] Fine location re-request ' + '${shown ? 'shown' : 'not shown'}'); + } catch (e) { + debugWarn('[GPS] Fine location re-request failed: $e'); + } + accuracy = await _tryReadAccuracy(); + case PreciseLocationStep.block: + debugWarn('[GPS] Connect refused for $entry: location accuracy is ' + 'reduced${asked ? ' after the prompt' : ' (no prompt possible)'}'); + return false; + } + } + } +} diff --git a/lib/services/recent_coverage_service.dart b/lib/services/recent_coverage_service.dart index 6c030390..7262b7f9 100644 --- a/lib/services/recent_coverage_service.dart +++ b/lib/services/recent_coverage_service.dart @@ -92,9 +92,14 @@ double _metersBetween(double lat1, double lon1, double lat2, double lon2) { return 2 * r * math.atan2(math.sqrt(a), math.sqrt(1 - a)); } +/// The colour of a covered cell: green is a heard TX echo, cyan an answered +/// discovery (the tile's `st` 1 and 2). +enum CoverageColor { green, cyan } + class _Tile { - /// 'i,j' keys of the covered cells. Null until the first successful fetch. - Set? cells; + /// 'i,j' keys of the covered cells with their colour. Null until the first + /// successful fetch. + Map? cells; DateTime? fetchedAt; DateTime? lastAttemptAt; bool loading = false; @@ -122,9 +127,10 @@ class RecentCoverageService { int _days = 14; String? _radioKey; bool _enabled = false; + bool _floodOnly = false; final Map _tiles = {}; // 'x/y' - final Set _sessionCells = {}; // 'i,j' + final Map _sessionCells = {}; // 'i,j' /// Squares already reported as deferred this API session, on the fixed /// 300 m grid whatever the user's Coverage Grid setting. The server dedupes @@ -139,6 +145,9 @@ class RecentCoverageService { /// True when the feature is on and a zone is known. bool get isActive => _enabled && _zone != null && _zone!.isNotEmpty; + /// True when only green cells hold a TX and a discovery is never held. + bool get floodOnly => _floodOnly; + /// Loaded (successfully fetched) tiles. Test hook. int get loadedTileCount => _tiles.values.where((t) => t.loaded).length; @@ -147,6 +156,8 @@ class RecentCoverageService { /// question. [radioKey] is `radioFilterKey(...)` from /// `lib/utils/radio_filter.dart` (the fetch itself carries the filter /// through ApiService; this only decides when loaded tiles go stale). + /// [floodOnly] is not part of that: tiles hold both colours, so flipping it + /// keeps them and only changes how [isCovered] reads them. /// /// Called on every zone check (every 100 m while disconnected), so an /// identical reconfigure is silent: it logs only when the zone, grid, @@ -157,8 +168,10 @@ class RecentCoverageService { required int days, required bool enabled, String? radioKey, + bool floodOnly = false, }) { final wasActive = isActive; + final floodOnlyChanged = floodOnly != _floodOnly; final changed = zone != _zone || gridSize != _gridSize || days != _days || @@ -168,12 +181,13 @@ class RecentCoverageService { _days = days; _radioKey = radioKey; _enabled = enabled; + _floodOnly = floodOnly; if (changed || !isActive) { clear(); } - if (changed || isActive != wasActive) { + if (changed || isActive != wasActive || floodOnlyChanged) { debugLog( - '[COVERAGE] Smart pinging ${isActive ? 'active' : 'inactive'}: zone=${zone ?? '-'} grid=${gridSize}m window=${days}d preset=${radioKey ?? 'any'} enabled=$enabled'); + '[COVERAGE] Smart pinging ${isActive ? 'active' : 'inactive'}: zone=${zone ?? '-'} grid=${gridSize}m window=${days}d preset=${radioKey ?? 'any'} enabled=$enabled floodOnly=$floodOnly'); } } @@ -188,12 +202,14 @@ class RecentCoverageService { /// The covered cell of a result this session got (a heard TX, an answered /// discovery), so the phone does not wait for the server tile to catch up. - void markCovered(double lat, double lon) { + /// Green wins: a later cyan mark never downgrades a green one. + void markCovered(double lat, double lon, CoverageColor color) { if (!isActive) return; final key = _cellKey(lat, lon); - if (_sessionCells.add(key)) { - debugLog('[COVERAGE] Session covered cell $key'); - } + final had = _sessionCells[key]; + if (had == CoverageColor.green || had == color) return; + _sessionCells[key] = color; + debugLog('[COVERAGE] Session covered cell $key (${color.name})'); } /// Record that smart pinging held a ping on this fix's fixed 300 m square. @@ -210,19 +226,26 @@ class RecentCoverageService { /// session), because the server credits one square per session id. void clearDeferred() => _deferredCells.clear(); - /// Whether the cell under this fix is recently covered. - RecentCoverage isCovered(double lat, double lon) { + /// Whether the cell under this fix is recently covered for this kind of + /// ping ([forTx] true for a TX, false for a discovery). With [floodOnly] a + /// discovery is never held and only a green cell holds a TX. + RecentCoverage isCovered(double lat, double lon, {required bool forTx}) { if (!isActive) return RecentCoverage.clear; + if (_floodOnly && !forTx) return RecentCoverage.clear; final key = _cellKey(lat, lon); - if (_sessionCells.contains(key)) return RecentCoverage.covered; + if (_counts(_sessionCells[key])) return RecentCoverage.covered; final t = recentCoverageTile(lat, lon); final tile = _tiles['${t.x}/${t.y}']; if (tile == null || !tile.loaded) return RecentCoverage.unknown; - return tile.cells!.contains(key) + return _counts(tile.cells![key]) ? RecentCoverage.covered : RecentCoverage.clear; } + /// Whether a cell of this colour (null: not covered) holds a ping. + bool _counts(CoverageColor? color) => + color != null && (!_floodOnly || color == CoverageColor.green); + /// Keep every tile within 500 m of the fix loaded and fresh. Cheap when the /// phone has not moved 100 m since the last call. Fetches run one at a /// time; the returned future completes when the queue drains. @@ -295,7 +318,17 @@ class RecentCoverageService { '[COVERAGE] Recent tile $key came back unfiltered (a cell that is not green or cyan), ignoring it'); continue; } - tile.cells = cells.map((c) => '${c.i},${c.j}').toSet(); + // A block (a feature carrying `k`) summarises k by k 300 m cells, + // so its i/j are not cells of this grid and its colour does not + // say every cell inside it is covered. Leave it out: those cells + // read clear and the ping goes out, the fail-open answer. z13 + // tiles carry no blocks today. + tile.cells = { + for (final c in cells) + if (!c.isBlock) + '${c.i},${c.j}': + c.st == 2 ? CoverageColor.cyan : CoverageColor.green, + }; tile.fetchedAt = _now(); debugLog( '[COVERAGE] Recent tile $key loaded: ${tile.cells!.length} covered cells'); diff --git a/lib/services/reconnect_flap_guard.dart b/lib/services/reconnect_flap_guard.dart new file mode 100644 index 00000000..244f9b50 --- /dev/null +++ b/lib/services/reconnect_flap_guard.dart @@ -0,0 +1,48 @@ +/// Counts radio drops that come right after an auto-reconnect succeeded. +/// +/// Every drop starts a fresh reconnect budget and every success clears it, so +/// a link that reconnects and then drops again within seconds (a radio on a +/// dying battery, say) looped for as long as the user let it, with no alert. +/// After [maxFlaps] such drops in a row the provider gives up instead. A +/// connection that stays up longer than [window] before it drops resets the +/// count, so ordinary range drops on a long drive never add up. +class ReconnectFlapGuard { + ReconnectFlapGuard({ + this.window = const Duration(seconds: 30), + this.maxFlaps = 3, + }); + + /// A drop at most this long after a reconnect success counts as a flap. + final Duration window; + + /// Flaps in a row that end the reconnecting. + final int maxFlaps; + + DateTime? _lastSuccessAt; + int _flaps = 0; + + /// Quick drops counted so far. + int get flaps => _flaps; + + /// An auto-reconnect reached a connected radio. + void onReconnectSuccess(DateTime now) => _lastSuccessAt = now; + + /// The radio dropped. True when this drop is the [maxFlaps]th in a row to + /// follow a reconnect within [window]: stop reconnecting. + bool onDrop(DateTime now) { + final last = _lastSuccessAt; + _lastSuccessAt = null; + if (last != null && now.difference(last) <= window) { + _flaps++; + } else { + _flaps = 0; + } + return _flaps >= maxFlaps; + } + + /// The radio session ended (a user disconnect or an abandoned reconnect). + void reset() { + _flaps = 0; + _lastSuccessAt = null; + } +} diff --git a/lib/services/repeater_admin/manage_target.dart b/lib/services/repeater_admin/manage_target.dart index 19797b5a..7cf4bde8 100644 --- a/lib/services/repeater_admin/manage_target.dart +++ b/lib/services/repeater_admin/manage_target.dart @@ -5,6 +5,16 @@ const String kChooseFromListHint = 'Choose from the list'; const String kCompanionFirmwareFloorHint = 'Update companion firmware to use Manage'; +/// Why Manage waits while a scope request still owns the radio. +const String kScopeRadioBusyHint = + 'Finishing a scope request. Try again in a few seconds.'; + +/// Whether scope discovery still owns the radio: a lease is held, or a reply +/// is still owed for a command already written. +bool scopeRadioBusy( + {required bool isScopeLeaseActive, required bool hasScopeReplyDebt}) => + isScopeLeaseActive || hasScopeReplyDebt; + /// Companion capability code introduced with MeshCore v1.9.0, which forwards /// the login reply's ACL permissions and repeater firmware level. /// This is FIRMWARE_VER_CODE, byte 1 of RESP_CODE_DEVICE_INFO, not the release @@ -52,6 +62,7 @@ String? manageBlockReason({ required bool isRepeaterAdminActive, required bool isAutoReconnecting, required bool companionFirmwareSupported, + required bool scopeRadioBusy, }) { if (!isConnected || isAutoReconnecting) { return 'Connect a radio to manage this repeater'; @@ -62,5 +73,6 @@ String? manageBlockReason({ return 'Wait for the current ping to finish'; } if (isRepeaterAdminActive) return 'A repeater session is already open'; + if (scopeRadioBusy) return kScopeRadioBusyHint; return null; } diff --git a/lib/services/repeater_admin/repeater_admin_session.dart b/lib/services/repeater_admin/repeater_admin_session.dart index a2a34054..8a7e6570 100644 --- a/lib/services/repeater_admin/repeater_admin_session.dart +++ b/lib/services/repeater_admin/repeater_admin_session.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import '../../utils/debug_logger_io.dart'; import '../meshcore/connection.dart'; +import 'manage_target.dart' show kScopeRadioBusyHint, scopeRadioBusy; import 'repeater_admin_models.dart'; enum RepeaterAdminState { idle, ensuringContact, loggingIn, admin, guest, failed } @@ -25,6 +26,8 @@ const String kNeighboursUnansweredSentence = "This repeater's firmware cannot report neighbours."; const String kNeighboursTimeoutSentence = 'No reply from the repeater. Try again.'; +const String kContactListTimeoutSentence = + "Your radio didn't finish sending its contact list. Try again."; const String kAdminCommandPendingSentence = 'The radio is still finishing the previous request. ' 'Wait for its reply, or close Manage and try again.'; @@ -492,12 +495,24 @@ class RepeaterAdminSession extends ChangeNotifier { debugLog('[RADMIN] Command refused: ${_closed ? 'closed' : 'busy'}'); return false; } - if (_connection.hasPendingAdminCommand) { + // A scope lease holds the admin slot too, so it is named first; the + // admin lane's own retained reply keeps its own sentence; reply debt + // left behind by a lease is the scope case again. + final scopeLease = _connection.isScopeLeaseActive; + if (!scopeLease && _connection.hasPendingAdminCommand) { _lastError = kAdminCommandPendingSentence; debugLog('[RADMIN] Command refused: radio request still pending'); _notify(); return false; } + if (scopeRadioBusy( + isScopeLeaseActive: scopeLease, + hasScopeReplyDebt: _connection.hasScopeReplyDebt)) { + _lastError = kScopeRadioBusyHint; + debugLog('[RADMIN] Command refused: a scope request owns the radio'); + _notify(); + return false; + } _busy = true; _notify(); return true; @@ -518,13 +533,22 @@ class RepeaterAdminSession extends ChangeNotifier { } void _fail(String message) { + debugLog('[RADMIN] Failed: $message'); _lastError = message; _state = RepeaterAdminState.failed; _notify(); } Future _ensureContact() async { - final contacts = await _connection.getContacts(); + final List contacts; + try { + contacts = await _connection.getContacts(); + } on TimeoutException { + // A local read, not the mesh: it must not read as a wrong password or + // count towards the automatic route reset. + debugWarn('[RADMIN] Contact list read timed out'); + throw const RepeaterAdminFailure(kContactListTimeoutSentence); + } final existing = _findContact(contacts); if (existing != null) { // Leave it alone: an add would wipe the learned route. diff --git a/lib/services/scope_discovery/scope_discovery_rules.dart b/lib/services/scope_discovery/scope_discovery_rules.dart new file mode 100644 index 00000000..734893ff --- /dev/null +++ b/lib/services/scope_discovery/scope_discovery_rules.dart @@ -0,0 +1,444 @@ +import 'dart:async'; + +import '../../utils/debug_logger_io.dart'; +import '../../utils/public_key.dart'; + +/// Whether a repeater's scopes should be asked again right now. +/// +/// Reads two independent signals, and answers due only when both of them +/// call for a fresh ask: +/// +/// - Rule 1, the server side: the server's own `scopesCheckedAt` for this +/// repeater. [onServerList] false (no list at all: offline, not loaded +/// yet) always counts as due on this rule. +/// - Rule 2, the phone side: this phone's own cached [phone] answer, if any. +/// +/// [persistPending] is read before either rule: while an earlier answer for +/// this same repeater is still being written (Task 6's detached +/// persistence), the repeater is never due, whatever the two rules would +/// otherwise say. +/// +/// [heldUntil] is read next: a repeater this phone asked and got no answer +/// from is held (not due) until that Unix-second deadline, whatever the two +/// rules would otherwise say. Null means no hold. At (not past) the +/// deadline it is due again, so the caller's own [nowSec] decides the +/// boundary, not this function. +bool isScopeQueryDue({ + required bool onServerList, + required int? serverCheckedAt, + required ScopeCacheEntry? phone, + required bool persistPending, + required int nowSec, + required int refreshDays, + int? heldUntil, +}) { + if (persistPending) return false; + if (heldUntil != null && nowSec < heldUntil) return false; + final refreshSec = refreshDays * 86400; + final rule1 = !onServerList || + serverCheckedAt == null || + nowSec - serverCheckedAt >= refreshSec; + final answeredAt = phone?.answeredAt; + final rule2 = answeredAt == null || nowSec - answeredAt >= refreshSec; + return rule1 && rule2; +} + +/// This phone's own cached answer for one repeater. +/// +/// There are no attempt stamps here: a request that got no answer records +/// nothing in [ScopeQueryCache]'s answer map. Instead it starts or extends a +/// separate, memory-only hold (see [ScopeQueryCache.recordNoAnswer]), so +/// this repeater is not re-asked and re-silenced within the same firmware +/// window. +class ScopeCacheEntry { + /// When this phone last got an answer from the repeater (Unix seconds). + final int? answeredAt; + + const ScopeCacheEntry({this.answeredAt}); +} + +/// The phone-side scope answer cache: the secondary guard behind the +/// server's own `scopes_checked_at`. The server already stops re-asks of +/// registered repeaters fleet-wide, and the hourly budget bounds how many +/// answers a phone can hold in the first place, so this cache's own +/// retention can be bounded on purpose (server ruling, round 2) without +/// costing more than an occasional extra zero-hop request. +/// +/// Keys are the repeater's full public key, normalized with +/// [normalizePublicKey]; anything that does not normalize is never stored +/// and never returned. +class ScopeQueryCache { + /// Retention is bounded: once more than this many answers are held, the + /// oldest are evicted regardless of how fresh the interval says they + /// still are. + static const int maxEntries = 20000; + + /// The bound Task 6's runner holds `pendingPersist` to. Named here so both + /// sides agree on the number; enforcing it (never evicting past it) is the + /// runner's job, not this cache's. + static const int maxPendingPersist = 32; + + /// The hold length for each consecutive miss, in order. A miss past the + /// end of this list holds for [noAnswerHoldMax]. The first step is short + /// on purpose: a first miss is usually a car at the edge of a repeater's + /// range, and by 15 minutes it has driven out of range for good. + static const List noAnswerHoldSteps = [ + Duration(minutes: 1), + Duration(minutes: 5), + Duration(minutes: 10), + Duration(minutes: 20), + ]; + + /// The longest a hold ever runs, however many consecutive misses in a + /// row. Also how long after a miss the stronger-signal rule + /// ([strongerSignalMarginDb]) stays in force. + static const Duration noAnswerHoldMax = Duration(minutes: 30); + + /// Once a hold has run out, a retry within [noAnswerHoldMax] of the miss + /// also needs the repeater heard at least this many dB stronger than it + /// was at the miss. Re-asking at the same signal would most likely go + /// unanswered again and spend the repeater's shared anonymous-request + /// budget (4 per 3 minutes, across every phone) for nothing; a parked + /// phone therefore waits out the full [noAnswerHoldMax]. + static const int strongerSignalMarginDb = 1; + + final Map _entries; + + /// Repeater keys whose answer is still being written to disk (Task 6's + /// detached persistence). Memory only: never read by [toJson] or + /// populated by [fromJson]. + final Set pendingPersist = {}; + + /// Consecutive no-answer holds, keyed the same way as [_entries]. Memory + /// only, exactly like [pendingPersist]: never read by [toJson] or + /// populated by [fromJson], so a hold never survives a relaunch. + final Map _holds = {}; + + ScopeQueryCache._(this._entries); + + /// Builds a cache from a stored JSON map. Tolerates any junk: a non-map + /// root, a key that does not normalize to a full public key, or a value + /// that is not a map with an int (or num) `answeredAt` is simply skipped. + factory ScopeQueryCache.fromJson(Map? json) { + final entries = {}; + if (json != null) { + json.forEach((rawKey, rawValue) { + final key = normalizePublicKey(rawKey); + if (key == null) return; + if (rawValue is! Map) return; + final rawAnsweredAt = rawValue['answeredAt']; + final answeredAt = rawAnsweredAt is int + ? rawAnsweredAt + : rawAnsweredAt is num + ? rawAnsweredAt.toInt() + : null; + if (answeredAt == null) return; + entries[key] = ScopeCacheEntry(answeredAt: answeredAt); + }); + } + return ScopeQueryCache._(entries); + } + + /// Serializes the answer stamps only. [pendingPersist] never rides along: + /// it names work in flight for this launch, not a durable fact. + Map toJson() => { + for (final entry in _entries.entries) + entry.key: {'answeredAt': entry.value.answeredAt}, + }; + + /// This repeater's cached answer, or null when it has none or [keyHex] + /// does not normalize to a full public key. + ScopeCacheEntry? operator [](String keyHex) { + final key = normalizePublicKey(keyHex); + if (key == null) return null; + return _entries[key]; + } + + /// Records that the repeater answered at [nowSec]. A no-op when [keyHex] + /// does not normalize to a full public key. Also clears any no-answer + /// hold and miss count [keyHex] was carrying: an answer means the + /// repeater is reachable again, so the next silence starts a fresh count. + void recordAnswer(String keyHex, int nowSec) { + final key = normalizePublicKey(keyHex); + if (key == null) return; + _entries[key] = ScopeCacheEntry(answeredAt: nowSec); + _holds.remove(key); + } + + /// Clears any no-answer hold and miss count for [keyHex], without + /// touching its answer stamp. Unlike [recordAnswer], this is called the + /// moment a reply PARSES as a valid scope list, whatever happens to its + /// persistence afterward: the repeater proved it is reachable right then, + /// so a failed save (or a hourly-cap withholding) must not leave the + /// miss count in place for the next ask to double from. A no-op when + /// [keyHex] does not normalize to a full public key. + void clearHold(String keyHex) { + final key = normalizePublicKey(keyHex); + if (key == null) return; + _holds.remove(key); + } + + /// The Unix-second deadline before which [keyHex] must not be asked + /// again, or null when it has no hold (never missed, or its last hold was + /// cleared by an answer). Also null when [keyHex] does not normalize. + int? heldUntil(String keyHex) { + final key = normalizePublicKey(keyHex); + if (key == null) return null; + return _holds[key]?.heldUntil; + } + + /// Whether [keyHex], whose hold has run out, is still waiting for a + /// stronger signal before it may be asked again: heard at [rssi] now, + /// less than [strongerSignalMarginDb] above the RSSI it was heard at when + /// it last missed, and still within [noAnswerHoldMax] of that miss. False + /// when it has no hold, the miss carried no RSSI, or [keyHex] does not + /// normalize. Does not look at [heldUntil]; the caller checks that first. + bool awaitingStrongerSignal(String keyHex, + {required int nowSec, required int rssi}) { + final key = normalizePublicKey(keyHex); + if (key == null) return false; + final hold = _holds[key]; + final missRssi = hold?.missRssi; + if (hold == null || missRssi == null) return false; + if (nowSec - hold.missAt >= noAnswerHoldMax.inSeconds) return false; + return rssi < missRssi + strongerSignalMarginDb; + } + + /// Records that an ask to [keyHex] at [nowSec] got no answer: starts or + /// extends its hold so this phone does not re-ask (and re-silence) it + /// before the repeater firmware's shared anonymous-request budget has had + /// a chance to recover, or before the phone is heard better than it was. + /// + /// The [missCount]th consecutive miss (no answer landing in between) + /// holds for the matching [noAnswerHoldSteps] entry, then + /// [noAnswerHoldMax] past the end of the list. [rssi] is the discovery + /// RSSI the repeater was heard at for this ask, kept for + /// [awaitingStrongerSignal]. A no-op when [keyHex] does not normalize to + /// a full public key. + void recordNoAnswer(String keyHex, int nowSec, {int? rssi}) { + final key = normalizePublicKey(keyHex); + if (key == null) return; + final missCount = (_holds[key]?.missCount ?? 0) + 1; + final holdSec = _holdSecondsFor(missCount); + final heldUntil = nowSec + holdSec; + _holds[key] = _ScopeHold( + heldUntil: heldUntil, + missCount: missCount, + missAt: nowSec, + missRssi: rssi); + debugLog('[SCOPES] ${_logPrefix(key)}: held for ' + '${_describeSeconds(holdSec)} after miss #$missCount' + '${rssi == null ? '' : ' at $rssi dBm, then needs ' + '${rssi + strongerSignalMarginDb} dBm or better until ' + '${_describeSeconds(noAnswerHoldMax.inSeconds)} after the miss'}'); + } + + /// The hold length for the [missCount]th consecutive miss. + static int _holdSecondsFor(int missCount) { + final i = missCount - 1; + if (i >= 0 && i < noAnswerHoldSteps.length) { + return noAnswerHoldSteps[i].inSeconds; + } + return noAnswerHoldMax.inSeconds; + } + + static String _logPrefix(String keyHex) => + keyHex.length <= 8 ? keyHex : keyHex.substring(0, 8); + + static String _describeSeconds(int sec) { + if (sec % 3600 == 0) { + final h = sec ~/ 3600; + return '$h ${h == 1 ? 'hour' : 'hours'}'; + } + final m = sec ~/ 60; + return '$m ${m == 1 ? 'minute' : 'minutes'}'; + } + + /// Drops answers the interval no longer needs, then, only if still over + /// [maxEntries], evicts the oldest remaining answers to fit. + /// + /// Retention follows the interval in force, never a fixed age (the server + /// allows intervals up to 99999 days): an answer stops blocking a re-ask + /// once it is older than [refreshDays], so removing it at that point + /// cannot change any decision [isScopeQueryDue] would make under the same + /// interval. If the interval later grows, a stamp pruned under a shorter + /// interval is gone, so that repeater can be asked early once; a known, + /// accepted edge. + void prune({required int nowSec, required int refreshDays}) { + final refreshSec = refreshDays * 86400; + _entries.removeWhere((_, entry) { + final answeredAt = entry.answeredAt; + return answeredAt != null && nowSec - answeredAt >= refreshSec; + }); + final overflow = _entries.length - maxEntries; + if (overflow <= 0) return; + final oldestFirst = _entries.entries.toList() + ..sort((a, b) => + (a.value.answeredAt ?? 0).compareTo(b.value.answeredAt ?? 0)); + for (var i = 0; i < overflow; i++) { + _entries.remove(oldestFirst[i].key); + } + debugLog('[SCOPES] Evicted $overflow scope cache ' + '${overflow == 1 ? 'entry' : 'entries'} over the $maxEntries cap'); + } +} + +/// One repeater's no-answer hold, as [ScopeQueryCache] tracks it in memory. +class _ScopeHold { + /// The Unix-second deadline before which the repeater is not due. + final int heldUntil; + + /// Consecutive misses (no intervening answer) that produced [heldUntil]. + final int missCount; + + /// When the latest miss happened (Unix seconds). + final int missAt; + + /// The discovery RSSI the repeater was heard at for the latest miss, or + /// null when the caller did not know it. + final int? missRssi; + + const _ScopeHold( + {required this.heldUntil, + required this.missCount, + required this.missAt, + this.missRssi}); +} + +/// The per-device-hour cap on `SCOPES` uploads: [perHour] per hour of the +/// answer's own timestamp, matching the server's own cap on the item's +/// timestamp. [deviceKey] is the connected radio's public key, or the +/// session id when there is none (ruling 5); there is no session reset, so +/// the same radio under a new session id is still capped by its own key. +/// +/// Restart-safe: [tryConsume] reserves synchronously in memory, so the +/// caller never waits on storage to know whether it may proceed. +/// [persistReservation] then writes that reservation durably, serialized +/// through one internal chain so two answers persisting at once both land +/// instead of one clobbering the other's count. +class ScopeHourlyBudget { + static const int perHour = 60; + + final Future Function(Map json) _save; + final Map _counts = {}; + + /// Buckets (`deviceKey|hour`) with one or more [persistReservation] calls + /// still running, counted by how many: incremented when a call starts, + /// decremented only when that call's own save settles (success or + /// failure), whatever turn it happens to be taking on the write chain. A + /// bucket stays in here (count above zero) as long as any of its calls is + /// still outstanding, so two overlapping reservations for the same bucket + /// keep it protected until BOTH finish, not just the first; it is never + /// dropped as stale while its count is above zero, however old it has + /// become in the meantime. + final Map _inFlightBuckets = {}; + + Future _chain = Future.value(); + + ScopeHourlyBudget( + {required Future Function(Map json) save}) + : _save = save; + + /// Loads a persisted budget. Tolerates junk like [ScopeQueryCache] does: a + /// non-map root, a bucket key with no hour suffix, or a non-numeric count + /// is skipped. Buckets older than the previous hour (relative to + /// [nowSec]) are dropped on load, since nothing can be in flight for a + /// budget that has not run yet. + factory ScopeHourlyBudget.fromJson( + Map? json, { + required Future Function(Map json) save, + required int nowSec, + }) { + final budget = ScopeHourlyBudget(save: save); + if (json != null) { + final currentHour = nowSec ~/ 3600; + json.forEach((bucketKey, rawCount) { + final count = rawCount is int + ? rawCount + : rawCount is num + ? rawCount.toInt() + : null; + if (count == null) return; + final hour = _hourOf(bucketKey); + if (hour == null) return; + if (hour < currentHour - 1) return; + budget._counts[bucketKey] = count; + }); + } + return budget; + } + + /// The raw bucket counts, exactly as [persistReservation] would save them + /// right now. Mainly useful for tests and diagnostics; the durable write + /// path is [persistReservation], not this. + Map toJson() => Map.from(_counts); + + /// True while [deviceKey]'s bucket for the hour [nowSec] falls in still + /// has room. Read-only: reserves nothing. + bool canAsk(String deviceKey, int nowSec) => + (_counts[_bucketKey(deviceKey, nowSec ~/ 3600)] ?? 0) < perHour; + + /// Reserves one slot in [deviceKey]'s bucket for the hour [answerSec] + /// falls in, synchronously. False when that hour is already full. + bool tryConsume(String deviceKey, int answerSec) { + final key = _bucketKey(deviceKey, answerSec ~/ 3600); + final count = _counts[key] ?? 0; + if (count >= perHour) return false; + _counts[key] = count + 1; + return true; + } + + /// Durably persists the reservation [tryConsume] made for [deviceKey]'s + /// [hour] bucket. + /// + /// The bucket is marked in flight for the life of this call (from here + /// until the returned future settles, not merely for as long as this + /// call's own turn on the write chain takes), so a later call's + /// stale-bucket drop never removes an answer whose own persistence has + /// not finished, however old that bucket has become in the meantime. + /// + /// Resolves false when [save] throws; the in-memory reservation stays + /// counted regardless, which is conservative: a failed write drops the + /// answer, it never grants an extra slot. + Future persistReservation(String deviceKey, int hour) { + final bucketKey = _bucketKey(deviceKey, hour); + _inFlightBuckets[bucketKey] = (_inFlightBuckets[bucketKey] ?? 0) + 1; + _dropStale(hour); + final result = Completer(); + _chain = _chain.then((_) async { + try { + await _save(Map.from(_counts)); + result.complete(true); + } catch (e) { + debugWarn('[SCOPES] Failed to persist scope hour budget: $e'); + result.complete(false); + } finally { + final remaining = (_inFlightBuckets[bucketKey] ?? 1) - 1; + if (remaining <= 0) { + _inFlightBuckets.remove(bucketKey); + } else { + _inFlightBuckets[bucketKey] = remaining; + } + } + }); + return result.future; + } + + /// Drops buckets older than the previous hour relative to [currentHour], + /// except one still counted in [_inFlightBuckets]. + void _dropStale(int currentHour) { + _counts.removeWhere((key, _) { + if (_inFlightBuckets.containsKey(key)) return false; + final hour = _hourOf(key); + return hour != null && hour < currentHour - 1; + }); + } + + static String _bucketKey(String deviceKey, int hour) => '$deviceKey|$hour'; + + static int? _hourOf(String bucketKey) { + final i = bucketKey.lastIndexOf('|'); + if (i < 0) return null; + return int.tryParse(bucketKey.substring(i + 1)); + } +} diff --git a/lib/services/scope_discovery/scope_lifecycle.dart b/lib/services/scope_discovery/scope_lifecycle.dart new file mode 100644 index 00000000..2992f673 --- /dev/null +++ b/lib/services/scope_discovery/scope_lifecycle.dart @@ -0,0 +1,272 @@ +import 'dart:async'; + +import '../../utils/debug_logger_io.dart'; +import '../meshcore/connection.dart' show ContactRecord; +import 'scope_provider_support.dart'; +import 'scope_runner.dart'; + +/// Companion firmware code (byte 1 of RESP_CODE_DEVICE_INFO) scope +/// discovery needs to ask a repeater at all. +const int kScopeDiscoveryFirmwareFloor = 13; + +/// Everything the scope discovery gate reads. +/// +/// [offered] is whether the last live `/auth` carried the `scope_discovery` +/// key, [enforced] whether it switched the feature on, [userEnabled] the +/// user's own switch, [firmwareCode] the connected companion's code. +typedef ScopeGateInputs = ({ + bool offered, + bool enforced, + bool userEnabled, + bool offlineMode, + int? firmwareCode, +}); + +/// Whether scope discovery may run: the server offered it, the effective +/// switch is on (the admin's enforcement wins over the user), Offline Mode +/// never asks, and the companion's firmware can carry the request. +bool scopeDiscoveryGateOpen(ScopeGateInputs g) => + g.offered && + (g.enforced || g.userEnabled) && + !g.offlineMode && + (g.firmwareCode ?? 0) >= kScopeDiscoveryFirmwareFloor; + +/// The provider-side events that end scope work at once. +enum ScopeStopEvent { + airborne('airborne'), + offlineSwitch('offline mode switch'), + onlineSwitch('online mode switch'), + zoneTransfer('zone transfer'), + userDisconnect('disconnect'), + disconnectCleanup('disconnect cleanup'), + autoReconnect('link lost'), + gateClosed('scope discovery switched off'), + dispose('disposed'); + + /// The stop reason logged by the runner. + final String reason; + + const ScopeStopEvent(this.reason); + + /// True when the connection goes with the event, so routes borrowed on + /// it are forgotten too (the radio replaces them when it learns a path). + bool get dropsConnection => + this == userDisconnect || + this == disconnectCleanup || + this == autoReconnect || + this == dispose; +} + +/// The provider's scope discovery wiring in one testable place: whether a +/// sweep gets a runner, the Scopes badge, routes borrowed per connection, +/// the stop events, and the connect-time repeater refresh discard. +/// +/// The Stop button and a force disable are handled inside PingService +/// itself (`disableAutoPing`, `forceDisableAutoPing`); this covers the +/// events that end a session without passing through there. +class ScopeLifecycle { + final void Function(String reason) _cancelHostRunner; + final void Function() _onBadgeChanged; + + bool _requestActive = false; + ScopeRunner? _live; + Object? _restoresOwner; + final List _restores = []; + final Set _knownNonContacts = {}; + int _modeSwitches = 0; + Timer? _repeaterRefreshTimer; + + /// [cancelHostRunner] cancels the runner PingService holds; + /// [onBadgeChanged] is a plain notify (the badge is not on the map). + ScopeLifecycle({ + required void Function(String reason) cancelHostRunner, + required void Function() onBadgeChanged, + }) : _cancelHostRunner = cancelHostRunner, + _onBadgeChanged = onBadgeChanged; + + /// True while a scope request is out (the Scopes badge). + bool get requestActive => _requestActive; + + /// The runner's `onActiveChanged`. + void setRequestActive(bool active) { + if (_requestActive == active) return; + _requestActive = active; + _onBadgeChanged(); + } + + /// The routes borrowed and not yet written back on [connection]. A + /// different connection starts with none. + List restoresFor(Object connection) { + _syncConnectionScopeState(connection); + return _restores; + } + + /// The pubkeys this connection's own lookups already proved are not saved + /// contacts. A different connection starts with none. + Set knownNonContactsFor(Object connection) { + _syncConnectionScopeState(connection); + return _knownNonContacts; + } + + /// Resets every per-connection scope state ([_restores], + /// [_knownNonContacts]) together the first time [connection] is seen, + /// keyed on the same owner so neither can go stale relative to the other. + void _syncConnectionScopeState(Object connection) { + if (!identical(_restoresOwner, connection)) { + _restores.clear(); + _knownNonContacts.clear(); + _restoresOwner = connection; + } + } + + /// One sweep's runner, or null when the gate is closed, an Offline Mode + /// switch is in progress, there is no connection, or there is neither a + /// device key nor a session id. + /// [create] builds it with the device key and the connection's restores. + ScopeRunner? buildRunner({ + required ScopeGateInputs gate, + required Object? connection, + required String? deviceKey, + required ScopeRunner Function(String deviceKey, + List pendingRestores, Set knownNonContacts) + create, + }) { + if (!scopeDiscoveryGateOpen(gate)) return null; + if (modeSwitching) { + debugLog('[SCOPES] No scope requests this sweep: a mode switch is ' + 'in progress'); + return null; + } + if (connection == null || deviceKey == null) return null; + final runner = create( + deviceKey, restoresFor(connection), knownNonContactsFor(connection)); + _live = runner; + return runner; + } + + /// Ends any scope work at once for [event]: the runner PingService holds + /// and the last one built here are cancelled (nothing more goes on the + /// air for them), the badge clears, the periodic repeater refresh timer + /// stops, and a lost connection takes its borrowed routes with it. + void onEvent(ScopeStopEvent event) { + _cancelHostRunner(event.reason); + final live = _live; + _live = null; + live?.cancel(event.reason); + setRequestActive(false); + stopRepeaterRefreshTimer(); + if (event.dropsConnection) { + _restores.clear(); + _knownNonContacts.clear(); + _restoresOwner = null; + } + } + + /// True while the periodic repeater-list refresh (Passive or Hybrid mode + /// running) is scheduled. + bool get repeaterRefreshTimerRunning => _repeaterRefreshTimer != null; + + /// (Re)starts the periodic repeater-list refresh: cancels any existing + /// schedule first, so calling this again while one is already running + /// reschedules it from now rather than stacking ticks. [onTick] fires + /// every [period]; this scheduling is dumb on purpose, so the caller + /// re-checks the gate, the zone and the radio preset itself on every + /// tick, exactly as the connect-time refresh does. + void startRepeaterRefreshTimer(Duration period, void Function() onTick) { + _repeaterRefreshTimer?.cancel(); + _repeaterRefreshTimer = Timer.periodic(period, (_) => onTick()); + } + + /// Stops the periodic repeater-list refresh. Idempotent. + void stopRepeaterRefreshTimer() { + _repeaterRefreshTimer?.cancel(); + _repeaterRefreshTimer = null; + } + + /// Starts an Offline Mode switch in either direction ([event] is + /// [ScopeStopEvent.offlineSwitch] or [ScopeStopEvent.onlineSwitch]): + /// ends any scope work at once, like [onEvent], and builds no runner until + /// the matching [endModeSwitch]. Called on the switch's first line, before + /// anything is awaited, because the gate still reads open while the switch + /// waits (Offline Mode is only set at its end) and a discovery window + /// closing then would otherwise start a fresh runner. + void beginModeSwitch(ScopeStopEvent event) { + _modeSwitches++; + onEvent(event); + } + + /// Ends a switch started by [beginModeSwitch]; runners are built again + /// once every switch in progress has ended. + void endModeSwitch() { + if (_modeSwitches > 0) _modeSwitches--; + } + + /// True while an Offline Mode switch is in progress. + bool get modeSwitching => _modeSwitches > 0; + + /// Called whenever a gate input changes outside the stop events: a live + /// `/auth` answer (a session recovery included) that drops or restores + /// `scope_discovery`, or the user's own switch. + /// + /// A gate that is now closed stops the periodic repeater refresh timer + /// (whether or not a request happens to be running) and cancels a live + /// runner at once, so a lease mid-exchange writes nothing more (no + /// borrow, no scope request). + /// + /// A gate that is now OPEN re-arms the periodic repeater refresh via + /// [startRepeaterRefresh] (the same mode-start sequence, 5-minute stale + /// check included) when [passiveOrHybridRunning] and no refresh is + /// already scheduled: turning scope discovery off and back on again while + /// Passive or Hybrid keeps running must not leave the refresh stopped for + /// the rest of the session, only to be caught by the mode's own next + /// start or stop. Already running (or the mode not running at all) is a + /// no-op, so an unrelated gate check does not keep rescheduling it. + void onGateChanged( + ScopeGateInputs gate, { + required bool passiveOrHybridRunning, + required void Function() startRepeaterRefresh, + }) { + if (scopeDiscoveryGateOpen(gate)) { + if (passiveOrHybridRunning && !repeaterRefreshTimerRunning) { + debugLog('[SCOPES] Scope discovery switched back on with the mode ' + 'still running: re-arming the periodic repeater refresh'); + startRepeaterRefresh(); + } + return; + } + stopRepeaterRefreshTimer(); + final live = _live; + if (live == null || live.isCancelled) return; + debugLog('[SCOPES] Scope discovery switched off with a request running'); + onEvent(ScopeStopEvent.gateClosed); + } + + /// Awaits [fetch] (started for [zone] under [preset]) and returns its + /// result only when neither the zone nor the preset moved while it was in + /// flight; null otherwise, and null when the fetch failed. + Future resultIfStillCurrent({ + required Future fetch, + required String zone, + required String? preset, + required String? Function() currentZone, + required String? Function() currentPreset, + }) async { + final T result; + try { + result = await fetch; + } catch (e) { + debugWarn('[SCOPES] Repeater list refresh failed: $e'); + return null; + } + if (!scopeRepeaterRefreshStillCurrent( + requestedZone: zone, + requestedFilterKey: preset, + currentZone: currentZone(), + currentFilterKey: currentPreset())) { + debugLog('[SCOPES] Repeater list for $zone discarded: the zone or ' + 'preset changed while it loaded'); + return null; + } + return result; + } +} diff --git a/lib/services/scope_discovery/scope_provider_support.dart b/lib/services/scope_discovery/scope_provider_support.dart new file mode 100644 index 00000000..513ce19d --- /dev/null +++ b/lib/services/scope_discovery/scope_provider_support.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; + +import '../../models/repeater.dart'; +import '../../utils/public_key.dart'; + +/// How old the repeater list may be at connect before scope discovery wants +/// it fetched again (the server's `scopes_checked_at` rides on it). +const Duration kScopeRepeaterListMaxAge = Duration(hours: 1); + +/// How old the repeater list may be when Passive or Hybrid mode starts +/// before scope discovery refreshes it right away, rather than waiting for +/// the connect-time refresh or the next periodic tick. +const Duration scopeListRefreshOnStartAge = Duration(minutes: 5); + +/// How often the repeater list is refreshed while Passive or Hybrid mode +/// keeps running, so another phone's answers (the server's +/// `scopes_checked_at`) reach this phone sooner than the connect-time +/// refresh alone would. +const Duration scopeListRefreshPeriod = Duration(minutes: 15); + +/// The server's scope stamp per repeater, keyed by the full upper-case +/// public key. Repeaters without a full key are left out. +Map scopeServerInfoMap(List repeaters) => { + for (final r in repeaters) + if (normalizePublicKey(r.hexId) case final key?) key: r.scopesCheckedAt, + }; + +/// What the server list says about [keyHex]: whether it is on the list at +/// all, and when the server last had its scopes. +({bool onList, int? checkedAt}) scopeServerInfoFor( + Map map, String keyHex) { + final key = normalizePublicKey(keyHex); + if (key == null || !map.containsKey(key)) { + return (onList: false, checkedAt: null); + } + return (onList: true, checkedAt: map[key]); +} + +/// Whether a repeater list refresh is due: scope discovery is active and +/// the list is missing or older than [maxAge] (the connect-time refresh's +/// [kScopeRepeaterListMaxAge] by default; the mode-start check passes +/// [scopeListRefreshOnStartAge] instead). +bool scopeRepeaterRefreshDue({ + required bool active, + required DateTime? loadedAt, + required DateTime now, + Duration maxAge = kScopeRepeaterListMaxAge, +}) { + if (!active) return false; + if (loadedAt == null) return true; + return now.difference(loadedAt) >= maxAge; +} + +/// What starting Passive or Hybrid mode should do about the repeater list: +/// nothing at all while scope discovery is inactive or there is no zone yet +/// (a user without scope discovery sees no change in traffic), otherwise +/// [refreshNow] fires an immediate refresh when the list is already older +/// than [scopeListRefreshOnStartAge], and [armTimer] says to start the +/// periodic refresh regardless (it has nothing to do with how stale the +/// list happens to be right now). +({bool refreshNow, bool armTimer}) scopeModeStartRefreshPlan({ + required bool active, + required String? zone, + required DateTime? loadedAt, + required DateTime now, +}) { + if (!active || zone == null || zone.isEmpty) { + return (refreshNow: false, armTimer: false); + } + final refreshNow = scopeRepeaterRefreshDue( + active: true, + loadedAt: loadedAt, + now: now, + maxAge: scopeListRefreshOnStartAge); + return (refreshNow: refreshNow, armTimer: true); +} + +/// Whether a periodic scope-discovery repeater-refresh tick should do +/// anything: scope discovery must still be active, Passive or Hybrid must +/// still be the mode running (a stray tick after a mode switch that +/// bypassed the timer's own stop must not refresh for a mode it no longer +/// serves), and there must be a known zone. +bool scopePeriodicRefreshShouldRun({ + required bool active, + required bool passiveOrHybridRunning, + required String? zone, +}) => + active && passiveOrHybridRunning && zone != null && zone.isNotEmpty; + +/// Whether replacing [before] with [after] changes anything the map draws. +/// +/// Every repeater field reaches the map (its marker, its colour, its detail +/// sheet) except the server's scope stamp, so the lists are compared field +/// for field, in order, with `scopes_checked_at` left out. A refresh that +/// only moved scope stamps must not bump the map revision. +bool scopeRefreshChangesMap(List before, List after) { + if (before.length != after.length) return true; + for (var i = 0; i < before.length; i++) { + if (_renderedJson(before[i]) != _renderedJson(after[i])) return true; + } + return false; +} + +String _renderedJson(Repeater r) => + jsonEncode(r.toJson()..remove('scopes_checked_at')); + +/// Whether a repeater list fetched for [requestedZone] under +/// [requestedFilterKey] may still be applied: neither the zone nor the +/// radio preset moved while it was in flight. +bool scopeRepeaterRefreshStillCurrent({ + required String requestedZone, + required String? requestedFilterKey, + required String? currentZone, + required String? currentFilterKey, +}) => + requestedZone == currentZone && requestedFilterKey == currentFilterKey; + +/// Decodes a stored JSON object (a string or a map), or null for anything +/// else. Never throws. +Map? decodeScopeJsonMap(Object? raw) { + try { + final value = raw is String ? jsonDecode(raw) : raw; + if (value is! Map) return null; + return { + for (final e in value.entries) + if (e.key is String) e.key as String: e.value, + }; + } catch (_) { + return null; + } +} diff --git a/lib/services/scope_discovery/scope_regions_codec.dart b/lib/services/scope_discovery/scope_regions_codec.dart new file mode 100644 index 00000000..3c1e9d35 --- /dev/null +++ b/lib/services/scope_discovery/scope_regions_codec.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import '../meshcore/protocol_constants.dart'; + +/// A repeater holds at most 32 regions, plus `*`. +const int kMaxScopeEntries = 33; + +/// `[regions][reply path len 0]`: the repeater answers zero-hop direct. +Uint8List buildRegionsRequest() => + Uint8List.fromList([AnonRequestTypes.regions, 0x00]); + +/// Parses the body of a regions reply as the connection hands it over +/// (tag already removed): `[repeater clock 4][comma-separated names]`. +/// Returns null for a malformed answer, which the caller logs and never +/// uploads. Names are kept exactly as sent: scope names are +/// case-sensitive in firmware, so nothing is trimmed or lower-cased. +/// Byte-faithful: splits at 0x2C (comma), validates each segment's bytes, +/// decodes, and preserves any leading byte-order mark (BOM, U+FEFF). +/// +/// The reply travels AES encrypted in 16-byte blocks and the companion +/// hands over whole blocks, so the names are followed by zero padding. +/// Trailing zeros are dropped; a zero anywhere before them is malformed. +List? parseRegionsReply(Uint8List data) { + if (data.length < 4) return null; + var end = data.length; + while (end > 4 && data[end - 1] == 0) { + end--; + } + final body = data.sublist(4, end); + if (body.isEmpty) return const []; + if (body.contains(0)) return null; + + // Split at byte level on 0x2C (comma) + final segments = []; + int start = 0; + for (int i = 0; i < body.length; i++) { + if (body[i] == 0x2C) { + segments.add(body.sublist(start, i)); + start = i + 1; + } + } + segments.add(body.sublist(start)); + + if (segments.length > kMaxScopeEntries) return null; + + // Validate and decode each segment + final names = []; + for (final segment in segments) { + if (!_isValidScopeTokenBytes(segment)) return null; + final String name; + try { + // Decode segment; this may drop a leading BOM + name = utf8.decode(segment); + } on FormatException { + return null; + } + // If segment starts with BOM (EF BB BF), restore it + if (segment.length >= 3 && + segment[0] == 0xEF && + segment[1] == 0xBB && + segment[2] == 0xBF) { + names.add('\u{FEFF}$name'); + } else { + names.add(name); + } + } + return names; +} + +/// Validates a scope token at the byte level: exactly [0x2A] (`*`), or +/// 1 to 30 bytes with no leading 0x23 (#), every byte one of 0x2D (-), +/// 0x24 ($), 0x23 (#), 0x30-0x39 (0-9), or >= 0x41 (A). +bool _isValidScopeTokenBytes(Uint8List bytes) { + if (bytes.length == 1 && bytes[0] == 0x2A) return true; // exactly '*' + if (bytes.isEmpty || bytes.length > 30) return false; + if (bytes[0] == 0x23) return false; // leading '#' + for (final b in bytes) { + final ok = b == 0x2D || b == 0x24 || b == 0x23 || + (b >= 0x30 && b <= 0x39) || b >= 0x41; + if (!ok) return false; + } + return true; +} + +/// The server's (and firmware's) token rule for one scope name: exactly +/// `*`, or 1 to 30 bytes with no leading `#`, every byte one of `-`, `$`, +/// `#`, `0`-`9`, or at least `A`. The server rejects a whole SCOPES item +/// for one bad entry. +bool isValidScopeToken(String name) { + if (name == '*') return true; + final bytes = utf8.encode(name); + if (bytes.isEmpty || bytes.length > 30) return false; + if (bytes.first == 0x23) return false; // leading '#' + for (final b in bytes) { + final ok = b == 0x2D || b == 0x24 || b == 0x23 || + (b >= 0x30 && b <= 0x39) || b >= 0x41; + if (!ok) return false; + } + return true; +} diff --git a/lib/services/scope_discovery/scope_runner.dart b/lib/services/scope_discovery/scope_runner.dart new file mode 100644 index 00000000..b42680e2 --- /dev/null +++ b/lib/services/scope_discovery/scope_runner.dart @@ -0,0 +1,659 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:geolocator/geolocator.dart'; + +import '../../models/scope_log_entry.dart'; +import '../../utils/debug_logger_io.dart'; +import '../../utils/public_key.dart'; +import '../meshcore/connection.dart'; +import '../meshcore/scope_lease.dart'; +import 'scope_discovery_rules.dart'; +import 'scope_regions_codec.dart'; + +/// One repeater a discovery sweep found, as the runner sees it. +/// +/// [keyHex] is the full upper-case public key, [lat]/[lon] the discovery +/// point, [localRssi]/[localSnr] the reply as this phone heard it, and +/// [discoveryReplyAfter] how long after the discovery command was submitted +/// that reply arrived (null for a reply to another phone's discovery). +typedef ScopeCandidate = ({ + String keyHex, + String repeaterId, + double lat, + double lon, + int localRssi, + double localSnr, + Duration? discoveryReplyAfter, +}); + +/// The radio as the runner uses it: one lease at a time. +abstract class ScopeRadio { + /// A short exclusive hold on the radio, or null when it was not admitted + /// within [admissionWait] or [cancel] fired first. + Future acquire( + {required Duration admissionWait, required ScopeCancelToken cancel}); +} + +/// One granted lease: the test seam over `ScopeLease`. +abstract class ScopeLeaseHandle { + /// Asks [pubkey] for its scopes (see `ScopeLease.requestScopes`). Releases + /// the lease itself before the answer wait. + Future requestScopes(Uint8List pubkey, Uint8List request, + {required Duration? answerWait, + required DateTime notAfter, + void Function(Duration wait)? onSent}); + + /// Writes a borrowed record back; true once the radio confirmed it. + Future restore(ContactRecord original); + + /// Records whose borrowed route has not been written back yet. + List get unrestored; + + /// Ends the lease now. Idempotent. + Future release(); +} + +/// [ScopeRadio] over a live [MeshCoreConnection]. +class MeshCoreScopeRadio implements ScopeRadio { + final MeshCoreConnection _connection; + + MeshCoreScopeRadio(this._connection); + + @override + Future acquire( + {required Duration admissionWait, + required ScopeCancelToken cancel}) => + _connection.acquireScopeLease( + admissionWait: admissionWait, cancel: cancel); +} + +/// One answer on its way to the upload queue. +class ScopeAnswer { + final String keyHex; + final List scopes; + + /// The discovery point. + final double lat; + final double lon; + + /// When the answer arrived (Unix seconds). + final int timestampSec; + + const ScopeAnswer({ + required this.keyHex, + required this.scopes, + required this.lat, + required this.lon, + required this.timestampSec, + }); +} + +/// What an answer's detached persistence captured when it was received, so +/// it never reads state that moved on after the runner ended. +class ScopePersistContext { + final String deviceKey; + final String? sessionId; + final int queueGeneration; + final int budgetHour; + + const ScopePersistContext({ + required this.deviceKey, + required this.sessionId, + required this.queueGeneration, + required this.budgetHour, + }); +} + +/// Runs writes one after another. A write that throws is logged and never +/// stops the next one. +class ScopeSerialWriter { + final Future Function() _write; + final String _what; + Future _chain = Future.value(); + + ScopeSerialWriter(this._what, this._write); + + /// Queues one write of the current state. Resolves when it has run. + Future schedule() { + final next = _chain.then((_) async { + try { + await _write(); + } catch (e) { + debugWarn('[SCOPES] Failed to save the $_what: $e'); + } + }); + _chain = next; + return next; + } +} + +/// Asks up to [maxAsksPerSweep] repeaters one discovery sweep found for +/// their scope list, strongest first, one at a time, in the background. +/// +/// Built per sweep. Nothing about the ping schedule waits on it: every ask +/// that would run past [hardStop] (the earliest the next discovery can go +/// out) is not started, and the runner is cancelled outright by the next +/// discovery send, every stop path and its own hard-stop timer. An answer is +/// persisted detached from the runner, so a late answer still lands in the +/// queue and the cache after the runner has ended. +class ScopeRunner { + /// At most this many asks per sweep. + static const int maxAsksPerSweep = 3; + + /// The longest answer wait for one ask. + static const Duration maxWaitPerAsk = Duration(seconds: 7); + + /// Added to the repeater's discovery reply time for its answer wait. + static const Duration discoveryReplyMargin = Duration(seconds: 2); + + /// A runner never outlives this, whatever hard stop it was given. + static const Duration maxRunnerLifetime = Duration(seconds: 30); + + /// The phone may drift this far from the discovery point and still ask. + static const double scopeMaxDriftMeters = 300; + + /// How long one ask waits to be admitted to the radio. + static const Duration leaseAdmissionWait = Duration(seconds: 3); + + /// How long the runner waits for the sweep's DISC items to be persisted. + static const Duration discPersistWait = Duration(seconds: 2); + + final ScopeRadio _radio; + final ScopeCancelToken _cancel; + final DateTime _hardStop; + final int Function() _refreshDays; + final String Function() _deviceKey; + final String? Function() _sessionId; + final int Function() _queueGeneration; + final ({bool onList, int? checkedAt}) Function(String keyHex) _serverInfo; + final ScopeQueryCache _cache; + final ScopeHourlyBudget _budget; + final Future Function(ScopeAnswer, ScopePersistContext) _enqueue; + final void Function() _onCacheStamped; + final int Function() _nowSec; + final ({double lat, double lon})? Function() _currentPosition; + final bool Function() _stillWanted; + final void Function(bool active) _onActiveChanged; + final void Function(ScopeLogEntry entry) _onLogged; + final List _pendingRestores; + final Set _knownNonContacts; + final bool Function() _cannotAskNonContacts; + + /// Set by the owner (PingService): false once this runner is no longer + /// the live one, so a late continuation never moves a newer runner's + /// badge. Always true when unset. + bool Function()? isCurrent; + + bool _active = false; + bool _started = false; + String? _stopReason; + ScopeLeaseHandle? _lease; + Timer? _hardStopTimer; + + /// The upload queue's generation when this sweep's DISC items were known + /// to be queued. Every answer of the sweep is enqueued against it, so a + /// queue cleared mid-sweep (which took those DISC items with it) refuses + /// the answers instead of queuing a SCOPES item the server would drop. + int? _sweepGeneration; + + ScopeRunner({ + required ScopeRadio radio, + required ScopeCancelToken cancel, + required DateTime hardStop, + required int Function() refreshDays, + required String Function() deviceKey, + required ({bool onList, int? checkedAt}) Function(String keyHex) + serverInfo, + required ScopeQueryCache cache, + required ScopeHourlyBudget budget, + required Future Function(ScopeAnswer, ScopePersistContext) enqueue, + required int Function() nowSec, + required ({double lat, double lon})? Function() currentPosition, + required bool Function() stillWanted, + required void Function(bool active) onActiveChanged, + required void Function(ScopeLogEntry entry) onLogged, + required List pendingRestores, + String? Function()? sessionId, + int Function()? queueGeneration, + void Function()? onCacheStamped, + Set? knownNonContacts, + bool Function()? cannotAskNonContacts, + }) : _radio = radio, + _cancel = cancel, + _hardStop = hardStop, + _refreshDays = refreshDays, + _deviceKey = deviceKey, + _sessionId = sessionId ?? (() => null), + _queueGeneration = queueGeneration ?? (() => 0), + _serverInfo = serverInfo, + _cache = cache, + _budget = budget, + _enqueue = enqueue, + _onCacheStamped = onCacheStamped ?? (() {}), + _nowSec = nowSec, + _currentPosition = currentPosition, + _stillWanted = stillWanted, + _onActiveChanged = onActiveChanged, + _onLogged = onLogged, + _pendingRestores = pendingRestores, + _knownNonContacts = knownNonContacts ?? {}, + _cannotAskNonContacts = cannotAskNonContacts ?? (() => false); + + /// True once [cancel] ran or the token fired. + bool get isCancelled => _cancel.isCancelled; + + /// Stops the runner now: the token fires (the lease checks it before + /// every write and at admission), a lease still held is released, and + /// the badge clears. Idempotent. + void cancel([String reason = 'cancelled']) { + if (_cancel.isCancelled) return; + _stopReason ??= reason; + debugLog('[SCOPES] Runner stopped: $reason'); + _cancel.cancel(); + final lease = _lease; + if (lease != null) unawaited(lease.release()); + _setActive(false); + } + + /// Runs the sweep. Never throws: an unexpected error is logged and ends + /// the runner. + Future run(List found, + {required Future discPersisted}) async { + if (_started) return; + _started = true; + try { + await _run(found, discPersisted); + } catch (e, st) { + debugError('[SCOPES] Runner failed: $e'); + debugError('[SCOPES] $st'); + } finally { + _hardStopTimer?.cancel(); + _hardStopTimer = null; + _setActive(false); + final lease = _lease; + _lease = null; + if (lease != null) { + try { + await lease.release(); + } catch (_) {} + } + } + } + + Future _run( + List found, Future discPersisted) async { + if (_cancel.isCancelled) return; + final startedAt = clock.now(); + final lifetimeEnd = startedAt.add(maxRunnerLifetime); + final hardStop = _hardStop.isBefore(lifetimeEnd) ? _hardStop : lifetimeEnd; + final untilStop = hardStop.difference(startedAt); + if (untilStop <= Duration.zero) { + _stop('hard stop already passed'); + return; + } + _hardStopTimer = Timer(untilStop, () => cancel('hard stop')); + + // The server only accepts a SCOPES item after the DISC that found the + // repeater, so the sweep's DISC items must be safely queued first. + final persisted = await _within(discPersisted, discPersistWait); + if (_cancel.isCancelled) return; + if (!persisted) { + _stop('DISC items not persisted within ' + '${discPersistWait.inSeconds}s'); + return; + } + _sweepGeneration = _queueGeneration(); + + final nowSec = _nowSec(); + final refreshDays = _refreshDays(); + final cannotAskNonContacts = _cannotAskNonContacts(); + final due = []; + var heldCount = 0; + var weakCount = 0; + var blockedCount = 0; + for (final c in found) { + final key = normalizePublicKey(c.keyHex); + if (key == null) continue; + // Filtered before the top-3 cut, not inside _ask: a known non-contact + // must never occupy a slot a weaker, askable repeater (a saved + // contact, or one not yet proven non-contact) could have used. + if (cannotAskNonContacts && _knownNonContacts.contains(key)) { + blockedCount++; + continue; + } + final info = _serverInfo(key); + final heldUntil = _cache.heldUntil(key); + if (heldUntil != null && nowSec < heldUntil) { + heldCount++; + continue; + } + // The hold has run out, but a repeater that missed is only worth + // asking again once it is heard clearly better than at the miss. + if (_cache.awaitingStrongerSignal(key, + nowSec: nowSec, rssi: c.localRssi)) { + weakCount++; + continue; + } + if (isScopeQueryDue( + onServerList: info.onList, + serverCheckedAt: info.checkedAt, + phone: _cache[key], + persistPending: _cache.pendingPersist.contains(key), + nowSec: nowSec, + refreshDays: refreshDays, + heldUntil: heldUntil)) { + due.add(c); + } + } + due.sort((a, b) { + final r = b.localRssi.compareTo(a.localRssi); + if (r != 0) return r; + final s = b.localSnr.compareTo(a.localSnr); + if (s != 0) return s; + return a.keyHex.toUpperCase().compareTo(b.keyHex.toUpperCase()); + }); + final chosen = due.take(maxAsksPerSweep).toList(); + debugLog('[SCOPES] Sweep: found ${found.length}, due ${due.length}, ' + 'held $heldCount, weak $weakCount, blocked $blockedCount, ' + 'chosen ${chosen.map((c) => _prefix(c.keyHex)).join(', ')}'); + + for (final c in chosen) { + if (!await _ask(c, hardStop)) return; + } + } + + /// One ask. False when the runner should stop. + Future _ask(ScopeCandidate c, DateTime hardStop) async { + final key = normalizePublicKey(c.keyHex)!; + final label = _prefix(key); + final wait = _waitFor(c); + if (!_mayAsk(c)) return false; + final needed = leaseAdmissionWait + kScopeLeaseHold + wait; + if (clock.now().add(needed).isAfter(hardStop)) { + _stop('the ask to $label would run past the next discovery'); + return false; + } + + _setActive(true); + final lease = await _radio.acquire( + admissionWait: leaseAdmissionWait, cancel: _cancel); + if (lease == null) { + _setActive(false); + if (!_cancel.isCancelled) _stop('radio not admitted for $label'); + return false; + } + _lease = lease; + if (_cancel.isCancelled) return false; + if (!_stillWanted()) { + _stop('no longer wanted'); + return false; + } + // The lease holds for at most kScopeLeaseHold, and the answer wait + // starts no later than that, so this is the last point the ask can be + // shown to finish before the hard stop. + if (clock.now().add(kScopeLeaseHold + wait).isAfter(hardStop)) { + _stop('admission for $label came too late for the next discovery'); + return false; + } + + // Routes borrowed by an earlier runner on this connection go back + // before anything else is written. + for (final record in List.of(_pendingRestores)) { + if (_cancel.isCancelled) return false; + if (await lease.restore(record)) { + _pendingRestores.removeWhere( + (r) => _sameBytes(r.publicKey, record.publicKey)); + } + } + if (_cancel.isCancelled) return false; + + final outcome = await lease.requestScopes( + _bytes(key), buildRegionsRequest(), + answerWait: c.discoveryReplyAfter == null ? null : wait, + notAfter: hardStop); + _lease = null; + _keepUnrestored(lease, outcome); + _setActive(false); + + switch (outcome) { + case ScopeAnswered(:final body, :final receivedAt): + if (_cancel.isCancelled) return false; + _handleAnswer(c, key, body, receivedAt); + return !_cancel.isCancelled; + case ScopeNoAnswer(): + if (_cancel.isCancelled) return false; + debugLog('[SCOPES] $label: no response'); + _cache.recordNoAnswer(key, _nowSec(), rssi: c.localRssi); + _log(c, key, ScopeLogOutcome.noResponse); + return true; + case ScopeFlooded(): + debugLog('[SCOPES] $label: flooded by the radio'); + _log(c, key, ScopeLogOutcome.flooded); + return !_cancel.isCancelled; + case ScopeRadioError(:final code, :final nonContactTableFull): + debugLog('[SCOPES] $label: radio error $code'); + if (nonContactTableFull) { + _knownNonContacts.add(key); + _log(c, key, ScopeLogOutcome.radioContactsFull); + } else { + _log(c, key, ScopeLogOutcome.radioError); + } + return !_cancel.isCancelled; + case ScopeLocalFailure(:final why): + _stop('local failure asking $label ($why)'); + return false; + case ScopeAborted(): + if (!_cancel.isCancelled) _stop('ask to $label aborted'); + return false; + case ScopeNonContactRefused(): + debugLog('[SCOPES] $label: not a contact and this connection cannot ' + 'ask non-contacts, nothing sent'); + _knownNonContacts.add(key); + return !_cancel.isCancelled; + } + } + + void _handleAnswer( + ScopeCandidate c, String key, Uint8List body, DateTime receivedAt) { + final label = _prefix(key); + final receivedSec = receivedAt.millisecondsSinceEpoch ~/ 1000; + final names = parseRegionsReply(body); + if (names == null) { + debugLog('[SCOPES] $label: unreadable answer (${body.length} bytes)'); + _log(c, key, ScopeLogOutcome.malformed, at: receivedAt); + return; + } + // It parsed: the repeater proved it is reachable right now, whatever + // happens to the upload below. Clearing the hold here, not only once + // persistence succeeds, means a failed save never leaves the miss count + // in place for the next ask to double from. + _cache.clearHold(key); + final deviceKey = _deviceKey(); + if (!_budget.tryConsume(deviceKey, receivedSec)) { + debugLog('[SCOPES] $label: answered [${names.join(', ')}], withheld ' + '(hourly cap)'); + _log(c, key, ScopeLogOutcome.withheldHourlyCap, + at: receivedAt, scopes: names); + return; + } + debugLog('[SCOPES] $label: answered [${names.join(', ')}]'); + _log(c, key, ScopeLogOutcome.answered, at: receivedAt, scopes: names); + final answer = ScopeAnswer( + keyHex: key, + scopes: List.unmodifiable(names), + lat: c.lat, + lon: c.lon, + timestampSec: receivedSec); + final ctx = ScopePersistContext( + deviceKey: deviceKey, + sessionId: _sessionId(), + queueGeneration: _sweepGeneration ?? _queueGeneration(), + budgetHour: receivedSec ~/ 3600); + unawaited(_persist(answer, ctx)); + } + + /// Detached: reserves the hour durably, queues the answer, and stamps the + /// cache only once the queue accepted it. Touches no runner, badge, timer + /// or schedule state, so it may finish long after the runner ended. + Future _persist(ScopeAnswer answer, ScopePersistContext ctx) async { + final key = answer.keyHex; + final label = _prefix(key); + _cache.pendingPersist.add(key); + try { + final reserved = + await _budget.persistReservation(ctx.deviceKey, ctx.budgetHour); + if (!reserved) { + debugWarn('[SCOPES] $label: hour reservation not saved, answer ' + 'dropped'); + return; + } + final accepted = await _enqueue(answer, ctx); + if (!accepted) { + debugWarn('[SCOPES] $label: answer not queued, dropped'); + return; + } + _cache.recordAnswer(key, answer.timestampSec); + _onCacheStamped(); + debugLog('[SCOPES] $label: answer queued'); + } catch (e) { + debugError('[SCOPES] $label: persisting the answer failed: $e'); + } finally { + _cache.pendingPersist.remove(key); + } + } + + /// The checks every ask passes before it starts. + bool _mayAsk(ScopeCandidate c) { + if (_cancel.isCancelled) return false; + if (!_stillWanted()) { + _stop('no longer wanted'); + return false; + } + final deviceKey = _deviceKey(); + if (!_budget.canAsk(deviceKey, _nowSec())) { + _stop('hourly cap reached'); + return false; + } + if (_cache.pendingPersist.length >= ScopeQueryCache.maxPendingPersist) { + _stop('too many answers still being saved'); + return false; + } + final here = _currentPosition(); + if (here != null) { + final drift = + Geolocator.distanceBetween(c.lat, c.lon, here.lat, here.lon); + if (drift > scopeMaxDriftMeters) { + _stop('moved ${drift.round()}m from the discovery point'); + return false; + } + } + return true; + } + + /// The answer wait for [c]: its discovery reply time plus the margin, + /// capped; the cap when the reply time is unknown (the radio's estimate is + /// only known after SENT, so the cap is what is reserved). + static Duration _waitFor(ScopeCandidate c) { + final after = c.discoveryReplyAfter; + if (after == null) return maxWaitPerAsk; + final wait = after + discoveryReplyMargin; + return wait > maxWaitPerAsk ? maxWaitPerAsk : wait; + } + + /// Keeps every record the lease could not write back, for the next runner + /// on this connection. + void _keepUnrestored(ScopeLeaseHandle lease, ScopeRequestOutcome outcome) { + final owed = [ + ...lease.unrestored, + if (outcome.restoreOwed && outcome.borrowedFrom != null) + outcome.borrowedFrom!, + ]; + for (final record in owed) { + if (_pendingRestores + .any((r) => _sameBytes(r.publicKey, record.publicKey))) { + continue; + } + _pendingRestores.add(record); + debugLog('[SCOPES] Route to ${_prefix(_hexOf(record.publicKey))} ' + 'kept for a later restore'); + } + } + + void _log(ScopeCandidate c, String key, ScopeLogOutcome outcome, + {DateTime? at, List? scopes}) { + try { + _onLogged(ScopeLogEntry( + timestamp: at ?? clock.now(), + latitude: c.lat, + longitude: c.lon, + repeaterId: c.repeaterId, + pubkeyHex: key, + outcome: outcome, + scopes: scopes)); + } catch (e) { + debugError('[SCOPES] Log entry failed: $e'); + } + } + + void _stop(String reason) { + if (_stopReason != null) return; + _stopReason = reason; + debugLog('[SCOPES] Runner stopped: $reason'); + } + + /// Moves the badge. After a cancel nothing moves it again, and a runner + /// that is no longer current never moves it at all. + void _setActive(bool active) { + if (_active == active) return; + if (active && _cancel.isCancelled) return; + _active = active; + final current = isCurrent?.call() ?? true; + if (!current) return; + try { + _onActiveChanged(active); + } catch (e) { + debugError('[SCOPES] Badge update failed: $e'); + } + } + + /// Resolves true when [f] completes within [limit], false on a timeout, + /// an error or a cancel. + Future _within(Future f, Duration limit) { + final done = Completer(); + final timer = Timer(limit, () { + if (!done.isCompleted) done.complete(false); + }); + f.then((_) { + if (!done.isCompleted) done.complete(true); + }, onError: (Object e) { + debugWarn('[SCOPES] DISC items failed to persist: $e'); + if (!done.isCompleted) done.complete(false); + }); + _cancel.whenCancelled.then((_) { + if (!done.isCompleted) done.complete(false); + }); + return done.future.whenComplete(timer.cancel); + } + + static Uint8List _bytes(String hex) => Uint8List.fromList([ + for (var i = 0; i < hex.length; i += 2) + int.parse(hex.substring(i, i + 2), radix: 16), + ]); + + static String _hexOf(Uint8List b) => + b.map((x) => x.toRadixString(16).padLeft(2, '0')).join().toUpperCase(); + + static bool _sameBytes(Uint8List a, Uint8List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + + /// Public keys are logged as an 8-character prefix only. + static String _prefix(String keyHex) => + keyHex.length <= 8 ? keyHex : keyHex.substring(0, 8); +} diff --git a/lib/services/session_recovery_join.dart b/lib/services/session_recovery_join.dart new file mode 100644 index 00000000..1c7b29d7 --- /dev/null +++ b/lib/services/session_recovery_join.dart @@ -0,0 +1,44 @@ +/// What a `session_expired` answer should do when it arrives while a +/// replacement session may already be under way. +enum SessionRecoveryJoin { + /// A recovery is running: hand its future back, the caller waits on it. + joinInFlight, + + /// A group handoff owns the recovery slot. Its drain uploads under the old + /// session, and that upload is the lane asking; handing it the handoff's + /// own future would make the two wait on each other for good. Answer + /// `superseded` at once: the upload comes back held (no retry spent), the + /// keepalive and the preflight bow out, and the handoff mints the + /// replacement itself. + supersededByHandoff, + + /// Nothing is running: start a recovery. + startNew, +} + +/// Pure rule behind `AppStateProvider._recoverExpiredLiveSession`. The +/// handoff test comes first: while it holds the slot, the in-flight future IS +/// the handoff, so a joiner must never be handed it. +SessionRecoveryJoin resolveSessionRecoveryJoin({ + required bool groupHandoffOwnsSlot, + required bool recoveryInFlight, +}) { + if (groupHandoffOwnsSlot) return SessionRecoveryJoin.supersededByHandoff; + if (recoveryInFlight) return SessionRecoveryJoin.joinInFlight; + return SessionRecoveryJoin.startNew; +} + +/// Whether the session check a Start or a manual ping runs first +/// (`AppStateProvider._checkSessionBeforeAction`) waits for the in-flight +/// session swap before it asks. Only a group handoff: it releases the old +/// session before it mints the new one, and for those two round trips the +/// held id is null, which `checkSessionValid` answers `no_session`, so a +/// tap, a Start or a Siri/watch Start landing there was refused with +/// "session has ended" for a session that was only moving. An ordinary +/// expiry recovery keeps the old id in place until its mint lands, and the +/// check joins it through `session_expired` anyway. +bool sessionCheckWaitsForHandoff({ + required bool groupHandoffOwnsSlot, + required bool recoveryInFlight, +}) => + groupHandoffOwnsSlot && recoveryInFlight; diff --git a/lib/services/status/android_notification.dart b/lib/services/status/android_notification.dart index ef7d81da..1a794503 100644 --- a/lib/services/status/android_notification.dart +++ b/lib/services/status/android_notification.dart @@ -23,3 +23,22 @@ import '../../providers/app_state_provider.dart' show AutoMode; }; return (title: 'MeshMapper - ${mode.displayName} Mode', body: body); } + +/// The notification while a radio is connected and no mode runs. The Android +/// session service shows a notification for the whole connection, not only +/// while a mode runs, so this is what it reads between modes. +({String title, String body}) androidConnectedNotificationContent({ + required String radioName, +}) => + (title: 'MeshMapper - Connected', body: 'Connected to $radioName'); + +/// The notification from the Connect tap until the radio is connected. The +/// session service starts at the tap, so it must not claim a connection yet, +/// nor name the radio last connected, which may not be the one being reached. +({String title, String body}) androidConnectingNotificationContent() => + (title: 'MeshMapper - Connecting', body: 'Connecting to your radio'); + +/// The notification while the zone grace period looks for a zone to move to. +/// The radio stays connected through it, so the service keeps running. +({String title, String body}) androidZoneGraceNotificationContent() => + (title: 'MeshMapper - Outside zone', body: 'Searching for a nearby zone'); diff --git a/lib/utils/compact_count.dart b/lib/utils/compact_count.dart new file mode 100644 index 00000000..916dcb90 --- /dev/null +++ b/lib/utils/compact_count.dart @@ -0,0 +1,19 @@ +/// A count short enough for a status bar chip. +/// +/// Under 1000 the count is shown as it is. From 1000 it becomes `k` and from +/// one million `M`, with one decimal while the leading part is a single digit +/// ("1.4k", "9.9M") and none above ("12k", "999k", "12M"). The decimal is +/// truncated, never rounded, so the chip never reads higher than the real +/// count (rounding would turn 9999 into "10.0k" and 999999 into "1000k"). +String formatCompactCount(int count) { + if (count < 1000) return '$count'; + if (count < 1000000) return _scaled(count, 1000, 'k'); + return _scaled(count, 1000000, 'M'); +} + +String _scaled(int count, int unit, String suffix) { + final whole = count ~/ unit; + if (whole >= 10) return '$whole$suffix'; + final tenth = (count % unit) * 10 ~/ unit; + return '$whole.$tenth$suffix'; +} diff --git a/lib/utils/coverage_refresh.dart b/lib/utils/coverage_refresh.dart new file mode 100644 index 00000000..7643a5ea --- /dev/null +++ b/lib/utils/coverage_refresh.dart @@ -0,0 +1,27 @@ +import '../models/api_queue_item.dart'; + +/// Whether an uploaded item of [type] can change a coverage tile. +/// +/// A DEFER is kept in a server table nothing renders, and a SCOPES is a +/// repeater's answer about its scopes, not a coverage row. Neither moves a +/// cell, so neither is worth a fresh-tile check. +bool changesCoverage(String type) => type != 'DEFER' && type != 'SCOPES'; + +/// What an uploaded batch asks of the post-upload fresh-tile check: +/// whether it arms one at all, and which fixes to add to the pending list +/// (at most [cap] in total, counting the [alreadyPending] ones). +({bool armsRefresh, List> coords}) coverageRefreshFor( + Iterable items, { + required int alreadyPending, + int cap = 16, +}) { + var arms = false; + final coords = >[]; + for (final item in items) { + if (!changesCoverage(item.type)) continue; + arms = true; + if (alreadyPending + coords.length >= cap) continue; + coords.add([item.latitude, item.longitude]); + } + return (armsRefresh: arms, coords: coords); +} diff --git a/lib/utils/coverage_summary.dart b/lib/utils/coverage_summary.dart index 1f6ee6ce..60b36b61 100644 --- a/lib/utils/coverage_summary.dart +++ b/lib/utils/coverage_summary.dart @@ -766,6 +766,48 @@ List repeaterCoverageCells( return cells.values.toList(); } +/// One dashed coverage line, from a shared start point out to ([lat],[lon]), +/// in [color] (a hex string). +typedef CoverageLineSegment = ({double lat, double lon, String color}); + +/// The coverage lines drawn for a selected repeater (Feature B): one per +/// coverage cell, from the repeater at ([lat],[lon]) to the cell centre. The +/// map keeps them while the repeater stays selected so the Repeater Coverage +/// Lines switch can redraw or clear them without a reselect (web +/// `mmRedrawSelectedCoverage` parity). +class RepeaterCoverageLines { + final String repeaterId; // full identity of the selected repeater + final double lat; + final double lon; + final List segments; + + const RepeaterCoverageLines({ + required this.repeaterId, + required this.lat, + required this.lon, + required this.segments, + }); + + /// The segments to draw with the switch at [show]. Empty clears the layer. + List visible(bool show) => show ? segments : const []; +} + +/// What flipping the Repeater Coverage Lines switch to [show] does to the +/// lines layer: the segments to push (empty clears it), or null to leave the +/// layer alone. Null when no repeater coverage is on the map ([drawn] null), +/// when it belongs to a repeater other than [selectedRepeaterId], or when a +/// tapped tile is open ([tileSelected]): the layer is shared with the tile +/// fan-out, which the switch does not cover. +List? repeaterCoverageLinesAfterSwitch( + RepeaterCoverageLines? drawn, + {required bool show, + required String? selectedRepeaterId, + required bool tileSelected}) { + if (drawn == null || tileSelected) return null; + if (drawn.repeaterId != selectedRepeaterId) return null; + return drawn.visible(show); +} + // --- cell fan-out endpoints (Feature A) -------------------------------------- /// One repeater endpoint that heard a ping in a tapped cell, ready to render as diff --git a/lib/utils/debouncer.dart b/lib/utils/debouncer.dart new file mode 100644 index 00000000..0056db65 --- /dev/null +++ b/lib/utils/debouncer.dart @@ -0,0 +1,38 @@ +import 'dart:async'; + +/// Runs the latest scheduled action once things have been quiet for [delay]. +/// +/// Each [schedule] replaces the pending action and restarts the wait, so a +/// burst of changes ends in one call with the newest action. [flush] runs a +/// pending action now (used when the app goes to the background, where the +/// process may be killed before the timer fires); [cancel] drops it. +class Debouncer { + Debouncer(this.delay); + + final Duration delay; + Timer? _timer; + void Function()? _pending; + + /// True while an action is waiting to run. + bool get isPending => _pending != null; + + void schedule(void Function() action) { + _pending = action; + _timer?.cancel(); + _timer = Timer(delay, flush); + } + + void flush() { + _timer?.cancel(); + _timer = null; + final action = _pending; + _pending = null; + action?.call(); + } + + void cancel() { + _timer?.cancel(); + _timer = null; + _pending = null; + } +} diff --git a/lib/utils/gps_marker_colors.dart b/lib/utils/gps_marker_colors.dart new file mode 100644 index 00000000..e0046136 --- /dev/null +++ b/lib/utils/gps_marker_colors.dart @@ -0,0 +1,69 @@ +import 'package:flutter/painting.dart'; + +/// The fill colours one GPS position marker is painted with. +/// +/// Every marker style has a white outline and a [body] fill; the car's +/// windshield and the dog's ear use [shade], the boat's sail uses [light]. +class GpsMarkerColors { + /// Main fill. + final Color body; + + /// Darker detail drawn on top of [body]. + final Color shade; + + /// Lighter detail drawn beside [body]. + final Color light; + + const GpsMarkerColors({ + required this.body, + required this.shade, + required this.light, + }); + + /// Stored value of the default colour. + static const String defaultChoice = 'default'; + + /// Stored value of the green colour. + static const String greenChoice = 'green'; + + /// Every colour choice, in picker order. + static const List choices = [defaultChoice, greenChoice]; + + /// Material blue, the colour every style but Chomper has always used. + static const blue = GpsMarkerColors( + body: Color(0xFF2196F3), + shade: Color(0xFF1565C0), + light: Color(0xFF64B5F6), + ); + + /// Chomper's own default: cyan. + static const cyan = GpsMarkerColors( + body: Color(0xFF00BCD4), + shade: Color(0xFF00838F), + light: Color(0xFF4DD0E1), + ); + + /// A dark Material green. Darker than the pale green of a bidirectional + /// coverage square (`#7EE094`), so the marker stands apart from the + /// coverage under it by lightness as well as by its white outline. Like the + /// blue, it does not change with Color Vision: it is the user's own pick, + /// not a semantic colour, and the white outline separates it from the + /// coverage under any palette. + static const green = GpsMarkerColors( + body: Color(0xFF388E3C), + shade: Color(0xFF1B5E20), + light: Color(0xFF81C784), + ); + + /// A stored choice, with anything unknown (a missing value, or one a newer + /// version wrote) read as [defaultChoice]. + static String normalize(String? choice) => + choices.contains(choice) ? choice! : defaultChoice; + + /// The colours [style] is painted with for [choice]. The default keeps each + /// style's own colour: blue, or cyan for Chomper. + static GpsMarkerColors forStyle(String style, String choice) { + if (normalize(choice) == greenChoice) return green; + return style == 'chomper' ? cyan : blue; + } +} diff --git a/lib/utils/marker_data_version.dart b/lib/utils/marker_data_version.dart new file mode 100644 index 00000000..1eab1481 --- /dev/null +++ b/lib/utils/marker_data_version.dart @@ -0,0 +1,20 @@ +/// Hash inputs for the map's marker data version. +/// +/// The map pin lists are capped rolling FIFOs: once full, every add evicts one +/// entry, so the length stops changing. A version built from lengths alone then +/// misses a new pin whenever the evicted and added entries carry the same echo +/// or node counts (a dead area: zero and zero), and the map never draws it. +/// +/// This signature folds in the IDENTITY of both ends of the list, so an add at +/// either end and an eviction at either end each change it. O(1): it reads the +/// length and two elements, never walks the list. The ping and log entry +/// classes do not override `==`, so `identityHashCode` is used explicitly to +/// keep that guarantee even if one ever gains value equality. +int cappedListSignature(List list) { + if (list.isEmpty) return 0; + return Object.hash( + list.length, + identityHashCode(list.first), + identityHashCode(list.last), + ); +} diff --git a/lib/utils/mvt_cells.dart b/lib/utils/mvt_cells.dart index 1ded7855..84bb3621 100644 --- a/lib/utils/mvt_cells.dart +++ b/lib/utils/mvt_cells.dart @@ -2,11 +2,16 @@ import 'dart:typed_data'; /// Minimal decoder for MeshMapper's coverage vector tiles (vector_tile.php) — /// just enough of the MVT/protobuf wire format to extract each cell's -/// `{id, i, j, st}`. Geometry is skipped entirely: a cell's rectangle is +/// `{id, i, j, st, k}`. Geometry is skipped entirely: a cell's rectangle is /// reconstructed from its grid indices (i, j) and the grid step table, which /// is byte-identical to what the server encoded (both compute corners from /// indices). Contract reference: MeshMapper_Server/docs/VECTOR_TILES.md. /// +/// Coverage format 2 (`cf=2` on the request): a feature may carry `k`, which +/// makes it a BLOCK of k by k 300 m cells whatever gsize was asked for. Its +/// (i, j) are block indices on the 300 m steps times k. Use +/// [CoverageCell.bounds] to get a rectangle, never the raw grid steps. +/// /// WEB-SAFE BY DESIGN: feature ids run up to ~2^42 and dart2js truncates /// bitwise ops to 32 bits, so varint/zigzag decoding here uses arithmetic /// (`*`, `~/`, `%`) only — same rule as WireTagCodec. @@ -19,16 +24,77 @@ const Map> kCoverageGridSteps = { 100: [0.0009, 0.00128], }; +/// The coverage tile format this app understands, sent as `cf` on every +/// vector_tile.php request. 2 = any feature may carry `k` (a block of k by k +/// 300 m cells), at any zoom. Absent means format 1, today's fine cells. +const int kCoverageTileFormat = 2; + /// One coverage cell from a decoded tile. `st` is the server's status /// category (1=green 2=cyan 3=orange 4=purple 5=grey 6=red). +/// +/// [k] is null for a plain cell of the requested grid. When set, the feature +/// is a block of k by k 300 m cells and (i, j) index blocks, not cells. class CoverageCell { final int id; final int i; final int j; final int st; - const CoverageCell(this.id, this.i, this.j, this.st); + final int? k; + const CoverageCell(this.id, this.i, this.j, this.st, [this.k]); + + /// True when this feature is a zoomed-out block rather than a grid cell. + bool get isBlock => k != null; + + /// `[lat0, lon0, latStep, lonStep]` of this feature's rectangle. A block + /// always sits on the 300 m steps times k; a plain cell on [gridSize]'s + /// steps (falling back to 300 m for an unknown size). + List bounds(int gridSize) { + final k = this.k; + final double latStep; + final double lonStep; + if (k != null) { + final s300 = kCoverageGridSteps[300]!; + latStep = s300[0] * k; + lonStep = s300[1] * k; + } else { + final s = kCoverageGridSteps[gridSize] ?? kCoverageGridSteps[300]!; + latStep = s[0]; + lonStep = s[1]; + } + return [i * latStep, j * lonStep, latStep, lonStep]; + } } +/// The base coverage layer's SHOW filter while a session patch exists: +/// show a feature when it is a block (carries `k`) OR its `"i_j"` is not one +/// of the patched [keys]. A block's i/j are block indices, so matching it +/// against a fine cell's key would hide a block that has nothing to do with +/// the patch. Writing it as `all[!has(k), ...]` instead would hide every +/// block whenever any patch exists. +List coveragePatchBaseFilter(List keys) => [ + 'any', + ['has', 'k'], + [ + '!', + [ + 'in', + [ + 'concat', + [ + 'to-string', + ['get', 'i'] + ], + '_', + [ + 'to-string', + ['get', 'j'] + ], + ], + ['literal', keys], + ], + ], + ]; + class _Reader { final Uint8List buf; int pos = 0; @@ -117,16 +183,20 @@ List _decodeLayer(_Reader layer) { _skip(f, wire); } } - int? i, j, st; + int? i, j, st, k; for (var t = 0; t + 1 < tags.length; t += 2) { final key = tags[t] < keys.length ? keys[tags[t]] : ''; final value = tags[t + 1] < values.length ? values[tags[t + 1]] : 0; if (key == 'i') i = value; if (key == 'j') j = value; if (key == 'st') st = value; + if (key == 'k') k = value; } + // A block size that is not a positive int cannot be drawn or keyed, so + // the feature is dropped like any other unreadable one. + if (k != null && k < 1) continue; if (i != null && j != null && st != null) { - cells.add(CoverageCell(id, i, j, st)); + cells.add(CoverageCell(id, i, j, st, k)); } } return cells; diff --git a/lib/utils/ping_colors.dart b/lib/utils/ping_colors.dart index a96b34d5..c1ab419e 100644 --- a/lib/utils/ping_colors.dart +++ b/lib/utils/ping_colors.dart @@ -26,6 +26,11 @@ class ColorPalette { final Color traceSuccess; final Color noResponse; final Color deferred; + final Color scopes; + + /// [scopes] for text on a light card (`#F8FAFC`): the same hue, darker, + /// so the SCP label and scope-name chips stay readable in the light theme. + final Color scopesOnLight; // Signal quality (SNR/RSSI) traffic-light final Color signalGood; @@ -65,6 +70,8 @@ class ColorPalette { required this.traceSuccess, required this.noResponse, required this.deferred, + required this.scopes, + required this.scopesOnLight, required this.signalGood, required this.signalMedium, required this.signalBad, @@ -106,6 +113,8 @@ class ColorPalettes { discFail: Color(0xFF9E9E9E), traceSuccess: Color(0xFF00BCD4), noResponse: Color(0xFF9E9E9E), + scopes: Color(0xFFF59E0B), // Amber: distinct from every other log accent + scopesOnLight: Color(0xFFB45309), // Amber 700 signalGood: Colors.green, signalMedium: Colors.orange, signalBad: Colors.red, @@ -138,6 +147,8 @@ class ColorPalettes { discFail: Color(0xFF9E9E9E), // Grey (unchanged) traceSuccess: Color(0xFF009E73), // Wong bluish green noResponse: Color(0xFF9E9E9E), // Grey (unchanged) + scopes: Color(0xFFE69F00), // Wong orange + scopesOnLight: Color(0xFFA35F00), // Wong orange, darkened signalGood: Color(0xFF0072B2), // Blue signalMedium: Color(0xFFF0E442), // Wong yellow signalBad: Color(0xFFD55E00), // Vermillion @@ -170,6 +181,8 @@ class ColorPalettes { discFail: Color(0xFF9E9E9E), // Grey (unchanged) traceSuccess: Color(0xFFD55E00), // Vermillion (replaces cyan) noResponse: Color(0xFF9E9E9E), // Grey (unchanged) + scopes: Color(0xFF56B4E9), // Wong sky blue + scopesOnLight: Color(0xFF0B6FA4), // Wong sky blue, darkened signalGood: Color(0xFF009E73), // Bluish green signalMedium: Color(0xFFE69F00), // Orange signalBad: Color(0xFFD55E00), // Vermillion @@ -202,6 +215,8 @@ class ColorPalettes { discFail: Color(0xFF757575), // Medium-dark traceSuccess: Color(0xFF757575), // Medium-dark noResponse: Color(0xFF616161), // Dark + scopes: Color(0xFFCFCFCF), // Light-medium, distinct from every other tone + scopesOnLight: Color(0xFF5C5C5C), // Dark, for the light card signalGood: Color(0xFFE0E0E0), // Light signalMedium: Color(0xFF9E9E9E), // Medium signalBad: Color(0xFF424242), // Very dark @@ -266,6 +281,14 @@ class PingColors { static Color get traceSuccess => _activePalette.traceSuccess; static Color get noResponse => _activePalette.noResponse; static Color get deferred => _activePalette.deferred; + static Color get scopes => _activePalette.scopes; + + /// The scope accent for text drawn on a card of [brightness]: [scopes] on + /// a dark card, the palette's darker `scopesOnLight` on a light one. + static Color scopesFor(Brightness brightness) => + brightness == Brightness.light + ? _activePalette.scopesOnLight + : _activePalette.scopes; // ── Signal quality (SNR/RSSI traffic-light) ── static Color get signalGood => _activePalette.signalGood; diff --git a/lib/utils/repeater_nicknames.dart b/lib/utils/repeater_nicknames.dart new file mode 100644 index 00000000..06b6b315 --- /dev/null +++ b/lib/utils/repeater_nicknames.dart @@ -0,0 +1,203 @@ +/// Personal repeater nicknames: the pure store and resolution rules. +/// +/// A nickname is a short label the user gives one repeater (for example "Mell" +/// for the repeater whose key starts 5007). It lives only on the phone, keyed +/// by the repeater's FULL public key (the one stable identity a repeater has), +/// and takes priority over the server's name wherever a heard repeater is named +/// on the Top Heard overlay, the Live Activity, the Watch and Siri. +/// +/// **A nickname is shown only when the heard ID resolves to exactly one +/// repeater.** A short path hash routinely matches several repeaters, and a +/// confidently wrong name is worse than none. +library; + +import 'package:flutter/widgets.dart' show StringCharacters; + +import '../models/repeater.dart'; +import '../services/external_surfaces/geo/external_surface_geo_builder.dart'; +import 'public_key.dart'; + +/// One saved nickname, with a snapshot of the repeater it was given to. +/// +/// [name] and [hex] are captured when the nickname is saved so a Settings list +/// can still describe a repeater that is not in the current zone's catalogue. +/// They are display-only and never used to match a heard ID. +class RepeaterNickname { + const RepeaterNickname({ + required this.nickname, + required this.name, + required this.hex, + }); + + /// The user's short label, already through + /// [RepeaterNicknames.normalizeNickname]. + final String nickname; + + /// The server's repeater name at save time. + final String name; + + /// `Repeater.displayHexId()` at save time. + final String hex; + + @override + bool operator ==(Object other) => + other is RepeaterNickname && + other.nickname == nickname && + other.name == name && + other.hex == hex; + + @override + int get hashCode => Object.hash(nickname, name, hex); + + @override + String toString() => 'RepeaterNickname($nickname, $name, $hex)'; +} + +/// Static helpers over a nickname map keyed by upper-case 64-hex public key. +class RepeaterNicknames { + const RepeaterNicknames._(); + + /// The longest nickname, in user-perceived characters. + static const int maxLength = 8; + + /// [raw] trimmed, with every run of whitespace collapsed to one space and + /// capped at [maxLength] characters, or null when nothing is left. + /// + /// The cap counts user-perceived characters (grapheme clusters), so an emoji + /// or an accented letter is never cut in half. A cap that lands on a space + /// is trimmed again so the result is stable under a second pass. + /// + /// Zero-width spaces, word joiners and byte-order marks are dropped, and a + /// nickname of nothing but format characters (joiners, direction marks) is + /// blank: pasted, it would save a label nobody can see. Joiners inside an + /// emoji sequence are kept. + static String? normalizeNickname(String? raw) { + if (raw == null) return null; + final collapsed = + raw.replaceAll(_zeroWidth, '').trim().replaceAll(RegExp(r'\s+'), ' '); + final capped = collapsed.characters.take(maxLength).toString().trim(); + if (capped.replaceAll(_format, '').trim().isEmpty) return null; + return capped; + } + + static final RegExp _zeroWidth = RegExp('[\u200B\u2060\uFEFF]'); + static final RegExp _format = RegExp(r'\p{Cf}', unicode: true); + + /// The nicknames persisted in Hive: a map of key to a map holding + /// `nickname`, `name` and `hex`. + /// + /// Keys are stored in normalized form. An entry whose key is not a full + /// public key, or whose nickname is blank, is dropped. Anything that is not + /// a map, or a field that is not a string, is tolerated rather than thrown + /// on, so a corrupt box can never stop the app starting. + static Map sanitize(Object? raw) { + if (raw is! Map) return const {}; + final out = {}; + for (final entry in raw.entries) { + final key = entry.key; + final value = entry.value; + if (key is! String || value is! Map) continue; + final normalizedKey = normalizePublicKey(key); + if (normalizedKey == null) continue; + final rawNickname = value['nickname']; + final nickname = + rawNickname is String ? normalizeNickname(rawNickname) : null; + if (nickname == null) continue; + final name = value['name']; + final hex = value['hex']; + out[normalizedKey] = RepeaterNickname( + nickname: nickname, + name: name is String ? name : '', + // A damaged entry still shows an ID in the Settings list: the key's + // first four characters, the same fallback setRepeaterNicknameByKey + // uses. + hex: hex is String && hex.trim().isNotEmpty + ? hex + : normalizedKey.substring(0, 4), + ); + } + return out; + } + + /// [nicknames] as plain maps, the shape [sanitize] reads back from Hive. + static Map> toStorage( + Map nicknames, + ) => + { + for (final entry in nicknames.entries) + entry.key: { + 'nickname': entry.value.nickname, + 'name': entry.value.name, + 'hex': entry.value.hex, + }, + }; + + /// The nickname saved for [repeater], matched on its full public key, or + /// null when it has none or its `hexId` is not a full key (a repeater with an + /// empty or short `hexId` can never be told apart from another one). + static String? nicknameFor( + Repeater repeater, + Map nicknames, + ) { + final key = normalizePublicKey(repeater.hexId); + return key == null ? null : nicknames[key]?.nickname; + } + + /// [name], the server's repeater name, cut to [maxLength] user-perceived + /// characters for a label with `…` appended when it was cut, or null when + /// [name] is blank. + /// + /// Cleaned like [normalizeNickname] first: zero-width characters dropped, + /// whitespace runs collapsed to one space, and a name of nothing but format + /// characters is blank. A name of [maxLength] characters or fewer is + /// returned with no ellipsis. The cut counts grapheme clusters, so an emoji + /// or an accented letter is never split. + static String? shortenServerName(String name) { + final trimmed = + name.replaceAll(_zeroWidth, '').replaceAll(RegExp(r'\s+'), ' ').trim(); + if (trimmed.replaceAll(_format, '').trim().isEmpty) return null; + final chars = trimmed.characters; + if (chars.length <= maxLength) return trimmed; + return '${chars.take(maxLength).toString().trimRight()}…'; + } + + /// The label for a heard row, or null (show the hex) when the row does not + /// resolve to exactly one repeater that has one. + /// + /// That is the repeater's nickname, or, with [useServerName], its server name + /// through [shortenServerName] when it has no nickname. The server name is + /// skipped for the placeholder name `Unknown` and for an anonymised + /// repeater ([Repeater.isHidden]). + /// + /// Resolves through [ExternalSurfaceGeoBuilder.resolveOverlayRow]: the + /// fullest [identity] the row arrived with first (a discovery response's + /// public key, a trace's target), then [displayId], the hash it is shown + /// under. + /// + /// With [useServerName] false, an empty [nicknames] returns null without + /// scanning [repeaters], which is the common case and runs on every overlay + /// rebuild. + static String? labelFor({ + required String displayId, + String? identity, + required List repeaters, + int? hopBytes, + required Map nicknames, + bool useServerName = false, + }) { + if (nicknames.isEmpty && !useServerName) return null; + final match = ExternalSurfaceGeoBuilder.resolveOverlayRow( + displayId: displayId, + identity: identity, + repeaters: repeaters, + hopBytes: hopBytes, + ); + if (match == null) return null; + final nickname = nicknameFor(match, nicknames); + if (nickname != null) return nickname; + if (!useServerName || match.name == 'Unknown' || match.isHidden) { + return null; + } + return shortenServerName(match.name); + } +} diff --git a/lib/utils/share_origin.dart b/lib/utils/share_origin.dart new file mode 100644 index 00000000..5350f19f --- /dev/null +++ b/lib/utils/share_origin.dart @@ -0,0 +1,11 @@ +import 'package:flutter/widgets.dart'; + +/// Global rect of the widget behind [context], or null before layout. +/// +/// Pass it as share_plus's `sharePositionOrigin`: iPad anchors the share +/// popover there and refuses to open the sheet without one. +Rect? globalRectOf(BuildContext context) { + final box = context.findRenderObject() as RenderBox?; + if (box == null || !box.hasSize) return null; + return box.localToGlobal(Offset.zero) & box.size; +} diff --git a/lib/utils/short_hop_ids.dart b/lib/utils/short_hop_ids.dart new file mode 100644 index 00000000..86e9b456 --- /dev/null +++ b/lib/utils/short_hop_ids.dart @@ -0,0 +1,140 @@ +import 'dart:math' as math; + +import '../models/repeater.dart'; + +/// Resolves a heard repeater id that arrived narrower than the repeater's own +/// width to the one known repeater it can only mean. +/// +/// A packet carries its hop ids at the width its sender chose, 1, 2 or 3 +/// bytes, so in a 3-byte region an advert relayed with 1-byte ids names +/// repeater `A81EA4` as just `A8`. Matched at full length only, that showed as +/// a second, unnamed repeater beside the real one. +/// +/// The rule is the server's (`rc_resolve_token` in the server's +/// `repeater_collision.php`): a repeater's key is its cleaned hex id, else its +/// legacy id; it matches when the key starts with the heard id, case +/// ignored. Matches whose keys form one prefix chain are the same device (a +/// legacy short row plus the full-key row) and collapse to the longest key. +/// Anything else is ambiguous and resolves to nothing, because a confidently +/// wrong repeater is worse than a bare id. +/// +/// Display only: logs and uploads keep the raw heard id, and the server +/// resolves it again on its own. +/// +/// Built once per repeater list (the provider caches it on the list's +/// identity): ids of 1, 2 and 3 bytes, the only widths a path carries, are +/// answered from a prefix map, and any other length falls back to a scan. +class ShortHopIds { + static const List _indexedLengths = [2, 4, 6]; + + final List<_Slot> _keys; + final Map _byPrefix; + + ShortHopIds._(this._keys, this._byPrefix); + + factory ShortHopIds.fromRepeaters(Iterable repeaters) { + final keys = <_Slot>[]; + final byPrefix = {}; + for (final repeater in repeaters) { + final key = _clean(repeater.hexId) ?? _clean(repeater.id); + if (key == null) continue; + final slot = _Slot(key, repeater); + keys.add(slot); + for (final length in _indexedLengths) { + if (key.length < length) break; + final prefix = key.substring(0, length); + final existing = byPrefix[prefix]; + byPrefix[prefix] = existing == null ? slot : existing.merge(slot); + } + } + return ShortHopIds._(keys, byPrefix); + } + + /// The one repeater [heardId] can mean, or null when none or several do. + Repeater? resolve(String heardId) => _slotFor(heardId)?.repeater; + + /// [heardId] as Top Heard shows and groups it: when it resolves, the + /// repeater's key cut to the wider of its own advertised width and the + /// region's [hopBytes] (never narrower than [heardId]), so `A8` and + /// `A81EA4` become the same row. Otherwise [heardId] unchanged. Upper case + /// either way. + String displayId(String heardId, {required int hopBytes}) { + final slot = _slotFor(heardId); + if (slot == null) return heardId.toUpperCase(); + final width = math.max( + heardId.length, math.max(slot.repeater.advertBytes, hopBytes) * 2); + return slot.key + .substring(0, math.min(width, slot.key.length)) + .toUpperCase(); + } + + /// One entry per repeater heard in [rows], keyed by [displayId], holding the + /// best SNR among the ids that resolve to it. + Map bestSnrByRepeater( + Iterable<({String repeaterId, double snr})> rows, { + required int hopBytes, + }) { + final best = {}; + for (final row in rows) { + final key = displayId(row.repeaterId, hopBytes: hopBytes); + final existing = best[key]; + if (existing == null || row.snr > existing) best[key] = row.snr; + } + return best; + } + + _Slot? _slotFor(String heardId) { + final token = _clean(heardId); + if (token == null) return null; + _Slot? found; + if (_indexedLengths.contains(token.length)) { + found = _byPrefix[token]; + } else { + for (final slot in _keys) { + if (!slot.key.startsWith(token)) continue; + found = found == null ? slot : found.merge(slot); + } + } + return found == null || found.ambiguous ? null : found; + } + + /// Cleaned lower-case hex of at least one byte, or null. + static String? _clean(String value) { + final clean = value + .replaceAll('!', '') + .replaceAll(RegExp('0x', caseSensitive: false), '') + .toLowerCase(); + if (clean.length < 2 || !_hex.hasMatch(clean)) return null; + return clean; + } + + static final RegExp _hex = RegExp(r'^[a-f0-9]+$'); +} + +/// The longest key seen under one prefix, or the marker that two keys under +/// it are different devices. +class _Slot { + final String key; + final Repeater? _repeater; + + const _Slot(this.key, Repeater this._repeater); + const _Slot._none() + : key = '', + _repeater = null; + + static const _Slot _conflict = _Slot._none(); + + bool get ambiguous => _repeater == null; + + /// Only read on a slot that is not [ambiguous]. + Repeater get repeater => _repeater!; + + /// Every key in a chain is a prefix of its longest, so comparing a new key + /// with the longest so far decides whether it is the same device. + _Slot merge(_Slot other) { + if (ambiguous) return this; + if (key.startsWith(other.key)) return this; + if (other.key.startsWith(key)) return other; + return _conflict; + } +} diff --git a/lib/utils/slots_chip.dart b/lib/utils/slots_chip.dart new file mode 100644 index 00000000..d3fb8a78 --- /dev/null +++ b/lib/utils/slots_chip.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; + +/// What the Connection screen's slots chip shows. +enum SlotsChipKind { + /// Flood is off for this zone's radio preset. Taps to the info sheet. + floodOff, + + /// Flood is on but the preset hands out no TX slots. A regional setting, + /// not a full zone, so it reads as info rather than an error. + zeroSlots, + + /// A normal `x/y Open` count. + open, + + /// No slot data yet. + unknown, +} + +class SlotsChipState { + final SlotsChipKind kind; + final String label; + final IconData icon; + final Color color; + + const SlotsChipState(this.kind, this.label, this.icon, this.color); + + bool get tappable => kind == SlotsChipKind.floodOff; +} + +/// Decides the slots chip from the zone's capacity and flood flags. +/// +/// [authFloodDisabled] is the live /auth veto. [zoneFloodDisabled] is the +/// zone's `flood_disabled` for the current preset, null when the server did +/// not send the key; only then is `slotsMax == 0` taken to mean flood off, +/// since per-preset slots let a preset have 0 slots with flood still on. +SlotsChipState slotsChipState({ + required bool authFloodDisabled, + required bool? zoneFloodDisabled, + required int? slotsAvailable, + required int? slotsMax, +}) { + final floodOff = authFloodDisabled || (zoneFloodDisabled ?? slotsMax == 0); + if (floodOff) { + return const SlotsChipState( + SlotsChipKind.floodOff, 'Flood Off', Icons.waves, Colors.blue); + } + if (slotsMax == 0) { + return const SlotsChipState( + SlotsChipKind.zeroSlots, '0 Slots', Icons.people_outline, Colors.blue); + } + if (slotsAvailable == null || slotsMax == null) { + return const SlotsChipState( + SlotsChipKind.unknown, '--', Icons.people_outline, Colors.grey); + } + final Color color; + if (slotsAvailable == 0) { + color = Colors.red; + } else if (slotsAvailable <= 2) { + color = Colors.orange; + } else { + color = Colors.green; + } + return SlotsChipState(SlotsChipKind.open, '$slotsAvailable/$slotsMax Open', + Icons.people_outline, color); +} diff --git a/lib/utils/store_links.dart b/lib/utils/store_links.dart new file mode 100644 index 00000000..f411e455 --- /dev/null +++ b/lib/utils/store_links.dart @@ -0,0 +1,133 @@ +import 'package:flutter/foundation.dart'; + +/// Where the "update the app" button sends the user, and what it says. +@immutable +class StoreLink { + final Uri uri; + final String label; + + const StoreLink(this.uri, this.label); + + @override + bool operator ==(Object other) => + other is StoreLink && other.uri == uri && other.label == label; + + @override + int get hashCode => Object.hash(uri, label); + + @override + String toString() => 'StoreLink($label, $uri)'; +} + +/// Picks the update link from how the app was installed. +/// +/// `installerStore` is `PackageInfo.installerStore`: on iOS the plugin reads +/// the receipt path (`com.apple.testflight` for TestFlight, `com.apple` for +/// the App Store, `com.apple.simulator`), on Android it is the installer +/// package name. Play shows closed-test members the testing build on the +/// normal listing, so one Play link covers testers and production. +class StoreLinks { + StoreLinks._(); + + static const String appleAppId = '6758073991'; + static const String androidPackage = 'net.meshmapper.app'; + + static final StoreLink testFlight = StoreLink( + Uri.parse('itms-beta://beta.itunes.apple.com/v1/app/$appleAppId'), + 'Update in TestFlight', + ); + static final StoreLink appStore = StoreLink( + Uri.parse('https://apps.apple.com/app/id$appleAppId'), + 'Update MeshMapper', + ); + static final StoreLink playStore = StoreLink( + Uri.parse( + 'https://play.google.com/store/apps/details?id=$androidPackage'), + 'Update MeshMapper', + ); + /// A store build's sideload link. GitHub resolves `/releases/latest` to + /// the newest stable release and skips pre-releases. + static final StoreLink githubRelease = StoreLink( + Uri.parse( + 'https://github.com/MeshMapper/MeshMapper_Project/releases/latest'), + 'Download latest version', + ); + + /// A beta build's sideload link. GitHub has no address for the newest + /// pre-release, so this is the releases page, which lists it first. + /// `/releases/latest` sent beta testers to the older stable build. + static final StoreLink githubPrerelease = StoreLink( + Uri.parse('https://github.com/MeshMapper/MeshMapper_Project/releases'), + 'Download latest version', + ); + + static const Set _playInstallers = { + 'com.android.vending', + 'com.google.android.feedback', + }; + + /// `isBetaBuild` is true for an `APP-` build (dev and beta lanes), + /// which only ever ships as a GitHub pre-release. + static StoreLink resolve(TargetPlatform platform, String? installerStore, + {bool isBetaBuild = false}) { + final sideload = isBetaBuild ? githubPrerelease : githubRelease; + switch (platform) { + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return installerStore == 'com.apple.testflight' ? testFlight : appStore; + case TargetPlatform.android: + return _playInstallers.contains(installerStore) + ? playStore + : sideload; + default: + return sideload; + } + } +} + +/// What the "Update MeshMapper to continue" panel shows after the server +/// refused this build (`/auth` reason `outofdate`). +@immutable +class AppUpdateRequirement { + /// The connection error text this requirement belongs to. The panel only + /// shows while this is still the current connection error. + final String errorMessage; + + /// One small line, e.g. "Your version: 1.3.0 · Needed: 1.4.0". + final String versionLine; + + final StoreLink link; + + const AppUpdateRequirement({ + required this.errorMessage, + required this.versionLine, + required this.link, + }); +} + +/// The minimum the server named in its `outofdate` message, e.g. +/// "App version outdated. Required: v1.4.0" or +/// "Dev version outdated. Required: 1791170991". Null when it names none. +String? parseRequiredAppVersion(String? serverMessage) { + if (serverMessage == null) return null; + final match = + RegExp(r'Required:\s*v?([0-9][0-9A-Za-z.\-]*)').firstMatch(serverMessage); + final version = match?.group(1); + if (version == null) return null; + // A trailing sentence full stop is not part of the version. + return version.endsWith('.') + ? version.substring(0, version.length - 1) + : version; +} + +/// "Your version: 1.3.0 · Needed: 1.4.0" for a store build, or +/// "Your build: 1790996175 · Needed: 1791170991" for a TestFlight build, +/// which the server compares by build number. `appVersion` is the +/// `APP-` or `APP-` string sent to the server. +String appUpdateVersionLine(String appVersion, String? requiredVersion) { + final own = appVersion.startsWith('APP-') ? appVersion.substring(4) : appVersion; + final isBuild = RegExp(r'^\d+$').hasMatch(own); + final ownLine = isBuild ? 'Your build: $own' : 'Your version: $own'; + if (requiredVersion == null || requiredVersion.isEmpty) return ownLine; + return '$ownLine · Needed: $requiredVersion'; +} diff --git a/lib/utils/zone_group.dart b/lib/utils/zone_group.dart new file mode 100644 index 00000000..490d60f6 --- /dev/null +++ b/lib/utils/zone_group.dart @@ -0,0 +1,163 @@ +/// A multi-region group the current zone belongs to, read from the +/// `/status` answer's `zone.group` (see APP_API.md section 2). +/// +/// The app uses the group only for what the user sees (labels) and where it +/// reads coverage from. The member zone's own code stays the identity of the +/// session everywhere else. +class ZoneGroup { + /// Upper-case group code, never empty, letters and digits only. Also the + /// subdomain of the group's own site (`.meshmapper.net`). + final String code; + + /// Display name, or null when the server sent none. + final String? name; + + /// Member zone codes, upper-case. May be empty. + final List members; + + const ZoneGroup({required this.code, this.name, this.members = const []}); +} + +final RegExp _groupCodePattern = RegExp(r'^[A-Z0-9]+$'); + +/// Reads `zone['group']`. Anything missing or malformed is "no group", so an +/// older server (which never sends the key) behaves exactly as before. +ZoneGroup? parseZoneGroup(Object? zone) { + if (zone is! Map) return null; + final raw = zone['group']; + if (raw is! Map) return null; + final rawCode = raw['code']; + if (rawCode is! String) return null; + final code = rawCode.trim().toUpperCase(); + if (!_groupCodePattern.hasMatch(code)) return null; + final rawName = raw['name']; + final name = + rawName is String && rawName.trim().isNotEmpty ? rawName.trim() : null; + final rawMembers = raw['members']; + final members = rawMembers is List + ? rawMembers + .whereType() + .map((m) => m.trim().toUpperCase()) + .where((m) => m.isNotEmpty) + .toList(growable: false) + : const []; + return ZoneGroup(code: code, name: name, members: members); +} + +/// Longest zone code shown whole on the short labels (chips, status bar, +/// Live Activity, watch, Siri). +const int kShortZoneLabelMax = 4; + +/// The short-label form of a zone or group code: anything longer than +/// [kShortZoneLabelMax] is cut and ends in an ellipsis. Display only; URLs +/// always use the full code. +String shortZoneLabel(String code) => code.length <= kShortZoneLabelMax + ? code + : '${code.substring(0, kShortZoneLabelMax)}…'; + +/// What a live session should do when `/status` reports a zone. +enum ZoneMove { + /// Still in the session's own zone (or no session). + none, + + /// Another member of the session's own group: move without the user + /// seeing it. + hiddenHandoff, + + /// Anything else: today's visible zone transfer. + fullTransfer, +} + +/// Pure decision for a zone change under a live session. The caller still +/// applies its own gates (connected, not Offline Mode, not in zone grace, +/// no transfer or handoff already running). +ZoneMove classifyZoneMove({ + required String? sessionZone, + required String? sessionGroup, + required String newZone, + required String? newGroup, +}) { + if (sessionZone == null || newZone.isEmpty || newZone == sessionZone) { + return ZoneMove.none; + } + if (sessionGroup != null && sessionGroup == newGroup) { + return ZoneMove.hiddenHandoff; + } + return ZoneMove.fullTransfer; +} + +/// What `_startGroupHandoff` does once a hidden handoff has settled +/// `failed`. A failed handoff has released the old session, and a connected +/// online radio must not sit without one: uploads would throw "no +/// session_id" and the keepalive is gone. +enum GroupHandoffFollowUp { + /// Nothing: the handoff did not fail, or something that owns its own + /// session (a disconnect, Offline Mode, zone grace) is in charge. + none, + + /// Re-mint through the visible transfer in the zone the phone is in NOW: + /// the member the handoff was for, a third member a later tick moved it to, + /// or the old member it moved back into (the transfer just auths in its + /// target). + transfer, + + /// No zone to re-join: end the session the way a failed visible transfer + /// does. + disconnect, +} + +/// Pure rule for [GroupHandoffFollowUp]. A handoff that was superseded never +/// gets here: whatever superseded it owns the cleanup. +GroupHandoffFollowUp groupHandoffFollowUp({ + required bool failed, + required bool connected, + required bool offlineMode, + required bool inZoneGracePeriod, + required String? zoneCode, +}) { + if (!failed || !connected || offlineMode || inZoneGracePeriod) { + return GroupHandoffFollowUp.none; + } + if (zoneCode == null || zoneCode.isEmpty) { + return GroupHandoffFollowUp.disconnect; + } + return GroupHandoffFollowUp.transfer; +} + +/// How `_reacquireSessionAfterReconnect`, the backstop for a reconnect that +/// lands online with no session (a group handoff superseded in its +/// release-to-mint gap), ends once its mint has answered. +enum ReconnectBackstopOutcome { + /// A session was minted and the link is still up: restore auto-ping. + restore, + + /// Something else (disconnect, cancel, Offline Mode, dispose) took over + /// during the mint and owns the cleanup: return quietly. + superseded, + + /// The link dropped during the mint. The reconnect's own BLE listener + /// ignores a drop while a reconnect is flagged and the reconnect timers + /// are already cancelled, so nothing else notices: hand back to the + /// ordinary auto-reconnect rather than restore auto-ping on a dead link. + handBackToReconnect, + + /// No session could be had and the radio is still connected: end the + /// session through the live-link path (channel deleted while BLE is up, + /// transport closed), never the dead-link abandon. + abandonOnLiveLink, +} + +/// Pure rule for [ReconnectBackstopOutcome]. A superseding owner is honoured +/// whatever the link did; past that the link decides before the mint does, +/// since a session minted over a link that is already gone is no use until +/// the next reconnect re-auths anyway. +ReconnectBackstopOutcome reconnectBackstopOutcome({ + required bool superseded, + required bool minted, + required bool linkUp, +}) { + if (superseded) return ReconnectBackstopOutcome.superseded; + if (!linkUp) return ReconnectBackstopOutcome.handBackToReconnect; + if (minted) return ReconnectBackstopOutcome.restore; + return ReconnectBackstopOutcome.abandonOnLiveLink; +} diff --git a/lib/widgets/background_location_setup.dart b/lib/widgets/background_location_setup.dart index 78831576..24a8c8b5 100644 --- a/lib/widgets/background_location_setup.dart +++ b/lib/widgets/background_location_setup.dart @@ -1,13 +1,25 @@ import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; +import '../models/connection_state.dart'; import '../providers/app_state_provider.dart'; +import '../services/location_consent.dart'; import '../services/permission_disclosure_service.dart'; Future setUpBackgroundLocation( BuildContext context, AppStateProvider appState, ) async { + // The background dialog only covers background use, so the main location + // disclosure comes first until it has been agreed to. + if (!await LocationConsent.hasAgreed()) { + if (!context.mounted) return false; + final agreed = + await PermissionDisclosureService.showLocationDisclosure(context); + if (!agreed) return false; + } + if (!context.mounted) return false; + final accepted = await PermissionDisclosureService.showBackgroundLocationDisclosure( context, @@ -15,6 +27,12 @@ Future setUpBackgroundLocation( if (!accepted || !context.mounted) return false; final granted = await appState.requestAlwaysLocationPermission(); + // This may be the first grant or the first Agree, and GPS refuses to + // start before both. Only when it is off: a restart mid-mode would reset + // the airborne latch and altitude tracking. + if (appState.gpsStatus == GpsStatus.permissionDenied) { + await appState.restartGpsAfterPermission(); + } if (granted || !context.mounted) return granted; await showDialog( @@ -22,9 +40,8 @@ Future setUpBackgroundLocation( builder: (dialogContext) => AlertDialog( title: const Text('Permission Required'), content: const Text( - 'To enable background location tracking, open Settings and set ' - 'Location to "Always".\n\nThis allows MeshMapper to track your ' - 'location in the background during continuous wardriving.', + 'To keep using your location in the background while your radio is ' + 'connected, open Settings and set Location to "Always".', ), actions: [ TextButton( diff --git a/lib/widgets/bug_report_dialog.dart b/lib/widgets/bug_report_dialog.dart index ecf1c020..8f9bddef 100644 --- a/lib/widgets/bug_report_dialog.dart +++ b/lib/widgets/bug_report_dialog.dart @@ -61,8 +61,9 @@ class _BugReportSheetState extends State { Future _loadUploadableFiles() async { try { - // Rotate log and get uploadable files (excludes new current file) - final files = await widget.appState.prepareDebugLogsForUpload(); + // Listed as they are. The live log is rotated once, at submit, and + // only when logs are attached, never on opening the dialog. + final files = await widget.appState.listDebugLogFiles(); if (mounted) { setState(() { _availableLogFiles = files; @@ -151,10 +152,13 @@ class _BugReportSheetState extends State { try { final service = DebugSubmitService(); - // Get selected files + // Get selected files. The one rotation happens here: the live log is + // closed in place (same path) so it is complete, and the selection, + // made by path, still names it. List? filesToUpload; if (_uploadLogs && _selectedLogFiles.isNotEmpty) { - filesToUpload = _availableLogFiles + final freshFiles = await widget.appState.prepareDebugLogsForUpload(); + filesToUpload = freshFiles .where((f) => _selectedLogFiles.contains(f.path)) .toList(); } @@ -487,6 +491,10 @@ class _BugReportSheetState extends State { sizeDisplay = '${(sizeBytes / 1024).toStringAsFixed(1)} KB'; } + if (file.path == + DebugFileLogger.currentLogPath) { + sizeDisplay = '$sizeDisplay (current)'; + } return ListTile( dense: true, diff --git a/lib/widgets/connection_panel.dart b/lib/widgets/connection_panel.dart index 47c2c9d6..17ae6e86 100644 --- a/lib/widgets/connection_panel.dart +++ b/lib/widgets/connection_panel.dart @@ -76,7 +76,7 @@ class ConnectionPanel extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - 'External Antenna', + 'Antenna', style: TextStyle( fontSize: 13, fontWeight: FontWeight.w500, @@ -106,10 +106,11 @@ class ConnectionPanel extends StatelessWidget { children: [ _buildSegmentButton( context, - label: 'No', + label: 'Internal', + icon: Icons.directions_car, isSelected: isSet && !hasExternal, onTap: () { - debugLog('[UI] External antenna button pressed: No'); + debugLog('[UI] Antenna button pressed: Internal'); appState.updatePreferences( prefs.copyWith( externalAntenna: false, externalAntennaSet: true), @@ -118,10 +119,11 @@ class ConnectionPanel extends StatelessWidget { ), _buildSegmentButton( context, - label: 'Yes', + label: 'External', + icon: Icons.cell_tower, isSelected: isSet && hasExternal, onTap: () { - debugLog('[UI] External antenna button pressed: Yes'); + debugLog('[UI] Antenna button pressed: External'); appState.updatePreferences( prefs.copyWith( externalAntenna: true, externalAntennaSet: true), @@ -136,20 +138,31 @@ class ConnectionPanel extends StatelessWidget { ); } + /// One antenna choice. [icon] matches the quick guide's picture of it. Widget _buildSegmentButton( BuildContext context, { required String label, + required IconData icon, required bool isSelected, required VoidCallback onTap, }) { final isDark = Theme.of(context).brightness == Brightness.dark; + final color = isSelected + ? (isDark + ? Colors.white + : const Color(0xFF1E293B)) // slate-800 for light + : (isDark + ? const Color(0xFF94A3B8) + : const Color(0xFF64748B)); // slate-400/500 return GestureDetector( onTap: onTap, child: AnimatedContainer( duration: const Duration(milliseconds: 200), curve: Curves.easeInOut, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + // Tighter than the old 16 so the icon costs no width: the label + // column beside the toggle has to keep "Remembered for ". + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), decoration: BoxDecoration( color: isSelected ? (isDark @@ -166,19 +179,20 @@ class ConnectionPanel extends StatelessWidget { ] : null, ), - child: Text( - label, - style: TextStyle( - fontSize: 13, - fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500, - color: isSelected - ? (isDark - ? Colors.white - : const Color(0xFF1E293B)) // slate-800 for light - : (isDark - ? const Color(0xFF94A3B8) - : const Color(0xFF64748B)), // slate-400/500 - ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: color), + const SizedBox(width: 3), + Text( + label, + style: TextStyle( + fontSize: 13, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500, + color: color, + ), + ), + ], ), ), ); diff --git a/lib/widgets/map_widget.dart b/lib/widgets/map_widget.dart index 731d2c22..b07cecb2 100644 --- a/lib/widgets/map_widget.dart +++ b/lib/widgets/map_widget.dart @@ -14,6 +14,7 @@ import 'package:provider/provider.dart'; import 'gps_info_chip.dart'; import '../models/log_entry.dart'; +import '../models/map_view_state.dart'; import '../models/noise_floor_session.dart'; import '../models/ping_data.dart'; import '../models/repeater.dart'; @@ -27,6 +28,7 @@ import '../utils/cluster_spread.dart'; import '../utils/coalesced_async_runner.dart'; import '../utils/debug_logger_io.dart'; import '../utils/geo_validation.dart'; +import '../utils/gps_marker_colors.dart'; import '../utils/mvt_cells.dart'; import '../utils/distance_formatter.dart'; import '../utils/ping_colors.dart'; @@ -36,10 +38,14 @@ import '../utils/repeater_format.dart'; import '../utils/repeater_marker_painter.dart'; import '../utils/repeater_marker_style.dart'; import '../utils/map_style_errors.dart'; +import '../utils/marker_data_version.dart'; import '../utils/serial_task_gate.dart'; import 'cell_summary_sheet.dart'; import 'repeater_admin_sheet.dart'; import 'repeater_id_chip.dart'; +import 'repeater_nickname_dialog.dart'; +import 'repeater_nickname_widgets.dart'; +import 'repeater_scope_chips.dart'; import 'rx_path_chain.dart'; /// Satellite style as inline MapLibre style JSON (ArcGIS raster source). @@ -63,7 +69,7 @@ String _repeaterIdentity(Repeater repeater) => rcCleanHex(repeater.hexId); /// Repeater shapes have one bitmap per (status color × hop_byte shape) — 12 /// total. Coverage markers have one bitmap per (ping type × success state) for /// the user's currently-selected style — 8 total per style preference. GPS -/// marker has one bitmap per style — 6 total. +/// marker has one bitmap per (style × colour choice) — 14 total. class _MapImages { _MapImages._(); @@ -109,10 +115,14 @@ class _MapImages { static const coverageTypes = ['tx', 'rx', 'disc', 'trace', 'deferred']; - // GPS marker bitmaps: one per style - // Names: gps_arrow, gps_car, etc. The list of styles lives in - // _registerMapImages where we map each style key to its CustomPainter. - static String gps(String style) => 'gps_$style'; + // GPS marker bitmaps: one per style and colour choice + // Names: gps_arrow, gps_car, etc. for the default colour, gps_car_green etc. + // for the others. The list of styles lives in _registerMapImages where we + // map each style key to its CustomPainter. + static String gps(String style, String color) => + GpsMarkerColors.normalize(color) == GpsMarkerColors.defaultChoice + ? 'gps_$style' + : 'gps_${style}_$color'; } /// Renders a [CustomPainter] into a PNG byte buffer using `dart:ui`. @@ -650,6 +660,14 @@ class _MapWidgetState extends State with WidgetsBindingObserver { false; // Track if we've done the one-time initial zoom to GPS bool _hasZoomedToLastKnown = false; // Track if we've zoomed to last known position (before GPS) + // The zoom MapLibreMap was created at (initialCameraPosition is read once). + double? _initialCameraZoom; + // False until the camera has been handed the remembered zoom (one of the + // startup zooms above) or the user has moved it off the creation zoom. + // Until then a camera idle is still the creation camera, possibly built + // before preferences loaded, and recording it would overwrite the zoom + // about to be restored. + bool _zoomRestoreSettled = false; bool _loggedMpxSanityCheck = false; // One-time log comparing formula vs MapLibre m/px @@ -686,9 +704,6 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // layer styling (see #347). bool _showRepeaters = true; - // Collapsible map controls in landscape - bool _mapControlsExpanded = true; - // Rotation lock (disable rotation gestures while keeping pinch-to-zoom) bool _rotationLocked = false; @@ -711,6 +726,10 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // the first entry and restored ONCE when the last view closes, so switching // directly between views animates only once and restores to the original view. bool _cameraFocusActive = false; + + /// The zoom a focus view or history fit last left the camera at, until the + /// camera moves off it. See [_rememberCameraZoom]. + double? _transientZoomHeld; bool _focusPanelMinimized = false; dynamic _focusedPingSource; // TxPing | RxPing | DiscLogEntry | TraceLogEntry @@ -720,11 +739,12 @@ class _MapWidgetState extends State with WidgetsBindingObserver { _MinimizedInfoPopup? _minimizedInfoPopup; // MapLibre style and overlay tracking. - // Tracks the zone code we last rendered the coverage overlay for. When the - // zone check succeeds after the style has already loaded (e.g. first check - // failed with gps_inaccurate and a later retry succeeded), _addCoverageOverlay - // would otherwise never re-run and the coverage layer would stay missing. - String? _lastOverlayZoneCode; + // Tracks the coverage host (the region or group code) we last rendered the + // coverage overlay for. When the zone check succeeds after the style has + // already loaded (e.g. first check failed with gps_inaccurate and a later + // retry succeeded), _addCoverageOverlay would otherwise never re-run and the + // coverage layer would stay missing. + String? _lastOverlayHostCode; // Last coverage overlay opacity we pushed into MapLibre. Compared against // the current preference in _onCoverageOpacityNotify to detect slider // changes and apply them live via _applyCoverageOverlayOpacity (no layer @@ -858,6 +878,11 @@ class _MapWidgetState extends State with WidgetsBindingObserver { bool _styleLoadInProgress = false; final CoalescedAsyncRunner _styleLoadRunner = CoalescedAsyncRunner(); + // Serializes region border rebuilds. The style restore and the build() + // watcher can both ask at once; overlapping remove-then-add runs raced + // into sourceAlreadyExists and could leave the border line missing. + final CoalescedAsyncRunner _regionBorderRunner = CoalescedAsyncRunner(); + // Monotonic counter for the Android deferred style re-sync. Bumped when a // style reload BEGINS (a new styleString handed to MapLibreMap), at the // start of every _restoreStyle, and again when a re-sync is armed at the end @@ -896,6 +921,13 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // _syncAllAnnotations) so the two features never wipe each other. bool _coverageLinesInstalled = false; bool _coverageCellsInstalled = false; + // The selected repeater's coverage lines, kept while its cells are on the + // map (cleared with them in _clearCoverageCells) so the Repeater Coverage + // Lines switch can redraw or clear them without a reselect. + RepeaterCoverageLines? _repeaterCoverageLines; + // The switch value _onRepeaterCoverageLinesNotify last saw, so it acts only + // on a flip and not on every provider notify. + bool? _lastSeenShowRepeaterCoverageLines; // Set while a tapped cell's fan-out is shown: the repeater ids that heard the // cell's pings. Non-null -> _buildRepeaterFeatureCollection hides every // repeater NOT in the set (web fades-but-keeps; the app hides for consistency @@ -1055,10 +1087,36 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // a direct listener too. See _onCoverageOpacityNotify. _patchProviderRef!.addListener(_onCoverageOpacityNotify); _patchProviderRef!.addListener(_onCoverageFilterNotify); + // The Repeater Coverage Lines switch does not bump mapRevision either. + _lastSeenShowRepeaterCoverageLines = + _patchProviderRef!.preferences.showRepeaterCoverageLines; + _patchProviderRef!.addListener(_onRepeaterCoverageLinesNotify); } AppStateProvider? _patchProviderRef; + /// Fires on every provider notify; applies a flipped Repeater Coverage Lines + /// switch to the selected repeater straight away (web + /// `mmRedrawSelectedCoverage` parity), no rebuild. Leaves the lines layer + /// alone unless the selected repeater's own lines are drawn: a tapped tile's + /// fan-out shares the layer and the switch does not cover it. + void _onRepeaterCoverageLinesNotify() { + final appState = _patchProviderRef; + if (appState == null || !mounted) return; + final show = appState.preferences.showRepeaterCoverageLines; + if (show == _lastSeenShowRepeaterCoverageLines) return; + _lastSeenShowRepeaterCoverageLines = show; + final drawn = _repeaterCoverageLines; + final segments = repeaterCoverageLinesAfterSwitch(drawn, + show: show, + selectedRepeaterId: _isolatedRepeaterId, + tileSelected: _cellPopupActive); + if (drawn == null || segments == null) return; + debugLog('[COVERAGE] repeater coverage lines ${show ? 'on' : 'off'}: ' + '${segments.length} drawn'); + _updateCoverageLines(segments, drawn.lat, drawn.lon, width: 1.5); + } + /// Auth/release can change the effective window on a UI-only notify. /// Observe it directly so the memoized map never keeps a regional override. void _onCoverageFilterNotify() { @@ -1168,7 +1226,10 @@ class _MapWidgetState extends State with WidgetsBindingObserver { if (!_showMeshMapperOverlay) return; final appState = context.read(); if (!appState.preferences.mapTilesEnabled) return; - if (appState.zoneCode == null || appState.zoneCode!.isEmpty) return; + if (appState.coverageHostCode == null || + appState.coverageHostCode!.isEmpty) { + return; + } debugLog('[MAP] Recovering coverage overlay after app resume'); _addCoverageOverlay(appState); } @@ -1181,11 +1242,13 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // keep the local only for listener cleanup below. _mapController = null; _styleLoadRunner.cancel(); + _regionBorderRunner.cancel(); WidgetsBinding.instance.removeObserver(this); _patchProviderRef?.removeListener(_onCoveragePatchNotify); _patchProviderRef?.removeListener(_onPositionNotify); _patchProviderRef?.removeListener(_onCoverageOpacityNotify); _patchProviderRef?.removeListener(_onCoverageFilterNotify); + _patchProviderRef?.removeListener(_onRepeaterCoverageLinesNotify); _tileLoadTimeoutTimer?.cancel(); if (controller != null) { controller.removeListener(_onCameraChanged); @@ -1478,6 +1541,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { void _exitFocusCamera() { if (!_cameraFocusActive) return; _cameraFocusActive = false; + // Before the zoom-back, so the saved center lands at the true map center. + _clearFitPadding(); final center = _preFocusCenter; final zoom = _preFocusZoom; final restoreFollow = _wasAutoFollowBeforeFocus && !_autoFollow; @@ -1503,6 +1568,22 @@ class _MapWidgetState extends State with WidgetsBindingObserver { } } + /// Android only: drop the edge padding a fit-to-box ([_animateFitBounds]) left + /// on the native map. MapLibre Android keeps a `newLatLngBounds` padding as + /// the map's viewport padding, and every later camera move (none carry a + /// padding) keeps it, so the map center stays pushed up by the room left for + /// the focus sheet. Auto-follow then adds its own control panel offset on top + /// and the GPS marker lands near the top of the screen. iOS applies a fit's + /// padding to that one move only, so it needs nothing here. + void _clearFitPadding() { + if (kIsWeb || !Platform.isAndroid) return; + if (_mapController == null || !_isMapReady || !_canAnimateCamera) return; + debugLog('[MAP CENTER] clearing fit padding after focus view'); + _mapController!.updateContentInsets(EdgeInsets.zero).catchError((e) { + debugLog('[MAP CENTER] clearing fit padding failed: $e'); + }); + } + /// True while any focus view (ping focus, tile coverage, repeater coverage) is /// open. Drives [_exitFocusCameraIfDone] so a view switch (which clears the old /// view AFTER the new one is claimed) keeps the camera engaged. @@ -1708,11 +1789,14 @@ class _MapWidgetState extends State with WidgetsBindingObserver { _isMapReady && _canAnimateCamera) { _hasZoomedToLastKnown = true; + _zoomRestoreSettled = true; final lastKnownCenter = LatLng(lastKnown.lat, lastKnown.lon); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { - _animateToPositionWithZoom(lastKnownCenter, 15.0 - _zoomEpsilon); - debugLog('[MAP] Initial zoom to last known position'); + final zoom = _startupZoom(appState, 15.0 - _zoomEpsilon); + _animateToPositionWithZoom(lastKnownCenter, zoom); + debugLog('[MAP] Initial zoom to last known position ' + '(zoom=${zoom.toStringAsFixed(2)})'); } }); } @@ -1725,8 +1809,15 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // One-time initial zoom to GPS (even with auto-follow off, centered on GPS). if (!_hasInitialZoomed && _isMapReady && _canAnimateCamera) { _hasInitialZoomed = true; + _zoomRestoreSettled = true; final initialPosition = center; _lastGpsPosition = initialPosition; + // The zoom the user last left the map at, or 16 on a first launch. + final initialZoom = _startupZoom(appState, 16.0 - _zoomEpsilon); + // Follow ticks aim at the startup zoom too, so one that lands during + // this animation cannot strand the camera at an in-between zoom. + // _onCameraIdle hands zoom back to the camera once it settles. + if (_autoFollow) _autoFollowDesiredZoom ??= initialZoom; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { if (_autoFollow) { @@ -1734,13 +1825,14 @@ class _MapWidgetState extends State with WidgetsBindingObserver { initialPosition, widget.bottomPaddingPixels, widget.rightPaddingPixels, - 16.0 - _zoomEpsilon); - _animateToPositionWithZoom(adjustedPosition, 16.0 - _zoomEpsilon); - debugLog( - '[MAP] Initial zoom to GPS position (with panel offset)'); + initialZoom); + _animateToPositionWithZoom(adjustedPosition, initialZoom); + debugLog('[MAP] Initial zoom to GPS position (with panel offset, ' + 'zoom=${initialZoom.toStringAsFixed(2)})'); } else { - _animateToPositionWithZoom(initialPosition, 16.0 - _zoomEpsilon); - debugLog('[MAP] Initial zoom to GPS position'); + _animateToPositionWithZoom(initialPosition, initialZoom); + debugLog('[MAP] Initial zoom to GPS position ' + '(zoom=${initialZoom.toStringAsFixed(2)})'); } } }); @@ -1822,6 +1914,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { appState.currentPosition?.longitude, _computedHeading, appState.preferences.gpsMarkerStyle, + appState.preferences.gpsMarkerColor, ); if (gpsVersion != _lastGpsSyncVersion) { // NOT recorded here: _syncGpsSymbol records the version of what it @@ -1933,6 +2026,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { } } else if (!appState.viewingHistorySession && _wasViewingHistory) { _wasViewingHistory = false; + // The camera is left at the session fit: not a zoom to remember. + _transientZoomHeld = _mapController?.cameraPosition?.zoom; } // Sync native annotations whenever marker data changes (provider triggers @@ -2184,9 +2279,12 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// Collapsible map controls (toggle at top, expands downward) Widget _buildCollapsibleMapControls(AppStateProvider appState) { // Use external state if provided, otherwise use internal state - final isExpanded = widget.mapControlsExpanded ?? _mapControlsExpanded; + // Portrait keeps its own state in the provider so it survives a relaunch. + final isExpanded = widget.mapControlsExpanded ?? + appState.mapViewState.mapControlsExpanded; final onToggle = widget.onMapControlsToggle ?? - () => setState(() => _mapControlsExpanded = !_mapControlsExpanded); + () => setState(() => appState.setMapControlsColumnExpanded( + !appState.mapViewState.mapControlsExpanded)); return Column( mainAxisSize: MainAxisSize.min, @@ -2295,16 +2393,18 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // onStyleLoadedCallback → _onStyleLoaded re-registers images, rebuilds // cluster layers, re-adds the coverage overlay, and re-syncs annotations. - // Detect zoneCode or overlay-pref changes → schedule a SINGLE coalesced - // refresh; the _coverageRefreshScheduled flag ensures at most one refresh - // is queued per frame even when both change together. + // Detect coverage host (region or group code) or overlay-pref changes → + // schedule a SINGLE coalesced refresh; the _coverageRefreshScheduled flag + // ensures at most one refresh is queued per frame even when both change + // together. A move between two members of the same group keeps the host, + // so nothing here fires for it. // - // The zoneCode watcher is needed because _addCoverageOverlay only runs + // The host watcher is needed because _addCoverageOverlay only runs // during _onStyleLoaded — if the first zone check failed with - // gps_inaccurate, the style loads with zoneCode=null and the overlay is - // skipped. When a later retry sets the zone, nothing else would trigger - // the coverage layer. - final zoneChanged = appState.zoneCode != _lastOverlayZoneCode && + // gps_inaccurate, the style loads with coverageHostCode=null and the + // overlay is skipped. When a later retry sets the zone, nothing else + // would trigger the coverage layer. + final zoneChanged = appState.coverageHostCode != _lastOverlayHostCode && _isMapReady && _styleLoaded; // Grid size is baked into the tile URL and the CVD palette into the layer @@ -2341,8 +2441,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { if (zoneChanged || overlayPrefChanged || radioChanged) { if (zoneChanged) { - _lastOverlayZoneCode = appState.zoneCode; - // The session patch belongs to the old region's grid. + _lastOverlayHostCode = appState.coverageHostCode; + // The session patch belongs to the old region's (or group's) grid. appState.clearCoveragePatch(); } if (overlayPrefChanged) { @@ -2438,11 +2538,15 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // MapLibre GL map (base tiles via style; coverage overlay added programmatically) MapLibreMap( styleString: newStyleUrl, + // Read once by the platform view at creation, so pin the zoom the + // map was created at: _onCameraIdle compares against it. initialCameraPosition: CameraPosition( target: center, - zoom: _defaultZoom, + zoom: _initialCameraZoom ??= + appState.mapViewState.zoom ?? _defaultZoom, ), - minMaxZoomPreference: const MinMaxZoomPreference(3, _maxUserZoom), + minMaxZoomPreference: + const MinMaxZoomPreference(MapViewState.minZoom, _maxUserZoom), rotateGesturesEnabled: !_rotationLocked, scrollGesturesEnabled: true, zoomGesturesEnabled: true, @@ -2638,7 +2742,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { return; } final appState = context.read(); - final zone = appState.zoneCode; + final zone = appState.coverageHostCode; if (zone == null || zone.isEmpty) return; final gridSize = appState.preferences.coverageGridSize; @@ -3346,6 +3450,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // also gone with the style; reset so the next draw treats it as fresh. _coverageLinesInstalled = false; _coverageCellsInstalled = false; + _repeaterCoverageLines = null; _coverageHeardRepeaterIds = null; _coverageDistanceLabelSymbols.clear(); _registeredCoverageLabelImages.clear(); @@ -3380,12 +3485,12 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // Re-add coverage overlay AFTER cluster layers exist so _addCoverageOverlay // can target the bottom repeater layer as its belowLayerId reference. This - // keeps the insertion point consistent with the zoneCode watcher path — + // keeps the insertion point consistent with the host watcher path: // both end up with raster at the bottom of the repeater stack, not above it. if (!_canContinueStyleRestore()) return; await _refreshCoverageOverlay(appState); if (!_canContinueStyleRestore()) return; - _lastOverlayZoneCode = appState.zoneCode; + _lastOverlayHostCode = appState.coverageHostCode; // Regional boundary layer — style reload wipes custom sources/layers. // Reset the signature so the build()-driven watcher will repaint even @@ -3676,10 +3781,50 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// current zoom (line ~1005), so the user can pinch-zoom freely while /// auto-follow is on without each tick snapping the zoom back. void _onCameraIdle() { - if (!_autoFollow || _mapController == null) return; + if (_mapController == null) return; + _rememberCameraZoom(); + if (!_autoFollow) return; _autoFollowDesiredZoom = null; } + /// The zoom a startup camera move should land at: the one the user last left + /// the map at, else [firstLaunchZoom]. Read live from the provider, because + /// the GPS listener can run this before the widget has rebuilt. + double _startupZoom(AppStateProvider appState, double firstLaunchZoom) => + appState.mapViewState.zoom ?? firstLaunchZoom; + + /// Record the settled camera zoom so the next launch opens at it. Skipped + /// for transient cameras: a focus view (tapped ping, cell or repeater) and + /// the history session fit. The provider drops repeats and debounces writes. + void _rememberCameraZoom() { + if (!mounted) return; + final zoom = _mapController?.cameraPosition?.zoom; + if (zoom == null || !zoom.isFinite) return; + final appState = context.read(); + if (!appState.preferencesLoaded) return; + if (_cameraFocusActive || appState.viewingHistorySession) { + _transientZoomHeld = zoom; + return; + } + // A transient view leaves its zoom behind when it closes (the history + // fit stays put). That is not the user's until they zoom away from it. + final held = _transientZoomHeld; + if (held != null) { + if (!MapViewState.zoomWorthSaving(held, zoom)) return; + _transientZoomHeld = null; + } + if (!_zoomRestoreSettled) { + final created = _initialCameraZoom; + if (created == null || + !MapViewState.zoomWorthSaving(created, zoom)) { + return; + } + // The user zoomed before any startup zoom ran: theirs wins. + _zoomRestoreSettled = true; + } + appState.rememberMapZoom(zoom); + } + /// Add MeshMapper coverage raster overlay as a MapLibre source+layer. /// Allocates fresh suffixed IDs each call to avoid native collisions. /// Gated entry point; see [_coverageGate]. @@ -3696,14 +3841,17 @@ class _MapWidgetState extends State with WidgetsBindingObserver { debugLog('[MAP] Coverage overlay add skipped: mapTilesEnabled=false'); return; } - if (appState.zoneCode == null || appState.zoneCode!.isEmpty) { - debugLog( - '[MAP] Coverage overlay add skipped: zoneCode=${appState.zoneCode}'); + if (appState.coverageHostCode == null || + appState.coverageHostCode!.isEmpty) { + debugLog('[MAP] Coverage overlay add skipped: ' + 'coverageHostCode=${appState.coverageHostCode}'); return; } final prefs = appState.preferences; - final zone = appState.zoneCode!.toLowerCase(); + // The region's site, or the group's when the zone belongs to one: the + // group's site merges every member's coverage. + final zone = appState.coverageHostCode!.toLowerCase(); final gridSize = prefs.coverageGridSize; final recentDays = appState.coverageOverlayDays; // Display every recent result. Only the Smart Pinging lookup filters types. @@ -3745,15 +3893,19 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // The server emits an integer status category per cell (st); colour // happens HERE via match expressions, so colour-vision palettes apply // without any server param and a tile carries data, not pixels. + // cf declares the tile format this build understands (blocks carrying + // `k`); only send it while the decoder, the patch filter and the paint + // all handle blocks. final url = - 'https://$zone.meshmapper.net/vector_tile.php?z={z}&x={x}&y={y}&gsize=$gridSize$radioSuffix$recentSuffix'; + 'https://$zone.meshmapper.net/vector_tile.php?z={z}&x={x}&y={y}&gsize=$gridSize&cf=$kCoverageTileFormat$radioSuffix$recentSuffix'; debugLog( '[MAP] Coverage overlay source: gsize=$gridSize preset=${appState.radioFilterKey ?? 'any'}'); - // minzoom 7 = the raster's old on-screen range (512px-convention vector - // tiles sit one display-zoom lower than 256px raster tiles). + // minzoom 2: the server answers z2 and up, zoomed-out tiles as blocks + // of 300 m cells (each carrying `k`). The fill paints from `st` alone, + // so a block colours exactly like a cell. await _mapController!.addSource( sourceId, - VectorSourceProperties(tiles: [url], minzoom: 7, maxzoom: 14), + VectorSourceProperties(tiles: [url], minzoom: 2, maxzoom: 14), ); await _mapController!.addFillLayer( sourceId, @@ -4049,12 +4201,13 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// GeoJSON FeatureCollection of the session patch: one rectangle per cell, /// corners computed from grid indices exactly like the server's tiles. Map _buildPatchGeoJson(AppStateProvider appState) { - final steps = kCoverageGridSteps[appState.preferences.coverageGridSize] ?? - kCoverageGridSteps[300]!; + final gridSize = appState.preferences.coverageGridSize; final features = >[]; for (final cell in appState.coveragePatchCells.values) { - final lat0 = cell.i * steps[0]; - final lon0 = cell.j * steps[1]; + final b = cell.bounds(gridSize); + final lat0 = b[0]; + final lon0 = b[1]; + final steps = [b[2], b[3]]; // No feature id: nothing reads it on the patch layer, and 42-bit ids // don't survive Android's float32 JSON bridge anyway (see // _applyBasePatchFilter). @@ -4086,33 +4239,20 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// on the feature id: Android's filter converter parses every JSON number /// as float32, which silently rounds the 42-bit ids so an id-based `in` /// never matches. Strings cross the bridge untouched on every platform. + /// + /// A zoomed-out block (a feature carrying `k`) is never hidden: its i/j are + /// block indices, so one that happens to equal a patched cell's indices + /// would otherwise vanish. See [coveragePatchBaseFilter]. Future _applyBasePatchFilter( AppStateProvider appState, String baseLayerId) async { if (_mapController == null || appState.coveragePatchCells.isEmpty) return; final keys = [ for (final cell in appState.coveragePatchCells.values) - '${cell.i}_${cell.j}' + if (!cell.isBlock) '${cell.i}_${cell.j}' ]; try { - await _mapController!.setFilter(baseLayerId, [ - '!', - [ - 'in', - [ - 'concat', - [ - 'to-string', - ['get', 'i'] - ], - '_', - [ - 'to-string', - ['get', 'j'] - ], - ], - ['literal', keys], - ], - ]); + await _mapController! + .setFilter(baseLayerId, coveragePatchBaseFilter(keys)); } catch (e) { debugLog('[MAP] Coverage base filter failed: $e'); } @@ -4230,7 +4370,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// of the state bar; a `new` chip is taller than the rest. /// - 5 cluster badge discs, one per dominant state. /// - 8 coverage marker bitmaps for the user's currently-selected style. - /// - 6 GPS marker bitmaps (one per style). + /// - 14 GPS marker bitmaps (7 styles × 2 colour choices). Every colour is + /// baked up front, so a colour change only swaps the image name. /// /// The cluster presence-dot strips are NOT registered here: which ones are /// reachable depends on the states actually on screen, so @@ -4241,6 +4382,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { Future _registerMapImages(AppStateProvider appState) async { if (_mapController == null) return; + var stage = 'starting'; try { // 1. Repeater chip bodies: 5 states × 3 hop widths. for (final status in RepeaterMarkerStatus.values) { @@ -4256,12 +4398,14 @@ class _MapWidgetState extends State with WidgetsBindingObserver { borderRadius: RepeaterMarkerStyle.chipCornerRadius, isNew: isNew, ); + stage = 'rendering ${_MapImages.repeater(status.wireKey, hopBytes)}'; final bytes = await _renderPainterToPng( painter, Size(chip.width + repeaterChipGlowMargin * 2, chip.height + repeaterChipGlowMargin * 2), devicePixelRatio: RepeaterMarkerStyle.bakeDevicePixelRatio, ); + stage = 'adding ${_MapImages.repeater(status.wireKey, hopBytes)}'; await _mapController!.addImage( _MapImages.repeater(status.wireKey, hopBytes), bytes, @@ -4271,40 +4415,52 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // 2. Cluster badge discs: one per dominant state. for (final status in RepeaterMarkerStatus.values) { + stage = 'rendering ${_MapImages.repeaterBadge(status.wireKey)}'; final bytes = await _renderRepeaterBadgePng(_repeaterStatusColor(status.wireKey)); + stage = 'adding ${_MapImages.repeaterBadge(status.wireKey)}'; await _mapController! .addImage(_MapImages.repeaterBadge(status.wireKey), bytes); } // 3. Coverage markers: 8 variants for current style + stage = 'registering coverage images (${appState.preferences.markerStyle})'; await _registerCoverageImages(appState.preferences.markerStyle); - // 4. GPS marker variants: 7 styles + // 4. GPS marker variants: 7 styles × every colour choice const gpsSize = Size(48, 48); - final gpsPainters = { - 'arrow': const _ArrowPainter(), - 'car': const _CarMarkerPainter(), - 'bike': const _BikeMarkerPainter(), - 'boat': const _BoatMarkerPainter(), - 'walk': const _WalkMarkerPainter(), - 'dog': const _DogMarkerPainter(), - 'chomper': const _ChomperMarkerPainter(), + final gpsPainters = { + 'arrow': _ArrowPainter.new, + 'car': _CarMarkerPainter.new, + 'bike': _BikeMarkerPainter.new, + 'boat': _BoatMarkerPainter.new, + 'walk': _WalkMarkerPainter.new, + 'dog': _DogMarkerPainter.new, + 'chomper': _ChomperMarkerPainter.new, }; + var gpsImageCount = 0; for (final entry in gpsPainters.entries) { - final bytes = await _renderPainterToPng(entry.value, gpsSize); - await _mapController!.addImage(_MapImages.gps(entry.key), bytes); + for (final color in GpsMarkerColors.choices) { + final name = _MapImages.gps(entry.key, color); + final painter = + entry.value(GpsMarkerColors.forStyle(entry.key, color)); + stage = 'rendering $name'; + final bytes = await _renderPainterToPng(painter, gpsSize); + stage = 'adding $name'; + await _mapController!.addImage(name, bytes); + gpsImageCount++; + } } _imagesRegistered = true; debugLog( - '[MAP] Registered ${_MapImages.repeaterStatuses.length * _MapImages.repeaterHopBytes.length} repeater chip + ${_MapImages.repeaterStatuses.length} cluster badge + 8 coverage + ${gpsPainters.length} GPS marker images'); + '[MAP] Registered ${_MapImages.repeaterStatuses.length * _MapImages.repeaterHopBytes.length} repeater chip + ${_MapImages.repeaterStatuses.length} cluster badge + 8 coverage + $gpsImageCount GPS marker images'); // NOTE: do NOT trigger _syncAllAnnotations here. The repeater cluster // source/layers haven't been created yet — _onStyleLoaded calls // _setupRepeaterClusterLayers AFTER us, then triggers the initial sync // once everything is in place. } catch (e) { - debugError('[MAP] Failed to register marker images: $e'); + debugError('[MAP] Failed to register marker images while $stage: $e'); } } @@ -4916,6 +5072,13 @@ class _MapWidgetState extends State with WidgetsBindingObserver { if (!mounted) return; _syncSpiderSymbols(appState, currentZoom); }); + // A post-frame callback does not schedule a frame of its own, and the + // setState frame from _spiderfy/_collapseSpider has usually already run by + // the time the await above returns. Map gestures and GPS do not rebuild + // this widget, so without this the spider push waited for an unrelated + // frame: opening a spider hid the originals and showed nothing, and + // closing one left the spread drawn over the restored originals. + WidgetsBinding.instance.ensureVisualUpdate(); } // --------------------------------------------------------------------------- @@ -4949,7 +5112,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// Maximum zoom the camera can reach (matches `minMaxZoomPreference`). /// Subtracted by [_zoomEpsilon] to dodge the integer-zoom label-blink /// bug described above. - static const double _maxUserZoom = 17.0 - _zoomEpsilon; + static const double _maxUserZoom = MapViewState.maxZoom; /// How far a tap may land from a cluster badge and still count as hitting /// it. The native tap dispatcher is more forgiving than an exact-point @@ -5584,8 +5747,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { try { await _mapController!.setGeoJsonSource( _gpsPuckSourceId, - _buildGpsPuckFeatureCollection( - pos.latitude, pos.longitude, style, iconRotate), + _buildGpsPuckFeatureCollection(pos.latitude, pos.longitude, style, + appState.preferences.gpsMarkerColor, iconRotate), ); _recordGpsSyncVersion(appState, pos); } catch (e) { @@ -5602,20 +5765,21 @@ class _MapWidgetState extends State with WidgetsBindingObserver { pos?.longitude, _computedHeading, appState.preferences.gpsMarkerStyle, + appState.preferences.gpsMarkerColor, ); } /// One-Point FeatureCollection for the GPS puck source. `iconImage` and /// `iconRotate` are read by the puck symbol layer's data-driven expressions. - Map _buildGpsPuckFeatureCollection( - double lat, double lon, String style, double iconRotate) { + Map _buildGpsPuckFeatureCollection(double lat, double lon, + String style, String color, double iconRotate) { return { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'properties': { - 'iconImage': _MapImages.gps(style), + 'iconImage': _MapImages.gps(style, color), 'iconRotate': iconRotate, }, 'geometry': { @@ -5708,7 +5872,11 @@ class _MapWidgetState extends State with WidgetsBindingObserver { try { await _mapController!.setGeoJsonSource( _gpsPuckSourceId, - _buildGpsPuckFeatureCollection(pos.latitude, pos.longitude, style, + _buildGpsPuckFeatureCollection( + pos.latitude, + pos.longitude, + style, + appState.preferences.gpsMarkerColor, _gpsIconRotate(style, _computedHeading ?? 0)), ); } catch (_) {} @@ -6065,7 +6233,10 @@ class _MapWidgetState extends State with WidgetsBindingObserver { } /// Empty the coverage-cells source so it renders nothing (layer stays). + /// Also forgets the selected repeater's kept lines: with no cells under them + /// the Repeater Coverage Lines switch must not draw them back. Future _clearCoverageCells() async { + _repeaterCoverageLines = null; if (_mapController == null || !_coverageCellsInstalled) return; try { await _mapController! @@ -6200,22 +6371,22 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// Feature B draw: render [matched] (the points that heard [repeater]) as /// deduped status-coloured coverage cells plus a status-coloured dashed line - /// from the repeater to each cell centre. The lines layer is ensured BEFORE - /// the cells layer so the lines read on top. Returns the (capped) cells so the - /// caller can frame them with the repeater. + /// from the repeater to each cell centre. The lines only draw while the + /// Repeater Coverage Lines switch is on, but are kept either way so a flip + /// can redraw them (_onRepeaterCoverageLinesNotify). The lines layer is + /// ensured BEFORE the cells layer (switch on or off) so the lines read on + /// top. Returns every cell so the caller can frame them with the repeater. Future> _drawRepeaterCoverage(Repeater repeater, List> matched, String cvd, int gridSize) async { final steps = kCoverageGridSteps[gridSize] ?? const [0.0009, 0.00128]; final blob = gridSize == 100 ? 1 : 0; - // High cap so a repeater's full footprint draws (web parity — it draws all). - // Still bounded (farthest-first) to protect against pathological volumes. - final cells = _capByFarthest( - repeaterCoverageCells(matched, repeater, - latStep: steps[0], lonStep: steps[1], blob: blob), - (c) => c.distanceMeters, - 5000, - '[COVERAGE] repeater coverage', - ); + // Every cell draws (web parity: it draws all). Only the lines are capped: + // capping the cells farthest-first dropped the ones nearest a busy + // repeater and left a pale hole round it. + final cells = repeaterCoverageCells(matched, repeater, + latStep: steps[0], lonStep: steps[1], blob: blob); + debugLog('[COVERAGE] repeater ${repeater.id} coverage: ' + '${cells.length} cells'); if (cells.isEmpty) { await _clearCoverageCells(); await _clearCoverageLines(); @@ -6223,16 +6394,33 @@ class _MapWidgetState extends State with WidgetsBindingObserver { } await _ensureCoverageLinesLayer(); await _updateCoverageCells(cells, cvd, steps[0], steps[1]); - final segments = [ - for (final c in cells) - ( - lat: c.centerLat, - lon: c.centerLon, - color: CoverageTilePalette.colorsForStatus(cvd, c.st)[0], - ), - ]; + // Bounded (farthest-first, so the longest-reach lines survive) to protect + // against pathological volumes. + final lineCells = _capByFarthest( + cells, + (c) => c.distanceMeters, + 5000, + '[COVERAGE] repeater coverage lines', + ); + final lines = RepeaterCoverageLines( + repeaterId: _repeaterIdentity(repeater), + lat: repeater.lat, + lon: repeater.lon, + segments: [ + for (final c in lineCells) + ( + lat: c.centerLat, + lon: c.centerLon, + color: CoverageTilePalette.colorsForStatus(cvd, c.st)[0], + ), + ], + ); + _repeaterCoverageLines = lines; + final show = + _patchProviderRef?.preferences.showRepeaterCoverageLines ?? false; // Skinnier than the tile fan-out — a repeater draws many lines at once. - await _updateCoverageLines(segments, repeater.lat, repeater.lon, + // Switch off: an empty list clears any lines already drawn. + await _updateCoverageLines(lines.visible(show), repeater.lat, repeater.lon, width: 1.5); // Dim the base coverage tiles so the repeater's coloured cells + lines pop // (web `drawRepeaterCoverageFromCache` tile-dim parity). Restored in @@ -6248,8 +6436,16 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// Always-on: renders whenever polygons are present, independent of BLE /// or auth state. Idempotent — safe to call repeatedly (removes existing /// source/layers first). - Future _refreshRegionBorders(AppStateProvider appState) async { - if (_mapController == null || !_styleLoaded) return; + /// + /// One rebuild runs at a time. Calls that arrive while one is running + /// coalesce into a single follow-up rebuild, which reads the borders and + /// layer state as they are by then; every caller's future completes after + /// that follow-up. + Future _refreshRegionBorders(AppStateProvider appState) => + _regionBorderRunner.run(() => _rebuildRegionBorders(appState)); + + Future _rebuildRegionBorders(AppStateProvider appState) async { + if (!mounted || _mapController == null || !_styleLoaded) return; // Remove existing layers (label, line) and source. Order matters: layers // reference the source, so they must go first. Each try/catch tolerates @@ -6690,11 +6886,13 @@ class _MapWidgetState extends State with WidgetsBindingObserver { if (t.success) traceSuccessTotal++; } + // Each capped list contributes its length plus the identity of both ends, + // so add-one/evict-one at the 500 cap still moves the version. return Object.hashAll([ - appState.txPings.length, - appState.rxPings.length, - appState.discLogEntries.length, - appState.traceLogEntries.length, + cappedListSignature(appState.txPings), + cappedListSignature(appState.rxPings), + cappedListSignature(appState.discLogEntries), + cappedListSignature(appState.traceLogEntries), deferredMarkers.length, deferredMarkers.lastOrNull, appState.repeaters.length, @@ -6705,13 +6903,16 @@ class _MapWidgetState extends State with WidgetsBindingObserver { _focusedPingTimestamp, _focusedRepeaters.length, appState.preferences.gpsMarkerStyle, + appState.preferences.gpsMarkerColor, appState.preferences.markerStyle, txEchoTotal, discNodeTotal, traceSuccessTotal, appState.preferences.showDeferredMarkers, appState.viewingHistorySession, - appState.historySessionMarkers?.length ?? 0, + // The history list is replaced wholesale per session, so its identity + // (not just its length) tells two same-sized sessions apart. + identityHashCode(appState.historySessionMarkers), ]); } @@ -6725,8 +6926,11 @@ class _MapWidgetState extends State with WidgetsBindingObserver { }; } - /// Build a single overlay table row with colored dot, repeater ID, and SNR - TableRow _overlayRow(String repeaterId, double snr, Color dotColor, + /// Build a single overlay table row with colored dot, label, and SNR. + /// [label] is the user's nickname when the row resolves to one repeater + /// that has one, else its server name (with Repeater Names in Top Heard on), + /// else the repeater's hex ID. + TableRow _overlayRow(String label, double snr, Color dotColor, {bool isLarge = false}) { final dotSize = isLarge ? 9.0 : 6.0; final fontSize = isLarge ? 17.0 : 11.0; @@ -6750,7 +6954,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { Padding( padding: EdgeInsets.symmetric(vertical: rowVerticalPadding), child: Text( - repeaterId, + label, style: TextStyle( fontSize: fontSize, fontWeight: FontWeight.w600, @@ -6777,7 +6981,7 @@ class _MapWidgetState extends State with WidgetsBindingObserver { ); } - /// Top heard repeaters overlay (bottom-right of map) + /// Top heard repeaters overlay (top-left of map, under the GPS chip) Widget _buildTopRepeatersOverlay(AppStateProvider appState) { final topRepeaters = appState.topRepeatersBySnr; final rxSlot = appState.rxOverlaySlot; @@ -6821,17 +7025,18 @@ class _MapWidgetState extends State with WidgetsBindingObserver { defaultColumnWidth: const IntrinsicColumnWidth(), columnWidths: { 0: const IntrinsicColumnWidth(), // dot - 1: const IntrinsicColumnWidth(), // ID + 1: const IntrinsicColumnWidth(), // label 2: FixedColumnWidth(isLarge ? 12 : 8), // spacer 3: const IntrinsicColumnWidth(), // SNR }, children: [ for (final r in topRepeaters) - _overlayRow(r.repeaterId, r.snr, _overlayTypeColor(r.type), + _overlayRow(appState.topHeardLabel(r.repeaterId), r.snr, + _overlayTypeColor(r.type), isLarge: isLarge), if (rxSlot != null) - _overlayRow(rxSlot.repeaterId, rxSlot.snr, - _overlayTypeColor(OverlayPingType.rx), + _overlayRow(appState.topHeardLabel(rxSlot.repeaterId), + rxSlot.snr, _overlayTypeColor(OverlayPingType.rx), isLarge: isLarge), ], ), @@ -6859,8 +7064,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { tooltip: 'Map Style: ${mapStyle.label}', onPressed: () => _cycleMapStyle(appState), ), - // MeshMapper overlay toggle (only show when zone code available) - if (appState.zoneCode != null) + // MeshMapper overlay toggle (only show when a coverage host is known) + if (appState.coverageHostCode != null) _buildControlButton( icon: Icons.layers, tooltip: _showMeshMapperOverlay @@ -8787,7 +8992,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { iconColor: color, valueColor: color); } - /// Row-1 identity for the repeater pill: a status-coloured dot + the name. + /// Row-1 identity for the repeater pill: a status-coloured dot + the name, + /// then the user's nickname tag when it has one (edited from the sheet). Widget _repeaterPillTitle(Repeater repeater, Color statusColor) { final theme = Theme.of(context); return Row( @@ -8808,10 +9014,36 @@ class _MapWidgetState extends State with WidgetsBindingObserver { color: theme.colorScheme.onSurface), ), ), + // Selected rather than read once: the pill can outlive an edit. + Selector( + selector: (_, s) => s.nicknameForRepeater(repeater), + builder: (context, nickname, _) => nickname == null + ? const SizedBox.shrink() + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(width: 6), + RepeaterNicknameTag(nickname: nickname), + ], + ), + ), ], ); } + /// The repeater sheet's Nickname button beside Manage: "Nickname" until + /// one is set, then the nickname. Opens the nickname dialog. Only built for + /// a repeater with a full key. + Widget _nicknameButton(AppStateProvider appState, Repeater repeater) { + return Selector( + selector: (_, s) => s.nicknameForRepeater(repeater), + builder: (context, nickname, _) => RepeaterNicknameButton( + nickname: nickname, + onPressed: () => editRepeaterNickname(context, appState, repeater), + ), + ); + } + /// Row-2 stats for the repeater pill: Max Range · Hop Bytes · Clock Sync · /// Last Heard. (Online/offline status is the coloured tower in the title.) /// Max Range comes from the lazy [statsFuture]. @@ -10774,25 +11006,42 @@ class _MapWidgetState extends State with WidgetsBindingObserver { const SizedBox(height: 14), // Manage: opens the admin sheet for this repeater. Disabled with // the reason when the key is short or the app cannot manage now. + // Beside it, for a repeater with a full key, the Nickname button + // (the nickname itself once one is set). A repeater without one + // can take no nickname, so Manage keeps the full width and its + // "Full key unknown" covers both. The reason spans the whole + // row: under a half-width Manage it wrapped to two lines beside + // empty space. Builder(builder: (context) { final block = appState.repeaterAdminBlockReason; final hasKey = isFullPublicKey(repeater.hexId); final hint = !hasKey ? 'Full key unknown' : block; + final manage = FilledButton.tonalIcon( + icon: + const Icon(Icons.admin_panel_settings_outlined, size: 18), + label: const Text('Manage'), + onPressed: hint == null + ? () { + Navigator.pop(context); + showRepeaterAdminSheet(this.context, + RepeaterTarget.fromRepeater(repeater)); + } + : null, + ); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - FilledButton.tonalIcon( - icon: const Icon(Icons.admin_panel_settings_outlined, - size: 18), - label: const Text('Manage'), - onPressed: hint == null - ? () { - Navigator.pop(context); - showRepeaterAdminSheet(this.context, - RepeaterTarget.fromRepeater(repeater)); - } - : null, - ), + if (hasKey) + Row( + children: [ + Expanded(child: manage), + const SizedBox(width: 8), + Expanded( + child: _nicknameButton(appState, repeater)), + ], + ) + else + manage, if (hint != null) Padding( padding: const EdgeInsets.only(top: 4), @@ -10970,6 +11219,14 @@ class _MapWidgetState extends State with WidgetsBindingObserver { Text(repeater.displayPreset!, style: const TextStyle(fontSize: 13)), ), + // The scopes the server has confirmed for this repeater. + // Absent when it knows none or predates the field. + if (repeater.scopeChips.isNotEmpty) + _repRow( + context, + Icons.sell_outlined, + RepeaterScopeChips(chips: repeater.scopeChips), + ), // Administrators (repeater administrators feature) _repRow( context, @@ -11020,7 +11277,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { // nothing to retry against: fetchRepeaterCoveragePoints // answers null without making a request, so a Retry button // would just loop on the same answer. Say why instead. - final hasZone = (appState.zoneCode ?? '').isNotEmpty; + final hasZone = + (appState.coverageHostCode ?? '').isNotEmpty; // Pop with our own token: the result handler treats every // other value, a bare pop included, as a real close and // tears the selection down. @@ -11221,7 +11479,8 @@ class _MapWidgetState extends State with WidgetsBindingObserver { /// Paints a crisp directional arrow pointing up class _ArrowPainter extends CustomPainter { - const _ArrowPainter(); + final GpsMarkerColors colors; + const _ArrowPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11241,9 +11500,9 @@ class _ArrowPainter extends CustomPainter { canvas.drawPath(outlinePath, outlinePaint); - // Blue arrow on top + // Coloured arrow on top final arrowPaint = Paint() - ..color = const Color(0xFF2196F3) // Material blue + ..color = colors.body ..style = PaintingStyle.fill; final arrowPath = ui.Path() @@ -11262,7 +11521,8 @@ class _ArrowPainter extends CustomPainter { /// Paints a car silhouette for GPS position marker class _CarMarkerPainter extends CustomPainter { - const _CarMarkerPainter(); + final GpsMarkerColors colors; + const _CarMarkerPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11281,9 +11541,9 @@ class _CarMarkerPainter extends CustomPainter { ); canvas.drawRRect(outlineRect, outlinePaint); - // Blue car body + // Car body final bodyPaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.fill; final bodyRect = RRect.fromRectAndRadius( @@ -11292,9 +11552,9 @@ class _CarMarkerPainter extends CustomPainter { ); canvas.drawRRect(bodyRect, bodyPaint); - // Windshield (darker blue rectangle near top) + // Windshield (darker rectangle near top) final windshieldPaint = Paint() - ..color = const Color(0xFF1565C0) + ..color = colors.shade ..style = PaintingStyle.fill; final windshieldRect = RRect.fromRectAndRadius( Rect.fromCenter(center: Offset(cx, cy - 3), width: 7, height: 4), @@ -11309,7 +11569,8 @@ class _CarMarkerPainter extends CustomPainter { /// Paints a bicycle silhouette for GPS position marker class _BikeMarkerPainter extends CustomPainter { - const _BikeMarkerPainter(); + final GpsMarkerColors colors; + const _BikeMarkerPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11322,13 +11583,13 @@ class _BikeMarkerPainter extends CustomPainter { ..strokeWidth = 3; final bikePaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.stroke ..strokeWidth = 1.5 ..strokeCap = StrokeCap.round; final fillPaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.fill; // Two wheels @@ -11355,11 +11616,11 @@ class _BikeMarkerPainter extends CustomPainter { ..strokeWidth = 3.5 ..strokeCap = StrokeCap.round); - // Blue wheels + // Wheels canvas.drawCircle(leftWheel, wheelR, bikePaint); canvas.drawCircle(rightWheel, wheelR, bikePaint); - // Blue frame + // Frame canvas.drawPath(framePath, bikePaint); // Seat dot @@ -11372,7 +11633,8 @@ class _BikeMarkerPainter extends CustomPainter { /// Paints a boat silhouette for GPS position marker class _BoatMarkerPainter extends CustomPainter { - const _BoatMarkerPainter(); + final GpsMarkerColors colors; + const _BoatMarkerPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11385,7 +11647,7 @@ class _BoatMarkerPainter extends CustomPainter { ..style = PaintingStyle.fill; final fillPaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.fill; // Hull outline (wider) @@ -11419,7 +11681,7 @@ class _BoatMarkerPainter extends CustomPainter { Offset(cx, cy + 2), Offset(cx, cy - 9), Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..strokeWidth = 1.5 ..strokeCap = StrokeCap.round); @@ -11440,7 +11702,7 @@ class _BoatMarkerPainter extends CustomPainter { canvas.drawPath( sail, Paint() - ..color = const Color(0xFF64B5F6) + ..color = colors.light ..style = PaintingStyle.fill); } @@ -11450,7 +11712,8 @@ class _BoatMarkerPainter extends CustomPainter { /// Paints a walking person silhouette for GPS position marker class _WalkMarkerPainter extends CustomPainter { - const _WalkMarkerPainter(); + final GpsMarkerColors colors; + const _WalkMarkerPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11464,13 +11727,13 @@ class _WalkMarkerPainter extends CustomPainter { ..strokeCap = StrokeCap.round; final personPaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.stroke ..strokeWidth = 1.8 ..strokeCap = StrokeCap.round; final fillPaint = Paint() - ..color = const Color(0xFF2196F3) + ..color = colors.body ..style = PaintingStyle.fill; // Head outline + fill @@ -11508,9 +11771,10 @@ class _WalkMarkerPainter extends CustomPainter { bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } -/// Paints a Chomper (cyan wedge) GPS position marker — mouth faces up (direction of travel) +/// Paints a Chomper (wedge, cyan by default) GPS position marker — mouth faces up (direction of travel) class _ChomperMarkerPainter extends CustomPainter { - const _ChomperMarkerPainter(); + final GpsMarkerColors colors; + const _ChomperMarkerPainter(this.colors); @override void paint(Canvas canvas, Size size) { @@ -11541,9 +11805,9 @@ class _ChomperMarkerPainter extends CustomPainter { ..close(); canvas.drawPath(outlinePath, outlinePaint); - // Cyan body + // Body final bodyPaint = Paint() - ..color = const Color(0xFF00BCD4) + ..color = colors.body ..style = PaintingStyle.fill; final bodyPath = ui.Path() @@ -11564,10 +11828,8 @@ class _ChomperMarkerPainter extends CustomPainter { /// Paints a dog silhouette (side profile, facing right) for GPS position marker class _DogMarkerPainter extends CustomPainter { - const _DogMarkerPainter(); - - static const _blue = Color(0xFF2196F3); - static const _darkBlue = Color(0xFF1565C0); + final GpsMarkerColors colors; + const _DogMarkerPainter(this.colors); /// Body, neck, head and muzzle as one closed silhouette around [cx],[cy]. ui.Path _bodyPath(double cx, double cy) { @@ -11628,8 +11890,8 @@ class _DogMarkerPainter extends CustomPainter { final body = _bodyPath(cx, cy); final tail = _tailPath(cx, cy); - // Every white outline goes down before any blue, so the halo around one - // limb never paints over the blue of the one beside it. + // Every white outline goes down before any fill, so the halo around one + // limb never paints over the fill of the one beside it. final legOutline = Paint() ..color = Colors.white ..style = PaintingStyle.stroke @@ -11647,20 +11909,20 @@ class _DogMarkerPainter extends CustomPainter { canvas.drawPath(body, bodyOutline); final legPaint = Paint() - ..color = _blue + ..color = colors.body ..style = PaintingStyle.stroke ..strokeWidth = 2.6 ..strokeCap = StrokeCap.round; _drawLegs(canvas, cx, cy, legPaint); canvas.drawPath(tail, legPaint); - canvas.drawPath(body, Paint()..color = _blue); + canvas.drawPath(body, Paint()..color = colors.body); // Ear and nose read as darker shading on top of the body, the way the car // marker's windshield does — no white outline, so nothing separates limbs. - canvas.drawPath(_earPath(cx, cy), Paint()..color = _darkBlue); + canvas.drawPath(_earPath(cx, cy), Paint()..color = colors.shade); canvas.drawCircle( - Offset(cx + 11.3, cy - 6.3), 0.9, Paint()..color = _darkBlue); + Offset(cx + 11.3, cy - 6.3), 0.9, Paint()..color = colors.shade); canvas.drawCircle( Offset(cx + 7, cy - 8.5), 1, Paint()..color = Colors.white); } diff --git a/lib/widgets/ping_controls.dart b/lib/widgets/ping_controls.dart index 0d5fd73c..6890c7b3 100644 --- a/lib/widgets/ping_controls.dart +++ b/lib/widgets/ping_controls.dart @@ -9,6 +9,7 @@ import '../services/repeater_admin/manage_target.dart'; import '../services/repeater_admin/repeater_admin_models.dart'; import '../services/status/ping_control_labels.dart'; import '../utils/debug_logger_io.dart'; +import '../utils/ping_colors.dart'; import 'repeater_admin_sheet.dart'; import 'repeater_picker_sheet.dart'; @@ -66,6 +67,64 @@ Color _hintColor(StatusHint hint) => switch (hint) { StatusHint.outsideServiceArea => Colors.red, }; +/// Whether [mode]'s button should show the "Scopes" badge (owner ruling 15): +/// a small pill at the corner of the running mode's button while the app is +/// asking a discovered repeater for its scopes +/// ([AppStateProvider.isScopeRequestActive]). Only Passive and Hybrid ever +/// send a scope request. Active broadcasts on the shared channel and Trace +/// targets one repeater's zero-hop path, so both always answer false here, +/// regardless of [isScopeRequestActive]. +bool showsScopesBadge( + AutoMode mode, { + required bool isModeRunning, + required bool isScopeRequestActive, +}) { + switch (mode) { + case AutoMode.passive: + case AutoMode.hybrid: + return isModeRunning && isScopeRequestActive; + case AutoMode.active: + case AutoMode.targeted: + return false; + } +} + +/// The phrase a screen reader adds to a mode button's label while its +/// [ScopesBadge] shows, so the pill is not a purely visual affordance. +const String scopesBadgeSemanticsSuffix = ', asking repeaters for scopes'; + +/// [label] with [scopesBadgeSemanticsSuffix] appended while [active], else +/// [label] unchanged. +String scopesBadgeSemanticsLabel(String label, bool active) => + active ? '$label$scopesBadgeSemanticsSuffix' : label; + +/// The small "Scopes" pill itself. Purely presentational: every caller +/// decides whether to show it and where to position it (each button's own +/// corner). Colour is `PingColors.scopes`, the same accent the log tab's SCP +/// entries use. +class ScopesBadge extends StatelessWidget { + const ScopesBadge({super.key}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: PingColors.scopes, + borderRadius: BorderRadius.circular(8), + ), + child: const Text( + 'Scopes', + style: TextStyle( + fontSize: 8, + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), + ); + } +} + /// Fields the ping-control widgets depend on for their enabled/label state. /// Used with `context.select` so the controls rebuild ONLY when one of these /// changes — not on every GPS / noise-floor / battery `notifyListeners()` @@ -94,6 +153,7 @@ typedef _ControlsDeps = ({ bool floodTrafficEnabled, bool hasTargetRepeaterId, bool isRepeaterAdminActive, + bool isScopeRequestActive, }); _ControlsDeps _controlsDepsOf(AppStateProvider s) { @@ -121,6 +181,7 @@ _ControlsDeps _controlsDepsOf(AppStateProvider s) { floodTrafficEnabled: s.floodTrafficEnabled, hasTargetRepeaterId: targetId != null && targetId.isNotEmpty, isRepeaterAdminActive: s.isRepeaterAdminActive, + isScopeRequestActive: s.isScopeRequestActive, ); } @@ -143,8 +204,15 @@ typedef _TargetedDeps = ({ bool isAutoReconnecting, int repeaterCount, int? companionFirmwareVersionCode, + // Manage waits on it; the provider notifies when it flips. + bool isScopeRadioBusy, }); +/// The Trace row's Selector record, public so a test can drive the real +/// selector against a fake provider. +@visibleForTesting +Object targetedDepsOf(AppStateProvider s) => _targetedDepsOf(s); + _TargetedDeps _targetedDepsOf(AppStateProvider s) { final prefs = s.preferences; return ( @@ -162,6 +230,7 @@ _TargetedDeps _targetedDepsOf(AppStateProvider s) { isAutoReconnecting: s.isAutoReconnecting, repeaterCount: s.repeaterCount, companionFirmwareVersionCode: s.companionFirmwareVersionCode, + isScopeRadioBusy: s.isScopeRadioBusy, ); } @@ -251,7 +320,7 @@ class PingControls extends StatelessWidget { // Manual pings use 15-second cooldown, no distance requirement // When Active/Passive Mode is running, just shows "Send Ping" (disabled) Expanded( - child: _ActionButton( + child: PingActionButton( icon: Icons.cell_tower, label: portraitSendPingLabel(status, rf), color: const Color(0xFF0EA5E9), // sky-500 @@ -296,7 +365,7 @@ class PingControls extends StatelessWidget { // When OFF after being ON: shows "Cooldown Xs" like other buttons // During manual ping: shows "Cooldown Xs" (disabled) Expanded( - child: _ActionButton( + child: PingActionButton( icon: hybridEnabled ? Icons.compare_arrows : Icons.sensors, label: portraitActiveModeLabel(status, rf), @@ -332,6 +401,9 @@ class PingControls extends StatelessWidget { : txNotAllowed ? Colors.red : Colors.orange, + showScopesBadge: showsScopesBadge(AutoMode.hybrid, + isModeRunning: isHybridModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), ), ), const SizedBox(width: 10), @@ -343,7 +415,7 @@ class PingControls extends StatelessWidget { // Disabled during manual ping countdown phases, shows "Cooldown Xs" // When Active/Hybrid Mode is running, just shows "Passive Mode" (disabled, no countdown) Expanded( - child: _ActionButton( + child: PingActionButton( icon: Icons.hearing, label: portraitPassiveModeLabel(status, rf), color: passiveStopping @@ -369,6 +441,9 @@ class PingControls extends StatelessWidget { autoPingWaiting)), // Active during listening/waiting phases subtitle: passiveStopping ? 'Stopping' : null, subtitleColor: Colors.orange, + showScopesBadge: showsScopesBadge(AutoMode.passive, + isModeRunning: isPassiveModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), onPressed: () => _toggleRxAuto(context, appState), ), ), @@ -440,8 +515,10 @@ class PingControls extends StatelessWidget { } } -/// Icon-based action button with animated active state -class _ActionButton extends StatefulWidget { +/// Icon-based action button with animated active state (portrait layout). +/// Public only so widget tests can render the real button. +@visibleForTesting +class PingActionButton extends StatefulWidget { final IconData icon; final String label; final Color color; @@ -451,8 +528,10 @@ class _ActionButton extends StatefulWidget { final VoidCallback onPressed; final String? subtitle; // Optional subtitle text (e.g., "Move 5m") final Color? subtitleColor; // Optional subtitle color + final bool showScopesBadge; // Show "Scopes" badge while requesting - const _ActionButton({ + const PingActionButton({ + super.key, required this.icon, required this.label, required this.color, @@ -462,13 +541,14 @@ class _ActionButton extends StatefulWidget { this.showCooldown = false, this.subtitle, this.subtitleColor, + this.showScopesBadge = false, }); @override - State<_ActionButton> createState() => _ActionButtonState(); + State createState() => _PingActionButtonState(); } -class _ActionButtonState extends State<_ActionButton> { +class _PingActionButtonState extends State { @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; @@ -484,7 +564,7 @@ class _ActionButtonState extends State<_ActionButton> { // The button still reads as "active" via color, the dot, and the text. final bgOpacity = widget.isActive ? 0.25 : 0.12; - return Material( + final button = Material( color: Colors.transparent, child: InkWell( onTap: widget.enabled ? widget.onPressed : null, @@ -538,22 +618,33 @@ class _ActionButtonState extends State<_ActionButton> { ), ), ), + // Scopes badge while asking for scopes. Read through the + // wrapper's label instead, so not read on its own. + if (widget.showScopesBadge) + const Positioned( + top: -4, + right: -8, + child: ExcludeSemantics(child: ScopesBadge()), + ), ], ), ), const SizedBox(height: 4), - // Label - always same height - Text( - widget.label, - style: TextStyle( - fontSize: 11, - fontWeight: - widget.isActive ? FontWeight.w600 : FontWeight.w500, - color: showColor - ? (widget.isActive - ? effectiveColor - : colorScheme.onSurface) - : colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + // Label - always same height. The wrapper's Semantics already + // reads it, so it is excluded here to stop it reading twice. + ExcludeSemantics( + child: Text( + widget.label, + style: TextStyle( + fontSize: 11, + fontWeight: + widget.isActive ? FontWeight.w600 : FontWeight.w500, + color: showColor + ? (widget.isActive + ? effectiveColor + : colorScheme.onSurface) + : colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + ), ), ), // Subtitle OR the "Active" status text - always reserve space. @@ -590,6 +681,13 @@ class _ActionButtonState extends State<_ActionButton> { ), ), ); + + return Semantics( + button: true, + enabled: widget.enabled, + label: scopesBadgeSemanticsLabel(widget.label, widget.showScopesBadge), + child: button, + ); } } @@ -718,6 +816,7 @@ class _TargetedPingSectionState extends State<_TargetedPingSection> { isAutoReconnecting: appState.isAutoReconnecting, companionFirmwareSupported: companionSupportsRepeaterAdmin( appState.companionFirmwareVersionCode), + scopeRadioBusy: appState.isScopeRadioBusy, ); final manageHint = manageBlock ?? (manageTarget == null ? kChooseFromListHint : 'Manage repeater'); @@ -1175,7 +1274,7 @@ class _CompactPingControlsState extends State { (!hasTargetRepeaterId || !traceModeShowColor); // Build the buttons - final sendPingButton = _CompactActionButton( + final sendPingButton = CompactPingActionButton( icon: Icons.cell_tower, label: compactSendPingLabel(status, rf, showFullText: sendPingExpanded), color: const Color(0xFF0EA5E9), // sky-500 @@ -1194,7 +1293,7 @@ class _CompactPingControlsState extends State { onPressed: () => _sendPing(context, appState), ); - final activeModeButton = _CompactActionButton( + final activeModeButton = CompactPingActionButton( icon: hybridEnabled ? Icons.compare_arrows : Icons.sensors, label: compactActiveModeLabel(status, rf, showFullText: activeModeExpanded, @@ -1217,12 +1316,15 @@ class _CompactPingControlsState extends State { _lastActiveButton == _LastActiveButton.activeMode ? appState.cooldownTimer.progress : null, + showScopesBadge: showsScopesBadge(AutoMode.hybrid, + isModeRunning: isHybridModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), onPressed: () => hybridEnabled ? _toggleHybridAuto(context, appState) : _toggleTxRxAuto(context, appState), ); - final passiveModeButton = _CompactActionButton( + final passiveModeButton = CompactPingActionButton( icon: Icons.hearing, label: compactPassiveModeLabel(status, rf, showFullText: passiveModeExpanded, @@ -1251,11 +1353,14 @@ class _CompactPingControlsState extends State { _lastActiveButton == _LastActiveButton.passiveMode ? appState.cooldownTimer.progress : null, + showScopesBadge: showsScopesBadge(AutoMode.passive, + isModeRunning: isPassiveModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), onPressed: () => _toggleRxAuto(context, appState), ); // Build trace mode button (only used when hasTargetRepeaterId) - final traceModeButton = _CompactActionButton( + final traceModeButton = CompactPingActionButton( icon: Icons.route, label: compactTraceModeLabel(status, rf, showFullText: traceModeExpanded, @@ -1444,7 +1549,7 @@ class LandscapePingControls extends StatelessWidget { if (!txNotAllowed && floodTrafficVisible) ...[ // TX Ping button Expanded( - child: _LandscapeIconButton( + child: LandscapePingIconButton( icon: Icons.cell_tower, tooltip: txNotAllowed ? 'Passive only (zone full)' @@ -1476,7 +1581,7 @@ class LandscapePingControls extends StatelessWidget { // Active/Hybrid Mode button Expanded( - child: _LandscapeIconButton( + child: LandscapePingIconButton( icon: hybridEnabled ? Icons.compare_arrows : Icons.sensors, tooltip: txNotAllowed @@ -1502,6 +1607,9 @@ class LandscapePingControls extends StatelessWidget { isActive: txStopping || isTxModeRunning, stopping: txStopping, countdown: landscapeActiveModeCountdown(status, rf), + showScopesBadge: showsScopesBadge(AutoMode.hybrid, + isModeRunning: isHybridModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), onPressed: () => hybridEnabled ? _toggleHybridAuto(context, appState) : _toggleTxRxAuto(context, appState), @@ -1512,7 +1620,7 @@ class LandscapePingControls extends StatelessWidget { // Passive Mode button Expanded( - child: _LandscapeIconButton( + child: LandscapePingIconButton( icon: Icons.hearing, tooltip: 'Passive Mode', color: passiveStopping @@ -1537,6 +1645,9 @@ class LandscapePingControls extends StatelessWidget { (discoveryWindowActive || autoPingWaiting)), stopping: passiveStopping, countdown: landscapePassiveModeCountdown(status, rf), + showScopesBadge: showsScopesBadge(AutoMode.passive, + isModeRunning: isPassiveModeRunning, + isScopeRequestActive: appState.isScopeRequestActive), onPressed: () => _toggleRxAuto(context, appState), ), ), @@ -1670,16 +1781,35 @@ class _LandscapeAntennaSelector extends StatelessWidget { left: Radius.circular(7)), ), alignment: Alignment.center, - child: Text( - 'Internal', - style: TextStyle( - fontSize: 11, - fontWeight: (!externalAntenna && externalAntennaSet) - ? FontWeight.w600 - : FontWeight.w500, - color: (!externalAntenna && externalAntennaSet) - ? Colors.orange - : colorScheme.onSurfaceVariant, + // The quick guide's icon for this choice; scales down + // rather than overflow the narrow landscape panel. + child: FittedBox( + fit: BoxFit.scaleDown, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.directions_car, + size: 13, + color: (!externalAntenna && externalAntennaSet) + ? Colors.orange + : colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 3), + Text( + 'Internal', + style: TextStyle( + fontSize: 11, + fontWeight: + (!externalAntenna && externalAntennaSet) + ? FontWeight.w600 + : FontWeight.w500, + color: (!externalAntenna && externalAntennaSet) + ? Colors.orange + : colorScheme.onSurfaceVariant, + ), + ), + ], ), ), ), @@ -1704,16 +1834,35 @@ class _LandscapeAntennaSelector extends StatelessWidget { right: Radius.circular(7)), ), alignment: Alignment.center, - child: Text( - 'External', - style: TextStyle( - fontSize: 11, - fontWeight: (externalAntenna && externalAntennaSet) - ? FontWeight.w600 - : FontWeight.w500, - color: (externalAntenna && externalAntennaSet) - ? Colors.orange - : colorScheme.onSurfaceVariant, + // The quick guide's icon for this choice; scales down + // rather than overflow the narrow landscape panel. + child: FittedBox( + fit: BoxFit.scaleDown, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.cell_tower, + size: 13, + color: (externalAntenna && externalAntennaSet) + ? Colors.orange + : colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 3), + Text( + 'External', + style: TextStyle( + fontSize: 11, + fontWeight: + (externalAntenna && externalAntennaSet) + ? FontWeight.w600 + : FontWeight.w500, + color: (externalAntenna && externalAntennaSet) + ? Colors.orange + : colorScheme.onSurfaceVariant, + ), + ), + ], ), ), ), @@ -1727,8 +1876,10 @@ class _LandscapeAntennaSelector extends StatelessWidget { } } -/// Icon-only action button for landscape panel -class _LandscapeIconButton extends StatefulWidget { +/// Icon-only action button for landscape panel. +/// Public only so widget tests can render the real button. +@visibleForTesting +class LandscapePingIconButton extends StatefulWidget { final IconData icon; final String tooltip; final Color color; @@ -1740,8 +1891,10 @@ class _LandscapeIconButton extends StatefulWidget { // so the caller says so directly. final bool stopping; final VoidCallback onPressed; + final bool showScopesBadge; // Show "Scopes" badge while requesting - const _LandscapeIconButton({ + const LandscapePingIconButton({ + super.key, required this.icon, required this.tooltip, required this.color, @@ -1750,28 +1903,29 @@ class _LandscapeIconButton extends StatefulWidget { this.isActive = false, this.countdown, this.stopping = false, + this.showScopesBadge = false, }); @override - State<_LandscapeIconButton> createState() => _LandscapeIconButtonState(); + State createState() => _LandscapePingIconButtonState(); } -class _LandscapeIconButtonState extends State<_LandscapeIconButton> { +class _LandscapePingIconButtonState extends State { @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; // Keep the button's color (not grey) whenever the countdown badge is shown, - // mirroring portrait's `_ActionButton` showCooldown handling. Otherwise the + // mirroring portrait's `PingActionButton` showCooldown handling. Otherwise the // badge renders white text on grey (onSurfaceVariant) during cooldown. final showColor = widget.enabled || widget.isActive || widget.countdown != null; final effectiveColor = showColor ? widget.color : colorScheme.onSurfaceVariant; // Static active-state opacity (continuous pulse animation removed — see - // _ActionButton; it kept the GPU rendering all session). + // PingActionButton; it kept the GPU rendering all session). final bgOpacity = widget.isActive ? 0.25 : 0.10; - return Tooltip( + final button = Tooltip( message: widget.tooltip, child: Material( color: Colors.transparent, @@ -1791,6 +1945,7 @@ class _LandscapeIconButtonState extends State<_LandscapeIconButton> { ), child: Stack( alignment: Alignment.center, + clipBehavior: Clip.none, children: [ // Main icon Icon( @@ -1844,19 +1999,35 @@ class _LandscapeIconButtonState extends State<_LandscapeIconButton> { ), ), ), + // Scopes badge while asking for scopes. Top-left, since the + // active dot and countdown already own the right-hand + // corners on this narrow icon-only button. + if (widget.showScopesBadge) + const Positioned( + top: -4, + left: -4, + child: ScopesBadge(), + ), ], ), ), ), ), ); + + return Semantics( + label: scopesBadgeSemanticsLabel(widget.tooltip, widget.showScopesBadge), + child: button, + ); } } /// Compact toggle button for landscape panel /// Compact action button for minimized panel - horizontal pill layout -/// Supports expanding to show label when active -class _CompactActionButton extends StatefulWidget { +/// Supports expanding to show label when active. +/// Public only so widget tests can render the real button. +@visibleForTesting +class CompactPingActionButton extends StatefulWidget { final IconData icon; final String? label; // Label text (shown when expanded) final Color color; @@ -1866,8 +2037,10 @@ class _CompactActionButton extends StatefulWidget { final VoidCallback onPressed; final double? progress; // 0.0 to 1.0 for progress bar fill, null = no progress bar + final bool showScopesBadge; // Show "Scopes" badge while requesting - const _CompactActionButton({ + const CompactPingActionButton({ + super.key, required this.icon, this.label, required this.color, @@ -1876,13 +2049,14 @@ class _CompactActionButton extends StatefulWidget { this.isActive = false, this.isExpanded = false, this.progress, + this.showScopesBadge = false, }); @override - State<_CompactActionButton> createState() => _CompactActionButtonState(); + State createState() => _CompactPingActionButtonState(); } -class _CompactActionButtonState extends State<_CompactActionButton> { +class _CompactPingActionButtonState extends State { @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; @@ -1892,10 +2066,10 @@ class _CompactActionButtonState extends State<_CompactActionButton> { // Show label if colored OR if expanded (shows countdown on grey button during cooldown) final hasLabel = widget.label != null && (showColor || widget.isExpanded); // Static active-state opacity (continuous pulse animation removed — see - // _ActionButton; it kept the GPU rendering all session). + // PingActionButton; it kept the GPU rendering all session). final bgOpacity = widget.isActive ? 0.25 : 0.12; - return Material( + final button = Material( color: Colors.transparent, child: InkWell( onTap: widget.enabled ? widget.onPressed : null, @@ -1914,6 +2088,7 @@ class _CompactActionButtonState extends State<_CompactActionButton> { ), ), child: Stack( + clipBehavior: Clip.none, children: [ // Progress fill (behind content) if (widget.progress != null && widget.progress! > 0) @@ -1959,17 +2134,20 @@ class _CompactActionButtonState extends State<_CompactActionButton> { mainAxisSize: MainAxisSize.min, children: [ const SizedBox(width: 5), - Text( - widget.label!, - style: TextStyle( - fontSize: 11, - fontWeight: widget.isActive - ? FontWeight.w600 - : FontWeight.w500, - color: showColor - ? effectiveColor - : colorScheme.onSurfaceVariant - .withValues(alpha: 0.5), + // Read by the wrapper's Semantics. + ExcludeSemantics( + child: Text( + widget.label!, + style: TextStyle( + fontSize: 11, + fontWeight: widget.isActive + ? FontWeight.w600 + : FontWeight.w500, + color: showColor + ? effectiveColor + : colorScheme.onSurfaceVariant + .withValues(alpha: 0.5), + ), ), ), ], @@ -1981,10 +2159,26 @@ class _CompactActionButtonState extends State<_CompactActionButton> { ), ), ), + // Scopes badge while asking for scopes. Read through the + // wrapper's label instead, so not read on its own. + if (widget.showScopesBadge) + const Positioned( + top: -6, + right: -6, + child: ExcludeSemantics(child: ScopesBadge()), + ), ], ), ), ), ); + + return Semantics( + button: true, + enabled: widget.enabled, + label: scopesBadgeSemanticsLabel( + widget.label ?? '', widget.showScopesBadge), + child: button, + ); } } diff --git a/lib/widgets/regional_config_card.dart b/lib/widgets/regional_config_card.dart index b149cde9..46d6007c 100644 --- a/lib/widgets/regional_config_card.dart +++ b/lib/widgets/regional_config_card.dart @@ -5,6 +5,11 @@ import 'package:flutter/material.dart'; class RegionalConfigCard extends StatelessWidget { final String? zoneName; final String? zoneCode; + + /// Full code of the region group the zone belongs to, or null when the + /// zone stands alone. The compact card shows it beside the member + /// [zoneCode] in a Region row. + final String? groupCode; final List channels; final String? scope; final bool isOfflineMode; @@ -14,6 +19,7 @@ class RegionalConfigCard extends StatelessWidget { super.key, this.zoneName, this.zoneCode, + this.groupCode, this.channels = const [], this.scope, this.isOfflineMode = false, @@ -156,6 +162,15 @@ class RegionalConfigCard extends StatelessWidget { ), const SizedBox(height: 10), + // Region row: the group's full code and the member zone + if (!isOfflineMode && groupCode != null) ...[ + _buildCompactRow(context, 'Region', [ + _buildChannelChip(context, groupCode!, isDefault: true), + if (zoneCode != null) _buildChannelChip(context, zoneCode!), + ]), + const SizedBox(height: 8), + ], + // Scope row _buildCompactRow(context, 'Scope', [ _buildChannelChip(context, displayScope, isDefault: true), diff --git a/lib/widgets/repeater_nickname_dialog.dart b/lib/widgets/repeater_nickname_dialog.dart new file mode 100644 index 00000000..8f8010cb --- /dev/null +++ b/lib/widgets/repeater_nickname_dialog.dart @@ -0,0 +1,186 @@ +import 'package:flutter/material.dart'; + +import '../models/repeater.dart'; +import '../providers/app_state_provider.dart'; +import '../utils/repeater_nicknames.dart'; +import 'repeater_nickname_widgets.dart'; + +/// Asks for [repeater]'s nickname and saves the answer, skipping a result +/// that changes nothing. The one flow behind the repeater sheet's Nickname +/// button and the Settings list's add. +/// +/// The save needs no context, so it does not wait on [context] still being +/// mounted: a screen closed under the dialog keeps what was typed. +Future editRepeaterNickname( + BuildContext context, + AppStateProvider appState, + Repeater repeater, +) async { + final current = appState.nicknameForRepeater(repeater); + final result = await showRepeaterNicknameDialog( + context, + hex: repeater.displayHexId(), + serverName: repeater.name == 'Unknown' ? '' : repeater.name, + current: current, + ); + if (!nicknameResultChanges(result, current)) return; + await appState.setRepeaterNickname(repeater, result); +} + +/// Asks for a nickname for the repeater shown as [hex] (named [serverName] by +/// the server), starting from [current]. +/// +/// Returns null when cancelled, '' when the user removed the nickname, +/// otherwise the normalized nickname. +Future showRepeaterNicknameDialog( + BuildContext context, { + required String hex, + required String serverName, + String? current, +}) { + return showDialog( + context: context, + builder: (_) => _RepeaterNicknameDialog( + hex: hex, + serverName: serverName, + current: current, + ), + ); +} + +/// Whether a [showRepeaterNicknameDialog] [result] would change a repeater +/// whose nickname is [current]. +/// +/// The provider setters save and sync on every call, so callers skip a +/// cancel, the same nickname again, and a removal of nothing. +bool nicknameResultChanges(String? result, String? current) { + if (result == null) return false; + if (result.isEmpty) return current != null; + return result != current; +} + +class _RepeaterNicknameDialog extends StatefulWidget { + const _RepeaterNicknameDialog({ + required this.hex, + required this.serverName, + this.current, + }); + + final String hex; + final String serverName; + final String? current; + + @override + State<_RepeaterNicknameDialog> createState() => + _RepeaterNicknameDialogState(); +} + +class _RepeaterNicknameDialogState extends State<_RepeaterNicknameDialog> { + late final TextEditingController _controller = + TextEditingController(text: widget.current ?? ''); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _save() { + Navigator.of(context) + .pop(RepeaterNicknames.normalizeNickname(_controller.text) ?? ''); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final hex = widget.hex; + final canRemove = widget.current != null; + + return AlertDialog( + title: const Text('Repeater Nickname'), + scrollable: true, + // The default 40 pt side inset left 232 pt for Remove, Cancel and Save, + // which pushed Remove onto its own row on 320 and 360 pt phones. At 16 + // (and Remove's padding trimmed below) all three fit from 320 up. + insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + RepeaterHexBadge(hex), + if (widget.serverName.isNotEmpty) ...[ + const SizedBox(width: 8), + Flexible( + child: Text( + widget.serverName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium + ?.copyWith(color: scheme.onSurfaceVariant), + ), + ), + ], + ], + ), + const SizedBox(height: 16), + TextField( + controller: _controller, + autofocus: true, + maxLength: RepeaterNicknames.maxLength, + textCapitalization: TextCapitalization.words, + textInputAction: TextInputAction.done, + decoration: InputDecoration( + labelText: 'Nickname', + hintText: 'Mell', + // Faded: the hint is a real-looking nickname, and at the + // theme's full hint colour it read as one already typed in the + // dark theme. + hintStyle: TextStyle( + color: scheme.onSurfaceVariant.withValues(alpha: 0.6)), + border: const OutlineInputBorder(), + ), + onSubmitted: (_) => _save(), + ), + const SizedBox(height: 4), + Text( + 'Shows instead of $hex in Top Heard, and as its name on the Live ' + 'Activity, CarPlay, Apple Watch and Siri. If another repeater ' + 'shares $hex, the ID shows instead.', + style: theme.textTheme.bodySmall + ?.copyWith(color: scheme.onSurfaceVariant), + ), + ], + ), + actionsAlignment: + canRemove ? MainAxisAlignment.spaceBetween : MainAxisAlignment.end, + actions: [ + if (canRemove) + TextButton( + style: TextButton.styleFrom( + foregroundColor: scheme.error, + padding: const EdgeInsets.symmetric(horizontal: 8), + ), + onPressed: () => Navigator.of(context).pop(''), + child: const Text('Remove'), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + const SizedBox(width: 8), + FilledButton( + onPressed: _save, + child: const Text('Save'), + ), + ], + ), + ], + ); + } +} diff --git a/lib/widgets/repeater_nickname_widgets.dart b/lib/widgets/repeater_nickname_widgets.dart new file mode 100644 index 00000000..4c4fc36f --- /dev/null +++ b/lib/widgets/repeater_nickname_widgets.dart @@ -0,0 +1,133 @@ +/// The pieces the repeater nickname UI is drawn from: the repeater's hex ID +/// and the user's own name for it, side by side the way a wardriver keeps +/// them on a paper list ("5007 Mell"), and the sheet's Nickname button. +library; + +import 'package:flutter/material.dart'; + +import '../utils/repeater_marker_style.dart'; + +/// Fill and border alphas of the app's tinted status pills (the zone and +/// TX/RX counters under the title, `status_bar.dart`), so a nickname tag and +/// the Nickname button read as one of them. +const double _tagFillAlpha = 0.15; +const double _tagBorderAlpha = 0.4; + +/// A repeater's hex ID as Top Heard shows it, in a hairline box with the map +/// chip's corner radius. No fill, so it sits on any surface. The border is the +/// muted text role at half strength: the app's scheme sets no +/// `outlineVariant`, and its `outline` all but vanishes on the dark cards. +class RepeaterHexBadge extends StatelessWidget { + const RepeaterHexBadge(this.hex, {super.key}); + + final String hex; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + borderRadius: + BorderRadius.circular(RepeaterMarkerStyle.chipCornerRadius), + border: + Border.all(color: scheme.onSurfaceVariant.withValues(alpha: 0.5)), + ), + child: Text( + hex, + maxLines: 1, + softWrap: false, + style: TextStyle( + fontFamily: 'monospace', + fontWeight: FontWeight.w600, + fontSize: 13, + color: scheme.onSurface, + ), + ), + ); + } +} + +/// The user's nickname for a repeater, as a small sky-tinted pill: the map +/// pill shows it after the repeater's name. Draws nothing when [nickname] is +/// null. +class RepeaterNicknameTag extends StatelessWidget { + const RepeaterNicknameTag({super.key, required this.nickname}); + + final String? nickname; + + @override + Widget build(BuildContext context) { + final name = nickname; + if (name == null) return const SizedBox.shrink(); + final scheme = Theme.of(context).colorScheme; + final hue = scheme.secondary; + // Sky-600 on its own tint is too dim on the dark slate surfaces, so the + // text is lifted toward the theme's text colour there; the fill and the + // border stay on the true hue. + final fg = Theme.of(context).brightness == Brightness.dark + ? Color.lerp(hue, scheme.onSurface, 0.45)! + : hue; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: hue.withValues(alpha: _tagFillAlpha), + borderRadius: + BorderRadius.circular(RepeaterMarkerStyle.chipCornerRadius), + border: Border.all(color: hue.withValues(alpha: _tagBorderAlpha)), + ), + child: Text( + name, + maxLines: 1, + softWrap: false, + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: fg), + ), + ); + } +} + +/// The repeater sheet's Nickname button, beside Manage and the same height +/// and shape. Reads "Nickname" until one is set, then the nickname itself. +class RepeaterNicknameButton extends StatelessWidget { + const RepeaterNicknameButton({ + super.key, + required this.nickname, + required this.onPressed, + }); + + final String? nickname; + final VoidCallback? onPressed; + + @override + Widget build(BuildContext context) { + final name = nickname; + // Named for what it does: a bare "Mell, button" would not say the + // button edits it. + return Semantics( + button: true, + label: name == null ? 'Add nickname' : 'Edit nickname $name', + onTap: onPressed, + excludeSemantics: true, + child: OutlinedButton.icon( + // The outline takes the status pills' border recipe in the button's + // own colour. The theme default (`outline`) is slate-700 on the dark + // sheet and all but disappears. + style: OutlinedButton.styleFrom( + side: BorderSide( + color: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: _tagBorderAlpha), + ), + ), + icon: Icon(name == null ? Icons.add : Icons.label_outline, size: 18), + label: Text( + name ?? 'Nickname', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + onPressed: onPressed, + ), + ); + } +} diff --git a/lib/widgets/repeater_picker_sheet.dart b/lib/widgets/repeater_picker_sheet.dart index e7258590..028daaae 100644 --- a/lib/widgets/repeater_picker_sheet.dart +++ b/lib/widgets/repeater_picker_sheet.dart @@ -9,7 +9,12 @@ import '../utils/distance_formatter.dart'; import '../utils/ping_colors.dart'; /// Show a bottom sheet repeater picker and return the selected repeater. -Future showRepeaterPicker(BuildContext context) { +/// [include], when given, limits the list to the repeaters it accepts, so a +/// caller never offers one it would then have to refuse. +Future showRepeaterPicker( + BuildContext context, { + bool Function(Repeater repeater)? include, +}) { return showModalBottomSheet( context: context, isScrollControlled: true, @@ -25,6 +30,7 @@ Future showRepeaterPicker(BuildContext context) { expand: false, builder: (context, scrollController) => _RepeaterPickerBody( scrollController: scrollController, + include: include, ), ), ); @@ -32,8 +38,9 @@ Future showRepeaterPicker(BuildContext context) { class _RepeaterPickerBody extends StatefulWidget { final ScrollController scrollController; + final bool Function(Repeater repeater)? include; - const _RepeaterPickerBody({required this.scrollController}); + const _RepeaterPickerBody({required this.scrollController, this.include}); @override State<_RepeaterPickerBody> createState() => _RepeaterPickerBodyState(); @@ -104,7 +111,10 @@ class _RepeaterPickerBodyState extends State<_RepeaterPickerBody> { @override Widget build(BuildContext context) { final appState = context.watch(); - final repeaters = appState.repeaters; + final include = widget.include; + final repeaters = include == null + ? appState.repeaters + : appState.repeaters.where(include).toList(); final position = appState.currentPosition; final isImperial = appState.preferences.isImperial; final colorScheme = Theme.of(context).colorScheme; diff --git a/lib/widgets/repeater_scope_chips.dart b/lib/widgets/repeater_scope_chips.dart new file mode 100644 index 00000000..ed694e11 --- /dev/null +++ b/lib/widgets/repeater_scope_chips.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; + +import '../models/repeater_scope.dart'; + +/// The repeater detail sheet's Scopes row: one chip per scope, the default +/// starred, folded after [kRepeaterScopeChipsShown] behind a "+N more" chip. +/// Tapping a chip says where it came from. Pure display: it reads the chips +/// it is given and changes no app state. +class RepeaterScopeChips extends StatefulWidget { + final List chips; + + const RepeaterScopeChips({super.key, required this.chips}); + + @override + State createState() => _RepeaterScopeChipsState(); +} + +class _RepeaterScopeChipsState extends State { + bool _expanded = false; + + static const Color _star = Color(0xFFE8B923); + + void _showDetails(RepeaterScopeChip chip) { + showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(chip.label == '?' ? 'Default scope' : chip.label), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final line in chip.details) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text(line), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), + child: const Text('OK'), + ), + ], + ), + ); + } + + Widget _chip(BuildContext context, Widget child, {VoidCallback? onTap}) { + final scheme = Theme.of(context).colorScheme; + return Material( + color: scheme.surfaceContainerHighest, + shape: StadiumBorder( + side: BorderSide(color: scheme.outlineVariant), + ), + child: InkWell( + customBorder: const StadiumBorder(), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3), + child: DefaultTextStyle.merge( + style: const TextStyle(fontSize: 12), + child: child, + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final chips = widget.chips; + final folded = + !_expanded && chips.length > kRepeaterScopeChipsShown; + final shown = + folded ? chips.take(kRepeaterScopeChipsShown).toList() : chips; + return Wrap( + spacing: 6, + runSpacing: 6, + children: [ + for (final c in shown) + _chip( + context, + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (c.label != '?') Text(c.label), + if (c.isDefault) + Padding( + padding: EdgeInsets.only(left: c.label == '?' ? 0 : 3), + child: const Text('★', style: TextStyle(color: _star)), + ), + if (c.label == '?') const Text(' ?'), + ], + ), + onTap: () => _showDetails(c), + ), + if (folded) + _chip( + context, + Text('+${chips.length - kRepeaterScopeChipsShown} more'), + onTap: () => setState(() => _expanded = true), + ), + ], + ); + } +} diff --git a/lib/widgets/scope_discovery_firmware_note.dart b/lib/widgets/scope_discovery_firmware_note.dart new file mode 100644 index 00000000..5de39946 --- /dev/null +++ b/lib/widgets/scope_discovery_firmware_note.dart @@ -0,0 +1,24 @@ +import 'package:flutter/material.dart'; + +/// The extra line shown under the Scope Discovery switch while the connected +/// radio's companion firmware is below the feature's floor (companion +/// firmware v1.16.0). The switch keeps working either way: the setting is +/// saved, but nothing is asked and nothing extra goes on the air until the +/// firmware catches up. +class ScopeDiscoveryFirmwareNote extends StatelessWidget { + const ScopeDiscoveryFirmwareNote({super.key, required this.show}); + + final bool show; + + @override + Widget build(BuildContext context) { + if (!show) return const SizedBox.shrink(); + return const Padding( + padding: EdgeInsets.only(top: 4), + child: Text( + 'Your radio needs firmware v1.16.0 or newer for this.', + style: TextStyle(color: Colors.amber, fontSize: 12), + ), + ); + } +} diff --git a/lib/widgets/status_bar.dart b/lib/widgets/status_bar.dart index 5ceb826e..2632628d 100644 --- a/lib/widgets/status_bar.dart +++ b/lib/widgets/status_bar.dart @@ -3,9 +3,36 @@ import 'package:provider/provider.dart'; import '../models/connection_state.dart'; import '../providers/app_state_provider.dart'; +import '../utils/compact_count.dart'; import '../utils/distance_formatter.dart'; import '../utils/ping_colors.dart'; +/// What the status bar's shared Trace/Scope slot shows. +enum StatusBarSlot { trace, scope, hidden } + +/// The one slot Trace and Scope share. Trace mode and scope discovery never +/// run together (scope discovery only follows a Passive or Hybrid discovery), +/// so one chip is enough: Trace while Trace is the session's mode, else Scope +/// while scope discovery can run or once this session has counted a scope, +/// else nothing. Each count lives on in [PingStats] across a swap. +StatusBarSlot statusBarSharedSlot({ + required bool targetedMode, + required bool scopeDiscoveryOn, + required int scopeCount, +}) { + if (targetedMode) return StatusBarSlot.trace; + if (scopeDiscoveryOn || scopeCount > 0) return StatusBarSlot.scope; + return StatusBarSlot.hidden; +} + +// Chip spacing, kept tight so five chips and the region chip fit a 375 pt +// phone with 4-digit counts. The vertical padding sets the tap height and is +// left alone. +const double _chipPadH = 5; +const double _chipPadV = 4; +const double _chipIconGap = 2; +const double _chipGap = 5; + /// Status bar showing GPS, connection, and queue status class StatusBar extends StatefulWidget { const StatusBar({super.key}); @@ -20,7 +47,7 @@ class _StatusBarState extends State { final appState = context.watch(); return Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceContainerHighest, boxShadow: [ @@ -36,10 +63,21 @@ class _StatusBarState extends State { // GPS region indicator (chip style) _buildGpsRegionChip(context, appState), - const Spacer(), - - // Stats summary - _buildStatsIndicator(context, appState), + const SizedBox(width: _chipGap), + + // Stats summary. Takes the rest of the row and, when the chips + // still do not fit (large Accessibility text, a very narrow + // screen), scales the whole group down rather than clip a chip. + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerRight, + child: _buildStatsIndicator(context, appState), + ), + ), + ), ], ), ); @@ -48,7 +86,8 @@ class _StatusBarState extends State { /// Show info popup as bottom sheet void _showInfoPopup(BuildContext context, String id) { final appState = context.read(); - final (title, description, icon, color) = _getPopupContent(id, appState); + final (title, description, icon, color) = + _getPopupContent(context, id, appState); showModalBottomSheet( context: context, @@ -121,7 +160,7 @@ class _StatusBarState extends State { /// Get content for the popup based on ID (String, String, IconData, Color) _getPopupContent( - String id, AppStateProvider appState) { + BuildContext context, String id, AppStateProvider appState) { switch (id) { case 'gps': if (appState.offlineMode) { @@ -135,7 +174,7 @@ class _StatusBarState extends State { if (appState.inZone == true && appState.zoneCode != null) { if (!appState.isConnected) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an authorized zone. Connect to a device to start wardriving.', Icons.flight, Colors.grey @@ -146,7 +185,7 @@ class _StatusBarState extends State { // deliberate regional setting (blue). if (appState.floodDisabled) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'Your regional admin has turned off flood traffic here, so Active and Hybrid modes are unavailable. The zone is not full. Passive and Trace modes still work.', Icons.flight, Colors.blue @@ -154,14 +193,14 @@ class _StatusBarState extends State { } if (!appState.txAllowed) { return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an authorized zone. However, the zone is at Active Wardrive capacity. You can still wardrive, but only Passive mode works.', Icons.flight, Colors.red ); } return ( - '${appState.zoneName ?? appState.zoneCode} Zone', + '${appState.displayZoneName ?? appState.shortZoneCode} Zone', 'You\'re in an active zone with ${appState.zoneSlotsAvailable ?? "?"} TX slots available. Ready to wardrive!', Icons.flight, Colors.green @@ -220,6 +259,15 @@ class _StatusBarState extends State { PingColors.traceSuccess ); + case 'scope': + return ( + 'Scopes', + 'Repeaters that answered a scope request this session, one per answer, as listed under SCP in the Log tab. ' + 'Scope discovery asks the strongest repeaters a Passive or Hybrid discovery found which scopes they carry.', + Icons.travel_explore, + PingColors.scopesFor(Theme.of(context).brightness) + ); + case 'upload': return ( 'Uploaded', @@ -264,7 +312,7 @@ class _StatusBarState extends State { : Colors.red) : Colors .grey; // Grey when not connected, red when zone is at TX capacity - text = appState.zoneCode!; + text = appState.shortZoneCode!; } else if (appState.inZone == false) { // GPS locked but outside any zone icon = Icons.flight; @@ -309,53 +357,72 @@ class _StatusBarState extends State { } Widget _buildStatsIndicator(BuildContext context, AppStateProvider appState) { + final stats = appState.pingStats; + final slot = statusBarSharedSlot( + targetedMode: appState.autoMode == AutoMode.targeted, + scopeDiscoveryOn: appState.scopeDiscoveryActive, + scopeCount: stats.scopeCount, + ); return Row( + key: const ValueKey('status-bar-stats'), mainAxisSize: MainAxisSize.min, children: [ // TX count chip (animated) _AnimatedStatChip( icon: Icons.arrow_upward, - value: appState.pingStats.txCount, + value: stats.txCount, color: PingColors.txSuccess, onTap: () => _showInfoPopup(context, 'tx'), ), - const SizedBox(width: 8), + const SizedBox(width: _chipGap), // RX count chip (animated) _AnimatedStatChip( icon: Icons.arrow_downward, - value: appState.pingStats.rxCount, + value: stats.rxCount, color: PingColors.rx, onTap: () => _showInfoPopup(context, 'rx'), ), - const SizedBox(width: 8), + const SizedBox(width: _chipGap), // DISC count chip (animated) _AnimatedStatChip( icon: Icons.radar, - value: appState.pingStats.discCount, + value: stats.discCount, color: PingColors.discSuccess, onTap: () => _showInfoPopup(context, 'disc'), ), - const SizedBox(width: 8), - - // Trace count chip (animated) - _AnimatedStatChip( - icon: Icons.route, - value: appState.pingStats.traceCount, - color: PingColors.traceSuccess, - onTap: () => _showInfoPopup(context, 'trace'), - ), + // Shared Trace / Scope slot. Keyed per kind so a swap starts a fresh + // chip instead of animating one count into the other. + if (slot == StatusBarSlot.trace) ...[ + const SizedBox(width: _chipGap), + _AnimatedStatChip( + key: const ValueKey('status-bar-trace'), + icon: Icons.route, + value: stats.traceCount, + color: PingColors.traceSuccess, + onTap: () => _showInfoPopup(context, 'trace'), + ), + ] else if (slot == StatusBarSlot.scope) ...[ + const SizedBox(width: _chipGap), + _AnimatedStatChip( + key: const ValueKey('status-bar-scope'), + icon: Icons.travel_explore, + value: stats.scopeCount, + color: PingColors.scopesFor(Theme.of(context).brightness), + onTap: () => _showInfoPopup(context, 'scope'), + ), + ], - const SizedBox(width: 8), + const SizedBox(width: _chipGap), // Uploaded count chip (animated) _AnimatedStatChip( icon: Icons.cloud_done, - value: appState.pingStats.successfulUploads, + value: stats.successfulUploads, color: Colors.teal[400]!, onTap: () => _showInfoPopup(context, 'upload'), ), @@ -372,7 +439,8 @@ class _StatusBarState extends State { return GestureDetector( onTap: onTap, child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: _chipPadH, vertical: _chipPadV), decoration: BoxDecoration( color: color.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(8), @@ -382,7 +450,7 @@ class _StatusBarState extends State { mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 14, color: color), - const SizedBox(width: 4), + const SizedBox(width: _chipIconGap), Text( value, style: TextStyle( @@ -398,7 +466,9 @@ class _StatusBarState extends State { } } -/// Animated stat chip that bounces and highlights when value increments +/// Animated stat chip that bounces and highlights when value increments. +/// [value] stays the raw count so the increment check is exact; only the +/// text is shortened (`formatCompactCount`). class _AnimatedStatChip extends StatefulWidget { final IconData icon; final int value; @@ -406,6 +476,7 @@ class _AnimatedStatChip extends StatefulWidget { final VoidCallback? onTap; const _AnimatedStatChip({ + super.key, required this.icon, required this.value, required this.color, @@ -466,7 +537,8 @@ class _AnimatedStatChipState extends State<_AnimatedStatChip> return Transform.scale( scale: _scaleAnimation.value, child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: _chipPadH, vertical: _chipPadV), decoration: BoxDecoration( color: widget.color.withValues(alpha: _highlightAnimation.value), @@ -477,9 +549,9 @@ class _AnimatedStatChipState extends State<_AnimatedStatChip> mainAxisSize: MainAxisSize.min, children: [ Icon(widget.icon, size: 14, color: widget.color), - const SizedBox(width: 4), + const SizedBox(width: _chipIconGap), Text( - '${widget.value}', + formatCompactCount(widget.value), style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, diff --git a/lib/widgets/update_required_panel.dart b/lib/widgets/update_required_panel.dart new file mode 100644 index 00000000..2f2f4ad6 --- /dev/null +++ b/lib/widgets/update_required_panel.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; + +import '../utils/store_links.dart'; + +/// Replaces the connection error card when the server refused this build as +/// out of date. The button opens the store the app was installed from. +class UpdateRequiredPanel extends StatelessWidget { + final AppUpdateRequirement requirement; + final ValueChanged onUpdate; + final VoidCallback onBack; + + const UpdateRequiredPanel({ + super.key, + required this.requirement, + required this.onUpdate, + required this.onBack, + }); + + static const String title = 'Update MeshMapper to continue'; + static const String body = + 'This version of the app is out of date, update the MeshMapper app on ' + 'your phone to keep wardriving.'; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isLandscape = + MediaQuery.of(context).orientation == Orientation.landscape; + + return SafeArea( + child: Center( + child: SingleChildScrollView( + padding: EdgeInsets.all(isLandscape ? 16 : 32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.system_update, + size: isLandscape ? 48 : 64, + color: Colors.orange, + ), + SizedBox(height: isLandscape ? 8 : 16), + Text( + title, + textAlign: TextAlign.center, + style: theme.textTheme.titleMedium, + ), + const SizedBox(height: 8), + Text( + body, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 8), + Text( + requirement.versionLine, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey, + fontSize: 11, + ), + ), + SizedBox(height: isLandscape ? 12 : 24), + ElevatedButton.icon( + onPressed: () => onUpdate(requirement.link), + icon: const Icon(Icons.open_in_new), + label: Text(requirement.link.label), + ), + const SizedBox(height: 8), + TextButton( + onPressed: onBack, + child: const Text('Back'), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/upload_logs_dialog.dart b/lib/widgets/upload_logs_dialog.dart index ccd211bc..e69d1fdb 100644 --- a/lib/widgets/upload_logs_dialog.dart +++ b/lib/widgets/upload_logs_dialog.dart @@ -64,7 +64,9 @@ class _UploadLogsSheetState extends State { Future _loadUploadableFiles() async { try { - final files = await widget.appState.prepareDebugLogsForUpload(); + // Listed as they are. The live log is rotated once, at submit, never + // on opening the sheet: that left a stub file behind every cancel. + final files = await widget.appState.listDebugLogFiles(); if (mounted) { setState(() { _availableLogFiles = files; @@ -156,24 +158,14 @@ class _UploadLogsSheetState extends State { }); try { - // Rotate the current log file now that the user has committed to uploading + // The one rotation: the live log is closed in place (same path) so it + // is complete, and a new current file takes over. The selection was + // made by path, so it still names the closed file, and the new current + // is not in the returned list. final freshFiles = await widget.appState.prepareDebugLogsForUpload(); - - // Build the upload list using the user's selection applied to the freshly rotated files. - // Selected paths from before rotation still match, plus any newly rotated file is included. - final selectedPaths = Set.from(_selectedLogFiles); - final filesToUpload = - freshFiles.where((f) => selectedPaths.contains(f.path)).toList(); - - // If the rotation produced a new file that wasn't in the original selection - // (i.e. the previously-active log that just got rotated), include it too - // since the user selected "all" initially and this file has new content. - final newFiles = - freshFiles.where((f) => !selectedPaths.contains(f.path)).toList(); - if (newFiles.isNotEmpty && - selectedPaths.length == _availableLogFiles.length) { - filesToUpload.addAll(newFiles); - } + final filesToUpload = freshFiles + .where((f) => _selectedLogFiles.contains(f.path)) + .toList(); if (filesToUpload.isEmpty) { if (mounted) { @@ -522,6 +514,9 @@ class _UploadLogsSheetState extends State { sizeDisplay = '${(sizeBytes / 1024).toStringAsFixed(1)} KB'; } + if (file.path == DebugFileLogger.currentLogPath) { + sizeDisplay = '$sizeDisplay (current)'; + } return ListTile( dense: true, diff --git a/play_store.py b/play_store.py new file mode 100755 index 00000000..ff55c5d4 --- /dev/null +++ b/play_store.py @@ -0,0 +1,1132 @@ +#!/usr/bin/env python3 +"""MeshMapper Google Play release manager. + +Puts an Android App Bundle on a Google Play track and replaces the phone +screenshots, through the Google Play Developer API (androidpublisher v3), for +MeshMapper (package net.meshmapper.app): + + status read-only overview: tracks, releases (with review state), + uploaded bundles, app details, listing languages + upload upload an AAB (or assign an already uploaded --version-code) to a + track with release notes; a stable release is + --track production --status completed, which is a 100% rollout + promote copy the latest release of one track to another + screenshots replace the phone screenshots of the default language + +Release text never lives in the repo: release notes come from a notes file you +pass on the command line (500 characters at most), screenshots from the folder +the capture script writes (/android-phone/*.png, 2 to 8 files). + +Every change happens inside a Play "edit" (a draft transaction). Nothing goes +live until the edit is committed, and on any failure the edit is deleted so +nothing half-applied lingers. Every write subcommand is a dry run by default; +pass --apply to commit. upload and screenshots also take --validate: stage the +whole change in an edit, ask Play to validate it (edits:validate), then delete +the edit. --validate never commits, so it proves the service account may write +without publishing anything. + +upload is safe to re-run: a versionCode Play already has is assigned to the +track instead of uploaded again, and a track that already holds exactly the +release (versionCodes, status, notes) is left alone with nothing committed. + +The listing text is never touched, and this script only writes English: it +stops when the app has a listing in any language other than en*. Release notes +and screenshots go to the app's default language (override the notes language +with --lang). + +Auth: PLAY_SERVICE_ACCOUNT_JSON (the service account's JSON key, e.g. +~/.play/play-publisher.json, chmod 600) in the environment or +~/.meshmapper_release.env (environment wins). PLAY_PACKAGE_NAME overrides the +built-in package name. The service account must be invited in Play Console > +Users and permissions with, for MeshMapper: Release to production, Manage store +presence and View app information. New grants can take 24-36 h to reach the +API. The OAuth token (RS256 JWT) is signed with the openssl CLI. + +Usage: + ./play_store.py status + ./play_store.py upload --track production --status completed --notes-file notes.txt + ./play_store.py upload --track production --status completed --notes-file notes.txt --validate + ./play_store.py upload --track production --status completed --notes-file notes.txt --apply + ./play_store.py upload --track production --version-code 1789991039 --notes-file notes.txt + ./play_store.py promote --from beta --to production --apply + ./play_store.py screenshots --dir shots/ # dry run + ./play_store.py screenshots --dir shots/ --validate + ./play_store.py screenshots --dir shots/ --apply + +Add --no-review to upload/promote/screenshots --apply if Play refuses the commit +asking for changesNotSentForReview (the changes then go to review from Console). + +Python 3 standard library only, plus the openssl CLI. PLAY_API_BASE overrides the +API host (for exercising the flow against a stub server). +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request +import zipfile + +REPO_DIR = os.path.dirname(os.path.abspath(__file__)) +LAST_BUILD = os.path.join(REPO_DIR, '.last_build') +RELEASE_ENV = os.path.expanduser('~/.meshmapper_release.env') +DEFAULT_PACKAGE = 'net.meshmapper.app' +API_BASE = os.environ.get('PLAY_API_BASE', 'https://androidpublisher.googleapis.com').rstrip('/') +SCOPE = 'https://www.googleapis.com/auth/androidpublisher' +DEFAULT_TOKEN_URI = 'https://oauth2.googleapis.com/token' + +MAX_NOTES = 500 +PHONE_FOLDER = 'android-phone' +PHONE_IMAGE_TYPE = 'phoneScreenshots' +MIN_PHONE_SCREENSHOTS = 2 +MAX_PHONE_SCREENSHOTS = 8 +MAX_SCREENSHOT_BYTES = 8 * 1024 * 1024 +MIN_SCREENSHOT_SIDE = 320 +MAX_SCREENSHOT_SIDE = 3840 + +TRACK_LABELS = { + 'internal': 'Internal testing', + 'alpha': 'Closed testing (alpha)', + 'beta': 'Open testing (beta)', + 'production': 'Production', +} +STANDARD_TRACKS = ['internal', 'alpha', 'beta', 'production'] + +# Hint context filled in as commands run, used to explain known API errors +HINT = {} + + +class PlayError(Exception): + """A fatal, user-facing error. main() prints it and exits 1.""" + + +class ApiError(PlayError): + def __init__(self, status, message, what): + self.status = status + self.api_message = message + super().__init__(f'{what} failed (HTTP {status}): {message}') + + +# --------------------------------------------------------------------------- +# Config +# --------------------------------------------------------------------------- + +def parse_env_file(path): + """Parse simple KEY=value lines (optional 'export ', quotes, # comments).""" + values = {} + if not os.path.isfile(path): + return values + with open(path, encoding='utf-8') as fh: + for raw in fh: + line = raw.strip() + if not line or line.startswith('#'): + continue + if line.startswith('export '): + line = line[len('export '):].strip() + key, sep, value = line.partition('=') + key = key.strip() + if not sep or not re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', key): + continue + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'': + value = value[1:-1] + elif ' #' in value: + value = value.split(' #', 1)[0].rstrip() + values[key] = value + return values + + +def load_release_env(): + """Parse ~/.meshmapper_release.env. Real environment variables take + precedence, and PLAY_* ones are picked up even when the file lacks them.""" + values = parse_env_file(RELEASE_ENV) + for key in list(values): + if os.environ.get(key): + values[key] = os.environ[key] + for key, value in os.environ.items(): + if key.startswith('PLAY_') and value: + values[key] = value + return values + + +ENV = load_release_env() + + +def env(key, default=''): + return ENV.get(key, default) or default + + +def package_name(): + return env('PLAY_PACKAGE_NAME', DEFAULT_PACKAGE) + + +def read_last_build(): + return parse_env_file(LAST_BUILD) + + +def default_language(details: dict, override: str | None) -> str: + """The language release notes and screenshots go to: --lang when given, else + the app's default language from edits.details.""" + if override: + return override + language = (details or {}).get('defaultLanguage') + if not language: + raise PlayError('Play reports no default language for this app; pass --lang.') + return language + + +def check_languages(languages: list[str]) -> None: + """This script only writes English text. Stop at the first other listing + language rather than leave it with stale or untranslated text.""" + for language in languages: + if not language.startswith('en'): + raise PlayError(f'The store listing has a {language} language. This script only ' + f'writes English text; handle {language} in Play Console first.') + + +def check_screenshot_size(w: int, h: int) -> None: + """Play wants each side 320-3840 px and the long side at most twice the short.""" + low, high = min(w, h), max(w, h) + if low < MIN_SCREENSHOT_SIDE or high > MAX_SCREENSHOT_SIDE: + raise PlayError(f'{w}x{h}: each side must be {MIN_SCREENSHOT_SIDE}-{MAX_SCREENSHOT_SIDE} px') + if high > 2 * low: + raise PlayError(f'{w}x{h}: the long side may be at most twice the short side') + + +# --------------------------------------------------------------------------- +# Credentials and OAuth +# --------------------------------------------------------------------------- + +SETUP_HINT = ( + 'Set PLAY_SERVICE_ACCOUNT_JSON (env or ~/.meshmapper_release.env) to the service\n' + 'account JSON key, e.g. ~/.play/play-publisher.json (chmod 600).\n' + 'See the header of play_store.py for the Play Console permissions it needs.' +) + + +def load_credentials(): + path = env('PLAY_SERVICE_ACCOUNT_JSON') + if not path: + raise PlayError('PLAY_SERVICE_ACCOUNT_JSON is not set.\n' + SETUP_HINT) + path = os.path.expanduser(path) + if not os.path.isfile(path): + raise PlayError(f'Service account key not found: {path}\n' + SETUP_HINT) + if os.stat(path).st_mode & 0o077: + print(f'Warning: {path} is readable by other users; run: chmod 600 {path}') + try: + with open(path, encoding='utf-8') as fh: + creds = json.load(fh) + except (OSError, ValueError) as exc: + raise PlayError(f'Could not read service account key {path}: {exc}') + if not isinstance(creds, dict) or creds.get('type') != 'service_account': + raise PlayError(f'{path} is not a service account JSON key (type != service_account).') + for field in ('client_email', 'private_key'): + if not creds.get(field): + raise PlayError(f'{path} has no {field}; download a fresh JSON key.') + return creds + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b'=').decode('ascii') + + +def rs256_sign(private_key_pem, data): + """Sign with openssl, keeping the key in a 0600 temp file only while signing.""" + tmpdir = tempfile.mkdtemp(prefix='play_store_') + key_path = os.path.join(tmpdir, 'key.pem') + try: + fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as fh: + fh.write(private_key_pem) + try: + result = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', key_path], + input=data, capture_output=True) + except FileNotFoundError: + raise PlayError('openssl is required but not installed.') + if result.returncode != 0 or not result.stdout: + raise PlayError('openssl could not sign the token request; is private_key in ' + 'the service account JSON intact?') + return result.stdout + finally: + if os.path.exists(key_path): + os.remove(key_path) + shutil.rmtree(tmpdir, ignore_errors=True) + + +def build_jwt(creds, now=None): + now = int(now if now is not None else time.time()) + header = {'alg': 'RS256', 'typ': 'JWT'} + if creds.get('private_key_id'): + header['kid'] = creds['private_key_id'] + payload = { + 'iss': creds['client_email'], + 'scope': SCOPE, + 'aud': creds.get('token_uri') or DEFAULT_TOKEN_URI, + 'iat': now, + 'exp': now + 3600, + } + signing_input = (b64url(json.dumps(header, separators=(',', ':')).encode()) + '.' + + b64url(json.dumps(payload, separators=(',', ':')).encode())) + signature = rs256_sign(creds['private_key'], signing_input.encode('ascii')) + return signing_input + '.' + b64url(signature) + + +def fetch_access_token(creds): + token_uri = creds.get('token_uri') or DEFAULT_TOKEN_URI + body = urllib.parse.urlencode({ + 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', + 'assertion': build_jwt(creds), + }).encode() + req = urllib.request.Request(token_uri, data=body, method='POST', + headers={'Content-Type': 'application/x-www-form-urlencoded'}) + try: + with urllib.request.urlopen(req, timeout=60) as resp: + data = json.loads(resp.read().decode('utf-8')) + except urllib.error.HTTPError as exc: + raw = exc.read().decode('utf-8', 'replace') + try: + err = json.loads(raw) + msg = err.get('error_description') or err.get('error') or raw + if err.get('error') and err.get('error_description'): + msg = f"{err['error']}: {err['error_description']}" + except ValueError: + msg = raw.strip()[:500] + raise PlayError(f'Google OAuth token exchange failed (HTTP {exc.code}): {msg}\n' + 'Check that the service account key is current (not deleted or ' + 'rotated in Google Cloud) and the system clock is correct.') + except urllib.error.URLError as exc: + raise PlayError(f'Could not reach {token_uri}: {exc.reason}') + if not data.get('access_token'): + raise PlayError('Google OAuth token exchange returned no access_token.') + return data['access_token'] + + +# --------------------------------------------------------------------------- +# API client and edits +# --------------------------------------------------------------------------- + +class PlayApi: + def __init__(self, creds, package): + self.package = package + self.client_email = creds['client_email'] + self.token = fetch_access_token(creds) + + def call(self, method, path, body=None, *, upload_path=None, upload_bytes=None, + content_type=None, query=None, timeout=120, what=None): + upload = upload_path is not None or upload_bytes is not None + prefix = '/upload/androidpublisher/v3' if upload else '/androidpublisher/v3' + url = f'{API_BASE}{prefix}/applications/{urllib.parse.quote(self.package)}{path}' + params = dict(query or {}) + if upload: + params['uploadType'] = 'media' + if params: + url += '?' + urllib.parse.urlencode(params) + headers = {'Authorization': f'Bearer {self.token}'} + data = None + fileobj = None + if upload_path is not None: + fileobj = open(upload_path, 'rb') + data = fileobj + headers['Content-Type'] = content_type or 'application/octet-stream' + headers['Content-Length'] = str(os.path.getsize(upload_path)) + elif upload_bytes is not None: + data = upload_bytes + headers['Content-Type'] = content_type or 'application/octet-stream' + elif body is not None: + data = json.dumps(body).encode('utf-8') + headers['Content-Type'] = 'application/json' + elif method in ('POST', 'PUT', 'PATCH'): + data = b'' + what = what or f'{method} {path}' + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read() + except urllib.error.HTTPError as exc: + raw = exc.read().decode('utf-8', 'replace') + message = raw.strip()[:1000] or exc.reason + try: + err = json.loads(raw).get('error', {}) + if isinstance(err, dict) and err.get('message'): + message = err['message'] + except (ValueError, AttributeError): + pass + raise ApiError(exc.code, message, what) + except urllib.error.URLError as exc: + raise PlayError(f'{what} failed: could not reach {API_BASE}: {exc.reason}') + except TimeoutError: + raise PlayError(f'{what} timed out after {timeout}s.') + finally: + if fileobj: + fileobj.close() + if not raw: + return {} + try: + return json.loads(raw.decode('utf-8')) + except ValueError: + return {} + + +class Edit: + """An androidpublisher edit. Deleted on exit unless committed.""" + + def __init__(self, api): + self.api = api + self.id = None + self.deleted = False + + def __enter__(self): + resp = self.api.call('POST', '/edits', {}, what='Opening an edit (edits.insert)') + self.id = resp.get('id') + if not self.id: + raise PlayError('edits.insert returned no edit id.') + return self + + def __exit__(self, exc_type, exc, tb): + if self.id: + try: + self.api.call('DELETE', f'/edits/{self.id}', what='edits.delete') + self.deleted = True + except PlayError as err: + print(f'Warning: could not delete edit {self.id}: {err}') + print('It expires on its own; nothing in it was committed.') + self.id = None + return False + + def call(self, method, path, body=None, **kw): + return self.api.call(method, f'/edits/{self.id}{path}', body, **kw) + + def validate(self): + """Ask Play to validate everything staged in this edit (edits.validate).""" + self.api.call('POST', f'/edits/{self.id}:validate', + what='Validating the edit (edits.validate)') + + def commit(self, no_review=False): + query = {'changesNotSentForReview': 'true'} if no_review else None + self.api.call('POST', f'/edits/{self.id}:commit', query=query, + what='Committing the edit (edits.commit)') + self.id = None # committed edits no longer exist; nothing to delete + + +def explain_api_error(err): + """Extra guidance for known Play API errors.""" + low = (err.api_message or '').lower() + track = HINT.get('track', '') + if re.search(r'version code.*(already been used|has already been)', low): + vc = HINT.get('version_code', 'N') + flags = HINT.get('upload_flags', '') + return ( + f'versionCode {vc} was already uploaded to Play; a versionCode can only be\n' + 'uploaded once. To put that existing build on a track without uploading:\n' + f' ./play_store.py upload --track {track} --version-code {vc}{flags} --apply\n' + 'Or build again (./Build.sh) to get a new versionCode.') + if 'changesnotsentforreview' in low: + return ('Play wants these changes committed without sending them for review.\n' + 'Re-run with --no-review, then send the changes for review in Play Console\n' + '(Publishing overview).') + if err.status == 404 and 'package' in low: + return (f'Play cannot find package {package_name()} for this service account. The app\n' + 'must already exist in Play Console, and the service account must be invited\n' + 'with access to it (Users and permissions).') + if err.status in (401, 403): + return ('The service account lacks permission. In Play Console > Users and\n' + 'permissions, give it Release to production, Manage store presence and\n' + 'View app information for MeshMapper. New grants can take 24-36 h to apply.\n' + 'Also confirm the Google Play Android Developer API is enabled in the\n' + "service account's Google Cloud project.") + return None + + +# --------------------------------------------------------------------------- +# Local file inspection: AAB manifest, PNG headers +# --------------------------------------------------------------------------- + +def _varint(buf, i): + shift = result = 0 + while True: + if i >= len(buf): + raise ValueError('truncated varint') + b = buf[i] + i += 1 + result |= (b & 0x7F) << shift + if not b & 0x80: + return result, i + shift += 7 + + +def _pb_fields(buf): + i = 0 + while i < len(buf): + key, i = _varint(buf, i) + field, wire = key >> 3, key & 7 + if wire == 0: + value, i = _varint(buf, i) + elif wire == 1: + value, i = buf[i:i + 8], i + 8 + elif wire == 2: + n, i = _varint(buf, i) + value, i = buf[i:i + n], i + n + elif wire == 5: + value, i = buf[i:i + 4], i + 4 + else: + raise ValueError(f'unsupported wire type {wire}') + yield field, wire, value + + +def read_aab_manifest(aab_path): + """Read package, versionCode and versionName from an AAB's proto manifest. + + base/manifest/AndroidManifest.xml is an aapt2 XmlNode protobuf: + XmlNode.element(1) > XmlElement.attribute(4) > XmlAttribute{name(2), value(3), + compiled_item(6) > Item.prim(7) > Primitive.int_decimal_value(6)}. + """ + with zipfile.ZipFile(aab_path) as z: + data = z.read('base/manifest/AndroidManifest.xml') + element = next((v for f, w, v in _pb_fields(data) if f == 1 and w == 2), None) + if element is None: + raise ValueError('no root element in manifest') + attrs = {} + for f, w, v in _pb_fields(element): + if f != 4 or w != 2: + continue + name = value = None + prim_int = None + for af, aw, av in _pb_fields(v): + if af == 2 and aw == 2: + name = av.decode('utf-8', 'replace') + elif af == 3 and aw == 2: + value = av.decode('utf-8', 'replace') + elif af == 6 and aw == 2: + for itf, itw, itv in _pb_fields(av): + if itf == 7 and itw == 2: + for pf, pw, pv in _pb_fields(itv): + if pf in (6, 7) and pw == 0: + prim_int = pv + if name: + attrs[name] = value if value else (str(prim_int) if prim_int is not None else None) + version_code = attrs.get('versionCode') + return { + 'package': attrs.get('package'), + 'versionCode': int(version_code) if version_code and version_code.isdigit() else None, + 'versionName': attrs.get('versionName'), + } + + +def png_info(path): + """Return (width, height, color_type) from a PNG's IHDR chunk.""" + with open(path, 'rb') as fh: + head = fh.read(26) + if len(head) < 26 or head[:8] != b'\x89PNG\r\n\x1a\n' or head[12:16] != b'IHDR': + raise ValueError('not a PNG file') + width = int.from_bytes(head[16:20], 'big') + height = int.from_bytes(head[20:24], 'big') + return width, height, head[25] + + +def sha1_file(path): + h = hashlib.sha1() + with open(path, 'rb') as fh: + for chunk in iter(lambda: fh.read(1 << 20), b''): + h.update(chunk) + return h.hexdigest() + + +def human_size(n): + for unit in ('B', 'KB', 'MB', 'GB'): + if n < 1024 or unit == 'GB': + return f'{n:.1f} {unit}' if unit != 'B' else f'{n} B' + n /= 1024.0 + + +# --------------------------------------------------------------------------- +# Shared helpers +# --------------------------------------------------------------------------- + +def track_label(name): + return TRACK_LABELS.get(name, 'Closed testing (custom track)') + + +def sort_tracks(tracks): + order = {t: i for i, t in enumerate(STANDARD_TRACKS)} + return sorted(tracks, key=lambda t: (order.get(t.get('track'), 99), t.get('track', ''))) + + +def release_max_code(release): + codes = [int(c) for c in release.get('versionCodes', []) if str(c).isdigit()] + return max(codes) if codes else -1 + + +def describe_release(r, indent=' '): + lines = [f"{indent}{r.get('name') or '(unnamed)'}: status={r.get('status', '?')}" + f" versionCodes={','.join(r.get('versionCodes', [])) or '-'}" + + (f" userFraction={r['userFraction']}" if 'userFraction' in r else '')] + for note in r.get('releaseNotes', []): + text = note.get('text', '').replace('\n', ' / ') + if len(text) > 100: + text = text[:97] + '...' + lines.append(f"{indent} notes[{note.get('language')}]: {text}") + return '\n'.join(lines) + + +def review_states(api, track): + """versionCode -> review state for the track's non-obsolete releases + (tracks.releases.list, outside the edit; the edits API has no review state).""" + try: + releases = api.call('GET', f'/tracks/{urllib.parse.quote(track)}/releases', + what=f'Reading review state (tracks.releases.list {track})').get('releases', []) + except PlayError as exc: + print(f' (review state unavailable: {exc})') + return {} + states = {} + for r in releases: + state = r.get('releaseLifecycleState', '?').removeprefix('RELEASE_LIFECYCLE_STATE_') + for a in r.get('activeArtifacts', []): + states[str(a.get('versionCode'))] = state + return states + + +def list_tracks(edit): + return edit.call('GET', '/tracks', what='Listing tracks (edits.tracks.list)').get('tracks', []) + + +def edit_language(edit, override=None): + """The language this run writes to, after the language rule: stop when the + edit's store listing has any language other than English. Reads only.""" + listings = edit.call('GET', '/listings', + what='Listing store listings (edits.listings.list)').get('listings', []) + check_languages([lst.get('language', '') for lst in listings]) + details = edit.call('GET', '/details', what='Reading app details (edits.details.get)') + return default_language(details, override) + + +def validate_status(args): + if args.fraction is not None: + if args.status != 'inProgress': + raise PlayError('--fraction only applies with --status inProgress (a staged rollout).') + if not 0 < args.fraction < 1: + raise PlayError('--fraction must be between 0 and 1 (exclusive), e.g. 0.2.') + elif args.status == 'inProgress': + raise PlayError('--status inProgress needs --fraction F (e.g. --fraction 0.2).') + + +def build_release(name, version_codes, notes, status, fraction): + release = {'versionCodes': [str(c) for c in version_codes], 'status': status} + if name: + release['name'] = name + if notes: + release['releaseNotes'] = notes + if fraction is not None: + release['userFraction'] = fraction + return release + + +def finish_validate(edit): + """Validate the staged edit with Play. The caller's `with` block deletes the + edit afterwards; nothing is ever committed from here.""" + edit.validate() + print('') + print('validate: OK (Play accepted everything staged in the edit)') + + +def report_edit_deleted(edit): + if edit.deleted: + print('edit deleted, nothing was committed.') + + +# --------------------------------------------------------------------------- +# status +# --------------------------------------------------------------------------- + +def cmd_status(args): + api = PlayApi(load_credentials(), package_name()) + print(f'Package: {api.package}') + print(f'Service account: {api.client_email}') + with Edit(api) as edit: + print('') + print('Tracks:') + tracks = sort_tracks(list_tracks(edit)) + if not tracks: + print(' (none)') + for t in tracks: + print(f" {t.get('track')} - {track_label(t.get('track'))}") + releases = t.get('releases', []) + if not releases: + print(' (no releases)') + states = review_states(api, t.get('track')) if releases else {} + for r in releases: + print(describe_release(r)) + review = sorted({states[c] for c in r.get('versionCodes', []) if c in states}) + if review: + print(f" review: {', '.join(review)}") + + bundles = edit.call('GET', '/bundles', what='Listing bundles (edits.bundles.list)').get('bundles', []) + codes = sorted((b.get('versionCode') for b in bundles if b.get('versionCode')), reverse=True) + print('') + print(f'Uploaded bundles: {len(codes)}' + + (f" (latest versionCodes: {', '.join(map(str, codes[:5]))})" if codes else '')) + + details = edit.call('GET', '/details', what='Reading app details (edits.details.get)') + print('') + print('App details:') + for key in ('defaultLanguage', 'contactEmail', 'contactWebsite', 'contactPhone'): + if details.get(key): + print(f' {key}: {details[key]}') + + listings = edit.call('GET', '/listings', what='Listing store listings (edits.listings.list)').get('listings', []) + print('') + print('Store listing languages:') + if not listings: + print(' (none)') + for lst in sorted(listings, key=lambda x: x.get('language', '')): + print(f" {lst.get('language')}: {lst.get('title', '')!r}") + print('') + print('(Read-only: the edit was discarded, nothing committed.)') + + +# --------------------------------------------------------------------------- +# upload +# --------------------------------------------------------------------------- + +def load_notes_text(path): + """The release notes text from a file ('-' for stdin), checked against the + Play limit; None when no file was given.""" + if not path: + return None + if path == '-': + text = sys.stdin.read() + else: + if not os.path.isfile(path): + raise PlayError(f'Notes file not found: {path}') + with open(path, encoding='utf-8') as fh: + text = fh.read() + text = text.strip() + if not text: + raise PlayError(f'Notes file {path} is empty.') + if len(text) > MAX_NOTES: + raise PlayError(f'Release notes are {len(text)} characters; Play allows {MAX_NOTES} ' + f'per language. Shorten {path}.') + return text + + +def read_notes(path, lang): + text = load_notes_text(path) + return [{'language': lang, 'text': text}] if text else None + + +def upload_flags(args): + """The flags of this invocation that a re-run must keep (status, rollout + fraction, notes file, notes language), as a string with a leading space. + Without them a re-run would release with no release notes.""" + parts = ['--status', args.status] + if args.fraction is not None: + parts += ['--fraction', str(args.fraction)] + if args.notes_file: + parts += ['--notes-file', args.notes_file] + if args.lang: + parts += ['--lang', args.lang] + return ' ' + ' '.join(shlex.quote(part) for part in parts) + + +def uploaded_version_codes(edit): + """The versionCodes Play already has bundles for (edits.bundles.list).""" + bundles = edit.call('GET', '/bundles', what='Listing bundles (edits.bundles.list)').get('bundles', []) + return {int(b['versionCode']) for b in bundles if b.get('versionCode')} + + +def track_already_has(track, release): + """True when the track holds exactly this release and nothing else: same + versionCodes, status, rollout fraction and release notes.""" + releases = (track or {}).get('releases') or [] + if len(releases) != 1: + return False + have = releases[0] + + def notes_of(r): + return {n.get('language'): (n.get('text') or '').strip() + for n in r.get('releaseNotes') or []} + + return (sorted(have.get('versionCodes') or []) == sorted(release['versionCodes']) + and have.get('status') == release['status'] + and have.get('userFraction') == release.get('userFraction') + and notes_of(have) == notes_of(release)) + + +def cmd_upload(args): + pkg = package_name() + validate_status(args) + last = read_last_build() + HINT['track'] = args.track + HINT['upload_flags'] = upload_flags(args) + notes_text = load_notes_text(args.notes_file) + + release_name = args.release_name + + aab = None + info = {} + version_code = args.version_code + if version_code is None: + aab = args.aab or last.get('AAB_PATH') + if not aab: + raise PlayError('No AAB given and .last_build has no AAB_PATH. Run ./Build.sh or pass --aab PATH.') + aab = os.path.abspath(os.path.expanduser(aab)) + if not os.path.isfile(aab): + raise PlayError(f'AAB not found: {aab}\nRun ./Build.sh or pass --aab PATH.') + try: + info = read_aab_manifest(aab) + except (zipfile.BadZipFile, KeyError, ValueError) as exc: + raise PlayError(f'{aab} is not a readable Android App Bundle: {exc}') + if info['package'] and info['package'] != pkg: + raise PlayError(f"{aab} is package {info['package']}, but PLAY_PACKAGE_NAME is {pkg}.") + version_code = info['versionCode'] + if version_code is None: + if last.get('EPOCH') and os.path.abspath(last.get('AAB_PATH', '')) == aab: + version_code = int(last['EPOCH']) + print(f'Note: versionCode not readable from the manifest; using EPOCH {version_code} from .last_build.') + else: + print('Warning: versionCode not readable from the bundle manifest; Play will report it after upload.') + HINT['version_code'] = version_code if version_code is not None else 'N' + + # Name the release after the bundle actually being uploaded; .last_build + # only describes the newest local build, which may not be this one + if not release_name and aab and info.get('versionName') and version_code is not None: + release_name = f"{info['versionName']} ({version_code})" + + api = PlayApi(load_credentials(), pkg) + with Edit(api) as edit: + # The language rule comes before anything is written + lang = edit_language(edit, args.lang) + notes = [{'language': lang, 'text': notes_text}] if notes_text else None + # Play refuses a versionCode twice, so a build it already has is assigned + # to the track instead of uploaded again (a re-run after a commit is safe) + on_play = bool(aab) and version_code is not None and version_code in uploaded_version_codes(edit) + + print(f'Package: {pkg}') + print(f'Track: {args.track} - {track_label(args.track)}') + if aab: + print(f'Bundle: {aab} ({human_size(os.path.getsize(aab))})' + + (' - already on Play, assigning instead of uploading' if on_play else '')) + print(f"versionCode: {version_code if version_code is not None else '(unknown until upload)'}" + + (f" versionName: {info['versionName']}" if info.get('versionName') else '')) + else: + print(f'Bundle: (no upload) assigning existing versionCode {version_code}') + print(f"Release name: {release_name or '(Play default)'}") + print(f'Status: {args.status}' + + (f' (userFraction {args.fraction})' if args.fraction is not None else '')) + if notes: + print(f'Release notes [{lang}] ({len(notes_text)}/{MAX_NOTES} chars):') + for line in notes_text.splitlines(): + print(f' | {line}') + else: + print('Release notes: (none)') + + tracks = {t.get('track'): t for t in list_tracks(edit)} + current = tracks.get(args.track) + print('') + if current is None: + print(f"Warning: track '{args.track}' does not exist yet for this app. Custom closed " + 'tracks must be created in Play Console first.') + else: + print(f'Current {args.track} releases:') + for r in current.get('releases', []): + print(describe_release(r)) + if not current.get('releases'): + print(' (none)') + + release = (build_release(release_name, [version_code], notes, args.status, args.fraction) + if version_code is not None else None) + unchanged = release is not None and track_already_has(current, release) + # --validate still stages an unchanged release, so it proves write access + if unchanged and not args.validate: + print('') + print(f'Already on {args.track}; nothing to change.') + return + + if not (args.apply or args.validate): + print('') + print('Dry run: nothing uploaded or changed. Re-run with --validate to have Play check it ' + 'without publishing, or --apply to publish.') + return + + if unchanged: + print('') + print(f'Already on {args.track}; staging it anyway so validate checks the write.') + if aab and not on_play: + print('') + print(f'Uploading {os.path.basename(aab)} (this can take a few minutes)...') + resp = edit.call('POST', '/bundles', upload_path=aab, + content_type='application/octet-stream', timeout=1800, + what='Uploading the bundle (edits.bundles.upload)') + uploaded = resp.get('versionCode') + if uploaded is None: + raise PlayError('Bundle upload returned no versionCode.') + if version_code is not None and int(uploaded) != int(version_code): + print(f'Warning: Play reports versionCode {uploaded}, expected {version_code}.') + version_code = uploaded + print(f"Uploaded versionCode {version_code} (sha1 {resp.get('sha1', '?')}).") + + release = build_release(release_name, [version_code], notes, args.status, args.fraction) + edit.call('PUT', f'/tracks/{urllib.parse.quote(args.track)}', + {'track': args.track, 'releases': [release]}, + what=f'Updating track {args.track} (edits.tracks.update)') + if args.validate: + finish_validate(edit) + else: + edit.commit(no_review=args.no_review) + print('') + if args.validate: + report_edit_deleted(edit) + return + print(f'Committed: versionCode {version_code} is on {args.track} with status {args.status}.') + if args.status == 'draft': + print('The release is a draft; roll it out from Play Console > Testing.') + + +# --------------------------------------------------------------------------- +# promote +# --------------------------------------------------------------------------- + +def cmd_promote(args): + pkg = package_name() + validate_status(args) + HINT['track'] = args.to_track + if args.from_track == args.to_track: + raise PlayError('--from and --to must be different tracks.') + api = PlayApi(load_credentials(), pkg) + with Edit(api) as edit: + tracks = {t.get('track'): t for t in list_tracks(edit)} + src = tracks.get(args.from_track) + releases = [r for r in (src or {}).get('releases', []) if r.get('versionCodes')] + if not releases: + raise PlayError(f"Track '{args.from_track}' has no release with a build to promote.") + latest = max(releases, key=release_max_code) + HINT['version_code'] = release_max_code(latest) + release = build_release(latest.get('name'), latest['versionCodes'], + latest.get('releaseNotes'), args.status, args.fraction) + + print(f'Package: {pkg}') + print(f'From {args.from_track} ({track_label(args.from_track)}), latest release:') + print(describe_release(latest)) + dest = tracks.get(args.to_track) + print(f'To {args.to_track} ({track_label(args.to_track)}), currently:') + if dest is None: + print(f" Warning: track '{args.to_track}' does not exist yet for this app.") + for r in (dest or {}).get('releases', []) or []: + print(describe_release(r)) + if dest is not None and not dest.get('releases'): + print(' (no releases)') + print('New release:') + print(describe_release(release)) + + if not args.apply: + print('') + print('Dry run: nothing changed. Re-run with --apply to promote.') + return + edit.call('PUT', f'/tracks/{urllib.parse.quote(args.to_track)}', + {'track': args.to_track, 'releases': [release]}, + what=f'Updating track {args.to_track} (edits.tracks.update)') + edit.commit(no_review=args.no_review) + print('') + print(f"Committed: versionCodes {','.join(release['versionCodes'])} promoted to {args.to_track}.") + + +# --------------------------------------------------------------------------- +# screenshots +# --------------------------------------------------------------------------- + +def collect_phone_screenshots(base_dir): + """The android-phone/*.png files under base_dir, in name order, checked for + count, size and weight. Raises PlayError listing every problem found.""" + folder = os.path.join(os.path.abspath(os.path.expanduser(base_dir)), PHONE_FOLDER) + if not os.path.isdir(folder): + raise PlayError(f'{folder} not found. Run tool/store_screenshots/capture_android.sh first, ' + f'or pass the folder that holds {PHONE_FOLDER}/ as --dir.') + files = sorted(os.path.join(folder, name) for name in os.listdir(folder) + if name.lower().endswith('.png')) + if not MIN_PHONE_SCREENSHOTS <= len(files) <= MAX_PHONE_SCREENSHOTS: + raise PlayError(f'{folder}: {len(files)} PNG files, Play needs ' + f'{MIN_PHONE_SCREENSHOTS}-{MAX_PHONE_SCREENSHOTS} phone screenshots.') + errors = [] + for path in files: + name = os.path.basename(path) + try: + width, height, _ = png_info(path) + check_screenshot_size(width, height) + except (OSError, ValueError, PlayError) as exc: + errors.append(f'{name}: {exc}') + continue + size = os.path.getsize(path) + if size > MAX_SCREENSHOT_BYTES: + errors.append(f'{name}: {human_size(size)} exceeds the ' + f'{human_size(MAX_SCREENSHOT_BYTES)} limit') + if errors: + raise PlayError('The phone screenshots are not valid:\n - ' + '\n - '.join(errors)) + return files + + +def remote_images(edit, lang, image_type): + try: + return edit.call('GET', f'/listings/{lang}/{image_type}', + what=f'Listing {image_type} (edits.images.list)').get('images', []) + except ApiError as exc: + if exc.status != 404: + raise + return [] + + +def cmd_screenshots(args): + pkg = package_name() + files = collect_phone_screenshots(args.dir) + local = [sha1_file(path) for path in files] + + api = PlayApi(load_credentials(), pkg) + with Edit(api) as edit: + # The language rule comes before anything is written + lang = edit_language(edit) + remote = remote_images(edit, lang, PHONE_IMAGE_TYPE) + + print(f'Package: {pkg}') + print(f'{PHONE_IMAGE_TYPE} for {lang}: {len(remote)} on Play, {len(files)} local:') + for path in files: + width, height, _ = png_info(path) + print(f' {os.path.basename(path)} {width}x{height}') + + matches = [r.get('sha1') for r in remote] == local + # --validate stages the replacement even when Play already matches, so it + # still proves the service account may write + if matches and not args.validate: + print('') + print('Play already matches the local screenshots; nothing to change.') + return + if not (args.apply or args.validate): + print('') + print(f'Replace {len(remote)} remote with {len(files)} local. Dry run: nothing changed. ' + 'Re-run with --validate to have Play check it without publishing, or --apply.') + return + + edit.call('DELETE', f'/listings/{lang}/{PHONE_IMAGE_TYPE}', + what=f'Clearing {PHONE_IMAGE_TYPE} (edits.images.deleteall)') + for path in files: + edit.call('POST', f'/listings/{lang}/{PHONE_IMAGE_TYPE}', upload_path=path, + content_type='image/png', timeout=300, + what=f'Uploading {os.path.basename(path)} as {PHONE_IMAGE_TYPE} (edits.images.upload)') + print(f' uploaded {os.path.basename(path)}') + if args.validate: + finish_validate(edit) + else: + edit.commit(no_review=args.no_review) + print('') + if args.validate: + report_edit_deleted(edit) + return + print(f'Committed: {len(files)} {PHONE_IMAGE_TYPE} for {lang}.') + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def build_parser(): + parser = argparse.ArgumentParser( + prog='play_store.py', + description='Upload MeshMapper to Google Play and replace its phone screenshots. ' + 'Dry run unless --apply (or --validate) is passed.') + sub = parser.add_subparsers(dest='command') + sub.required = True + + sub.add_parser('status', help='show tracks, releases and listing languages (read-only)') + + def add_no_review(p): + p.add_argument('--no-review', action='store_true', + help='commit with changesNotSentForReview=true (send for review from Console)') + + def add_write_mode(p, validatable): + group = p.add_mutually_exclusive_group() + group.add_argument('--apply', action='store_true', help='actually make the change') + if validatable: + group.add_argument('--validate', action='store_true', + help='stage the change in an edit, have Play validate it, then ' + 'delete the edit; never commits') + add_no_review(p) + + def add_status(p): + p.add_argument('--status', choices=['draft', 'completed', 'inProgress'], default='completed', + help='release status (default completed; on production that is a 100%% rollout)') + p.add_argument('--fraction', type=float, help='userFraction for --status inProgress (0-1)') + + up = sub.add_parser('upload', help='upload an AAB and put it on a track') + up.add_argument('--track', required=True, + help='production, beta (open), alpha (closed), internal or a custom closed track') + up.add_argument('--aab', help='AAB path (default: AAB_PATH from .last_build)') + up.add_argument('--version-code', type=int, + help='assign this already uploaded versionCode to the track instead of uploading') + up.add_argument('--notes-file', help=f"release notes file ('-' for stdin), max {MAX_NOTES} chars") + up.add_argument('--lang', + help="release notes language (default: the app's default language on Play)") + up.add_argument('--release-name', + help='release name (default: versionName (versionCode) read from the AAB)') + add_status(up) + add_write_mode(up, validatable=True) + + pr = sub.add_parser('promote', help='copy the latest release from one track to another') + pr.add_argument('--from', dest='from_track', required=True, help='source track, e.g. beta') + pr.add_argument('--to', dest='to_track', required=True, help='destination track, e.g. production') + add_status(pr) + add_write_mode(pr, validatable=False) + + sc = sub.add_parser('screenshots', + help=f'replace the {PHONE_IMAGE_TYPE} of the default language') + sc.add_argument('--dir', required=True, metavar='DIR', + help=f'folder holding {PHONE_FOLDER}/ with {MIN_PHONE_SCREENSHOTS}-' + f'{MAX_PHONE_SCREENSHOTS} PNG files') + add_write_mode(sc, validatable=True) + return parser + + +def mode_label(args): + if args.command == 'status' or getattr(args, 'apply', False): + return '' + if getattr(args, 'validate', False): + return ' [VALIDATE ONLY, nothing is committed]' + return ' [DRY RUN]' + + +def main(): + args = build_parser().parse_args() + handlers = {'status': cmd_status, 'upload': cmd_upload, 'promote': cmd_promote, + 'screenshots': cmd_screenshots} + print(f'Google Play: {package_name()}{mode_label(args)}') + try: + handlers[args.command](args) + except ApiError as exc: + print('') + print(f'Error: {exc}', file=sys.stderr) + hint = explain_api_error(exc) + if hint: + print('', file=sys.stderr) + print(hint, file=sys.stderr) + print('', file=sys.stderr) + print('Nothing was committed (the edit was discarded).', file=sys.stderr) + sys.exit(1) + except PlayError as exc: + print('') + print(f'Error: {exc}', file=sys.stderr) + sys.exit(1) + except KeyboardInterrupt: + print('\nInterrupted; nothing was committed.', file=sys.stderr) + sys.exit(130) + + +if __name__ == '__main__': + main() diff --git a/pubspec.lock b/pubspec.lock index 15fb98e4..cc1ff9dc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -835,10 +835,10 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.20" material_color_utilities: dependency: transitive description: @@ -851,10 +851,10 @@ packages: dependency: transitive description: name: meta - sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" mime: dependency: transitive description: @@ -896,7 +896,7 @@ packages: source: hosted version: "2.2.0" package_info_plus: - dependency: transitive + dependency: "direct main" description: name: package_info_plus sha256: f69da0d3189a4b4ceaeb1a3defb0f329b3b352517f52bed4290f83d4f06bc08d @@ -1264,10 +1264,10 @@ packages: dependency: transitive description: name: test_api - sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.12" timezone: dependency: transitive description: @@ -1368,10 +1368,10 @@ packages: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.3" vm_service: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 6254edf4..ec1acca5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ dependencies: geolocator: ^11.0.0 maplibre_gl: ^0.27.1 clock: ^1.1.1 - http: ^1.2.0 + http: ^1.5.0 shared_preferences: ^2.2.0 hive: ^2.2.3 hive_flutter: ^1.1.0 @@ -31,6 +31,7 @@ dependencies: xml: ^6.5.0 file_picker: ^8.0.0 url_launcher: ^6.2.0 + package_info_plus: ^9.0.0 flutter_background_service: ^5.0.10 flutter_local_notifications: ^17.0.0 just_audio: ^0.9.40 diff --git a/test/debug/store_capture_test.dart b/test/debug/store_capture_test.dart new file mode 100644 index 00000000..46ea551c --- /dev/null +++ b/test/debug/store_capture_test.dart @@ -0,0 +1,169 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/debug/store_capture.dart'; +import 'package:mesh_mapper/debug/store_capture_route.dart'; + +final newest = DateTime(2026, 11, 1, 9, 40); + +final repeaters = [ + (id: 'CBC003', lat: 45.4210, lon: -75.6960), + (id: '85FFDD', lat: 45.4150, lon: -75.7000), + (id: 'BB0003', lat: 45.4300, lon: -75.6900), + (id: '60', lat: 45.4000, lon: -75.7200), +]; + +StoreCaptureSample _build( + {List<({String id, double lat, double lon})>? reps}) => + buildStoreCaptureSample(newest: newest, repeaters: reps ?? repeaters); + +void main() { + group('buildStoreCaptureSample', () { + test('one TX per route point, newest at the arrow at 9:40', () { + final s = _build(); + expect(storeCaptureRoute.length, 45); + expect(s.txPings.length, 45); + expect(s.txPings.last.timestamp, newest); + expect(s.txPings.last.latitude, storeCaptureRoute.last.$1); + expect(s.txPings.last.longitude, storeCaptureRoute.last.$2); + for (var i = 1; i < s.txPings.length; i++) { + expect( + s.txPings[i].timestamp.difference(s.txPings[i - 1].timestamp), + const Duration(seconds: 22), + ); + } + expect(s.txLog.length, 45); + }); + + test('mostly heard, at least one miss', () { + final misses = + _build().txPings.where((p) => p.heardRepeaters.isEmpty).length; + expect(misses, greaterThanOrEqualTo(1)); + expect(misses, lessThanOrEqualTo(9)); + expect(_build().txPings.last.heardRepeaters, isNotEmpty); + }); + + test('the newest ping is always heard', () { + final sets = [ + repeaters, + <({String id, double lat, double lon})>[], + [ + (id: 'CBC003', lat: 45.4210, lon: -75.6960), + (id: '60', lat: 45.4000, lon: -75.7200), + ], + [(id: 'BB0003', lat: 45.4300, lon: -75.6900)], + ]; + for (final reps in sets) { + expect(_build(reps: reps).txPings.last.heardRepeaters, isNotEmpty); + } + }); + + test('heard ids come from the loaded repeaters', () { + final allowed = {'CBC003', '85FFDD', 'BB0003', '60'}; + for (final p in _build().txPings) { + for (final h in p.heardRepeaters) { + expect(allowed, contains(h.repeaterId)); + } + } + }); + + test('falls back to fixed ids when no repeaters loaded', () { + final s = _build(reps: []); + expect(s.txPings, isNotEmpty); + expect(s.txPings.last.heardRepeaters, isNotEmpty); + for (final p in s.txPings) { + for (final h in p.heardRepeaters) { + expect(storeCaptureFallbackIds, contains(h.repeaterId)); + } + } + }); + + test('RX on every third point', () { + final s = _build(); + expect(s.rxPings.length, 15); + expect(s.rxLog.length, 15); + for (final r in s.rxPings) { + expect(r.timestamp.isBefore(newest), isTrue); + } + for (final r in s.rxLog) { + expect(r.timestamp.isBefore(newest), isTrue); + } + }); + + test('one discovery and one trace', () { + final s = _build(); + expect(s.disc.length, 1); + expect(s.trace.length, 1); + expect(s.trace.single.success, isTrue); + }); + + test('four finished sessions, newest first', () { + final s = _build(); + expect(s.sessions.map((e) => e.mode).toList(), + ['active', 'hybrid', 'passive', 'active']); + for (final session in s.sessions) { + expect(session.endTime, isNotNull); + for (final m in session.markers) { + expect(m.latitude, isNotNull); + expect(m.longitude, isNotNull); + } + } + for (var i = 1; i < s.sessions.length; i++) { + expect(s.sessions[i].startTime.isBefore(s.sessions[i - 1].startTime), + isTrue); + } + }); + + test('stats match the lists', () { + final s = _build(); + expect(s.stats.txCount, 45); + expect(s.stats.rxCount, 15); + expect(s.stats.discCount, 1); + expect(s.stats.traceCount, 1); + expect(s.stats.successfulUploads, 60); + }); + + test('header numbers', () { + final s = _build(); + expect(s.noiseFloor, -109); + expect(s.batteryPercent, 86); + }); + + test('deterministic', () { + // Lists inside records compare by identity, so flatten each ping to text. + List shape(StoreCaptureSample s) => [ + for (final p in s.txPings) + '${p.timestamp.toIso8601String()} ' + '${[ + for (final h in p.heardRepeaters) h.repeaterId + ].join(',')}', + ]; + expect(shape(_build()), isNotEmpty); + expect(shape(_build()), shape(_build())); + }); + }); + + group('StoreCaptureConfig', () { + test('config parse', () { + expect(StoreCaptureConfig.parse('{"screen":"log"}')?.screen, + StoreCaptureScreen.log); + expect(StoreCaptureConfig.parse('{"screen":"log"}')?.screen.tabIndex, 1); + expect( + StoreCaptureConfig.parse('{"screen":"history"}')?.screen.tabIndex, 2); + expect(StoreCaptureConfig.parse('{"screen":"map"}')?.screen.tabIndex, 0); + expect(StoreCaptureConfig.parse('not json'), isNull); + expect(StoreCaptureConfig.parse('{"screen":"settings"}'), isNull); + expect(StoreCaptureConfig.parse('{}'), isNull); + }); + + test('config load', () async { + final dir = Directory.systemTemp.createTempSync('store_capture_test'); + addTearDown(() => dir.deleteSync(recursive: true)); + expect(await StoreCaptureConfig.load(dir), isNull); + File('${dir.path}/$storeCaptureFileName') + .writeAsStringSync('{"screen":"history"}'); + final loaded = await StoreCaptureConfig.load(dir); + expect(loaded?.screen, StoreCaptureScreen.history); + }); + }); +} diff --git a/test/fixtures/coverage_cf2_z10_sea_164_357_gsize300.mvt b/test/fixtures/coverage_cf2_z10_sea_164_357_gsize300.mvt new file mode 100644 index 00000000..af9da54c Binary files /dev/null and b/test/fixtures/coverage_cf2_z10_sea_164_357_gsize300.mvt differ diff --git a/test/fixtures/coverage_cf2_z7_sea_20_44.mvt b/test/fixtures/coverage_cf2_z7_sea_20_44.mvt new file mode 100644 index 00000000..075d79f8 Binary files /dev/null and b/test/fixtures/coverage_cf2_z7_sea_20_44.mvt differ diff --git a/test/fixtures/coverage_cf2_z8_sea_41_89.mvt b/test/fixtures/coverage_cf2_z8_sea_41_89.mvt new file mode 100644 index 00000000..57a073a6 Binary files /dev/null and b/test/fixtures/coverage_cf2_z8_sea_41_89.mvt differ diff --git a/test/fixtures/coverage_cf2_z9_sea_82_178.mvt b/test/fixtures/coverage_cf2_z9_sea_82_178.mvt new file mode 100644 index 00000000..947d55db Binary files /dev/null and b/test/fixtures/coverage_cf2_z9_sea_82_178.mvt differ diff --git a/test/fixtures/coverage_z6_sea_10_22.mvt b/test/fixtures/coverage_z6_sea_10_22.mvt new file mode 100644 index 00000000..35dee795 Binary files /dev/null and b/test/fixtures/coverage_z6_sea_10_22.mvt differ diff --git a/test/models/api_queue_item_altitude_test.dart b/test/models/api_queue_item_altitude_test.dart index a7ec3de6..5529b07f 100644 --- a/test/models/api_queue_item_altitude_test.dart +++ b/test/models/api_queue_item_altitude_test.dart @@ -1,50 +1,98 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:mesh_mapper/models/api_queue_item.dart'; -/// Every wardrive post carries the phone's altitude in whole meters, and -/// leaves the key out entirely when the phone did not know it. +/// An altitude is uploaded only together with its reference, and its accuracy +/// only beside both. An item holding an altitude with no reference emits none +/// of the three keys. Contract: MeshMapper_Server/docs/APP_API.md. const _ts = 1768762843; +Map _tx({ + double? altitude, + String? altitudeRef, + double? altitudeAccuracy, +}) => + ApiQueueItem.fromTx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: '4e(12.25)', + timestamp: _ts, + externalAntenna: false, + altitude: altitude, + altitudeRef: altitudeRef, + altitudeAccuracy: altitudeAccuracy, + ).toApiJson(); + void main() { - group('altitude in toApiJson', () { - test('TX carries a rounded altitude', () { - final item = ApiQueueItem.fromTx( - latitude: 45.0, - longitude: -75.0, - heardRepeats: '4e(12.25)', - timestamp: _ts, - externalAntenna: false, - altitude: 123.6, - ); - expect(item.toApiJson()['altitude'], 124); + group('altitude trio in toApiJson', () { + test('all three present, rounded', () { + final j = _tx(altitude: 123.6, altitudeRef: 'msl', altitudeAccuracy: 5.4); + expect(j['altitude'], 124); + expect(j['altitude_ref'], 'msl'); + expect(j['altitude_acc'], 5); }); - test('TX omits the key when altitude is unknown', () { - final item = ApiQueueItem.fromTx( - latitude: 45.0, - longitude: -75.0, - heardRepeats: 'None', - timestamp: _ts, - externalAntenna: false, - ); - expect(item.toApiJson().containsKey('altitude'), isFalse); + test('altitude and reference without accuracy', () { + final j = _tx(altitude: 84.0, altitudeRef: 'ellipsoid'); + expect(j['altitude'], 84); + expect(j['altitude_ref'], 'ellipsoid'); + expect(j.containsKey('altitude_acc'), isFalse); + }); + + test('an altitude with no reference emits none of the three', () { + final j = _tx(altitude: 84.0, altitudeAccuracy: 5.0); + expect(j.containsKey('altitude'), isFalse); + expect(j.containsKey('altitude_ref'), isFalse); + expect(j.containsKey('altitude_acc'), isFalse); + }); + + test('a reference with no altitude emits none of the three', () { + final j = _tx(altitudeRef: 'msl', altitudeAccuracy: 5.0); + expect(j.containsKey('altitude'), isFalse); + expect(j.containsKey('altitude_ref'), isFalse); + expect(j.containsKey('altitude_acc'), isFalse); }); - test('RX carries altitude', () { - final item = ApiQueueItem.fromRx( + test('a zero, negative, infinite or NaN accuracy is not sent', () { + for (final acc in [0.0, -1.0, double.infinity, double.nan]) { + final j = + _tx(altitude: 84.0, altitudeRef: 'msl', altitudeAccuracy: acc); + expect(j['altitude'], 84, reason: '$acc'); + expect(j.containsKey('altitude_acc'), isFalse, reason: '$acc'); + } + }); + + test('a sub-meter accuracy rounds to 0 and is still sent', () { + final j = _tx(altitude: 84.0, altitudeRef: 'msl', altitudeAccuracy: 0.4); + expect(j['altitude_acc'], 0); + }); + + test('nothing at all when the item has no altitude', () { + final j = _tx(); + expect(j.containsKey('altitude'), isFalse); + expect(j.containsKey('altitude_ref'), isFalse); + expect(j.containsKey('altitude_acc'), isFalse); + }); + + test('RX carries the trio', () { + final j = ApiQueueItem.fromRx( latitude: 45.0, longitude: -75.0, heardRepeats: '4e(12.0)', timestamp: _ts, externalAntenna: false, altitude: 80.2, - ); - expect(item.toApiJson()['altitude'], 80); + altitudeRef: 'msl', + altitudeAccuracy: 3.0, + ).toApiJson(); + expect(j['altitude'], 80); + expect(j['altitude_ref'], 'msl'); + expect(j['altitude_acc'], 3); }); - test('DISC carries altitude', () { - final item = ApiQueueItem.fromDisc( + test('DISC carries the trio', () { + final pubkey = 'ab' * 32; + final j = ApiQueueItem.fromDisc( latitude: 45.0, longitude: -75.0, repeaterId: '4e', @@ -52,27 +100,35 @@ void main() { localSnr: 10.0, localRssi: -90, remoteSnr: 8.0, - pubkeyFull: 'ab' * 32, + pubkeyFull: pubkey, timestamp: _ts, externalAntenna: false, altitude: 200.0, - ); - expect(item.toApiJson()['altitude'], 200); + altitudeRef: 'ellipsoid', + altitudeAccuracy: 12.0, + ).toApiJson(); + expect(j['altitude'], 200); + expect(j['altitude_ref'], 'ellipsoid'); + expect(j['altitude_acc'], 12); }); - test('DISC drop carries altitude', () { - final item = ApiQueueItem.fromDiscDrop( + test('DISC drop carries the trio', () { + final j = ApiQueueItem.fromDiscDrop( latitude: 45.0, longitude: -75.0, timestamp: _ts, externalAntenna: false, altitude: 200.0, - ); - expect(item.toApiJson()['altitude'], 200); + altitudeRef: 'msl', + altitudeAccuracy: 2.0, + ).toApiJson(); + expect(j['altitude'], 200); + expect(j['altitude_ref'], 'msl'); + expect(j['altitude_acc'], 2); }); - test('TRACE carries altitude', () { - final item = ApiQueueItem.fromTrace( + test('TRACE carries the trio', () { + final j = ApiQueueItem.fromTrace( latitude: 45.0, longitude: -75.0, repeaterId: '4e', @@ -82,12 +138,16 @@ void main() { timestamp: _ts, externalAntenna: false, altitude: -3.4, - ); - expect(item.toApiJson()['altitude'], -3); + altitudeRef: 'msl', + altitudeAccuracy: 7.6, + ).toApiJson(); + expect(j['altitude'], -3); + expect(j['altitude_ref'], 'msl'); + expect(j['altitude_acc'], 8); }); - test('TRACE omits the key when altitude is unknown', () { - final item = ApiQueueItem.fromTrace( + test('TRACE with an unlabelled altitude emits none of the three', () { + final j = ApiQueueItem.fromTrace( latitude: 45.0, longitude: -75.0, repeaterId: '4e', @@ -96,8 +156,32 @@ void main() { remoteSnr: 8.0, timestamp: _ts, externalAntenna: false, - ); - expect(item.toApiJson().containsKey('altitude'), isFalse); + altitude: 50.0, + ).toApiJson(); + expect(j.containsKey('altitude'), isFalse); + expect(j.containsKey('altitude_ref'), isFalse); + }); + + test('DEFER and SCOPES never carry any of the three', () { + final defer = ApiQueueItem.fromDefer( + latitude: 45.0, + longitude: -75.0, + timestamp: _ts, + held: 'tx', + ).toApiJson(); + final scopes = ApiQueueItem.fromScopes( + publicKeyHex: + 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2', + scopes: const ['ROOM1'], + lat: 45.0, + lon: -75.0, + timestamp: _ts, + ).toApiJson(); + for (final j in [defer, scopes]) { + expect(j.containsKey('altitude'), isFalse); + expect(j.containsKey('altitude_ref'), isFalse); + expect(j.containsKey('altitude_acc'), isFalse); + } }); }); } diff --git a/test/models/api_queue_item_hive_roundtrip_test.dart b/test/models/api_queue_item_hive_roundtrip_test.dart index 8a7d22c8..863d111c 100644 --- a/test/models/api_queue_item_hive_roundtrip_test.dart +++ b/test/models/api_queue_item_hive_roundtrip_test.dart @@ -2,8 +2,96 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; +import 'package:hive/src/hive_impl.dart'; import 'package:mesh_mapper/models/api_queue_item.dart'; +/// The generated adapter as it existed before fields 21 to 23 (`scopes`, +/// `altitudeRef`, `altitudeAccuracy`) were added: writes only fields 0-20. +/// A record written with TODAY's adapter always carries field 21 (as an explicit null when [ApiQueueItem.scopes] +/// is null), so it does not exercise a reader's handling of a field that is +/// genuinely ABSENT from the binary data, the shape every item recorded +/// before this migration actually has on disk. This adapter, run against a +/// separate `HiveImpl` instance (its own adapter registry, so it can +/// register a different `ApiQueueItemAdapter` for typeId 3 without +/// colliding with the real one this file registers on the global `Hive`), +/// produces that genuine shape. +class _LegacyApiQueueItemAdapter extends TypeAdapter { + @override + final int typeId = 3; + + @override + ApiQueueItem read(BinaryReader reader) { + final numOfFields = reader.readByte(); + final fields = { + for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), + }; + return ApiQueueItem( + type: fields[0] as String, + latitude: fields[1] as double, + longitude: fields[2] as double, + timestamp: fields[3] as DateTime, + heardRepeats: fields[12] as String, + canUploadAfter: fields[13] as int, + externalAntenna: fields[14] as bool, + retryCount: fields[5] as int, + lastRetryAt: fields[6] as DateTime?, + noiseFloor: fields[11] as int?, + power: fields[15] as double?, + pingCounter: fields[16] as int?, + wireTag: fields[17] as String?, + altitude: fields[18] as double?, + autoMode: fields[19] as String?, + radioFreq: fields[20] as String?, + ); + } + + @override + void write(BinaryWriter writer, ApiQueueItem obj) { + writer + ..writeByte(16) + ..writeByte(0) + ..write(obj.type) + ..writeByte(1) + ..write(obj.latitude) + ..writeByte(2) + ..write(obj.longitude) + ..writeByte(3) + ..write(obj.timestamp) + ..writeByte(5) + ..write(obj.retryCount) + ..writeByte(6) + ..write(obj.lastRetryAt) + ..writeByte(11) + ..write(obj.noiseFloor) + ..writeByte(12) + ..write(obj.heardRepeats) + ..writeByte(13) + ..write(obj.canUploadAfter) + ..writeByte(14) + ..write(obj.externalAntenna) + ..writeByte(15) + ..write(obj.power) + ..writeByte(16) + ..write(obj.pingCounter) + ..writeByte(17) + ..write(obj.wireTag) + ..writeByte(18) + ..write(obj.altitude) + ..writeByte(19) + ..write(obj.autoMode) + ..writeByte(20) + ..write(obj.radioFreq); + } + + @override + int get hashCode => typeId.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is _LegacyApiQueueItemAdapter && runtimeType == other.runtimeType; +} + /// The generated adapter is gitignored and regenerated per machine, so a /// stale one compiles cleanly while silently dropping field 19 or 20. Every /// real upload reads its items back out of Hive, so the stamp must survive a @@ -101,4 +189,100 @@ void main() { expect(reopened.getAt(0)!.toApiJson()['radio_freq'], '910.525,62.5,7,5'); expect(reopened.getAt(1)!.toApiJson()['radio_freq'], '906.875,250,10,5'); }); + + test('a SCOPES item survives the adapter with its scopes list intact', + () async { + final box = await Hive.openBox('roundtrip4'); + await box.add(ApiQueueItem.fromScopes( + publicKeyHex: + 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2', + scopes: const ['ROOM1', '*'], + lat: 45.26974, + lon: -75.77746, + timestamp: 1757400000, + radioFreq: '910.525,62.5,7,5', + )); + await box.close(); + + final reopened = await Hive.openBox('roundtrip4'); + final item = reopened.getAt(0)!; + expect(item.type, 'SCOPES'); + expect(item.scopes, ['ROOM1', '*']); + expect(item.toApiJson(), { + 'type': 'SCOPES', + 'public_key': + 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2', + 'scopes': ['ROOM1', '*'], + 'timestamp': 1757400000, + 'lat': 45.26974, + 'lon': -75.77746, + 'radio_freq': '910.525,62.5,7,5', + }); + }); + + test('the altitude trio survives the adapter, and a null pair stays null', + () async { + final box = await Hive.openBox('roundtrip5'); + await box.add(ApiQueueItem.fromTx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: '4e(12.25)', + timestamp: 1757400000, + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'msl', + altitudeAccuracy: 6.0, + )); + await box.add(ApiQueueItem.fromTx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: 'None', + timestamp: 1757400001, + externalAntenna: false, + altitude: 84.0, + )); + await box.close(); + + final reopened = await Hive.openBox('roundtrip5'); + final labelled = reopened.getAt(0)!; + final bare = reopened.getAt(1)!; + expect(labelled.altitudeRef, 'msl'); + expect(labelled.altitudeAccuracy, 6.0); + expect(labelled.toApiJson()['altitude_ref'], 'msl'); + expect(labelled.toApiJson()['altitude_acc'], 6); + expect(bare.altitudeRef, isNull); + expect(bare.altitudeAccuracy, isNull); + expect(bare.toApiJson().containsKey('altitude'), isFalse); + }); + + test( + 'a record genuinely lacking field 21 (written before it existed) ' + 'reads scopes as null through the real adapter', () async { + // A separate Hive instance/registry, isolated from the global `Hive` + // this file's setUp registers the real adapter on, writes to the same + // directory using the OLD adapter shape: field 21 is not merely null, + // it is not written at all. + final legacyHive = HiveImpl()..init(dir.path); + legacyHive.registerAdapter(_LegacyApiQueueItemAdapter()); + final legacyBox = await legacyHive.openBox('legacy'); + await legacyBox.add(ApiQueueItem.fromRx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: '4e(12.0)', + timestamp: 1757400000, + externalAntenna: false, + )); + await legacyBox.close(); + + // The real adapter (registered on the global `Hive` in setUp) reads + // that same directory back. + final reopened = await Hive.openBox('legacy'); + final item = reopened.getAt(0)!; + expect(item.type, 'RX'); + expect(item.scopes, isNull); + expect(item.altitudeRef, isNull); + expect(item.altitudeAccuracy, isNull); + expect(item.toApiJson().containsKey('altitude_ref'), isFalse); + expect(item.toApiJson().containsKey('scopes'), isFalse); + }); } diff --git a/test/models/log_entry_scopes_test.dart b/test/models/log_entry_scopes_test.dart new file mode 100644 index 00000000..43aa4dc1 --- /dev/null +++ b/test/models/log_entry_scopes_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/log_entry.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; + +ScopeLogEntry _scope({ + DateTime? timestamp, + ScopeLogOutcome outcome = ScopeLogOutcome.answered, + List? scopes, +}) { + return ScopeLogEntry( + timestamp: timestamp ?? DateTime(2026, 9, 26, 10), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: outcome, + scopes: scopes, + ); +} + +void main() { + group('UnifiedPingLogEntry.asScopes', () { + test('carries the entry through unchanged', () { + final scope = _scope(); + final unified = UnifiedPingLogEntry( + type: PingLogType.scopes, timestamp: scope.timestamp, entry: scope); + expect(unified.asScopes, same(scope)); + }); + + test('timeString, locationString and toCsv delegate to the entry', () { + final scope = _scope(scopes: const ['Ottawa', '*']); + final unified = UnifiedPingLogEntry( + type: PingLogType.scopes, timestamp: scope.timestamp, entry: scope); + expect(unified.timeString, scope.timeString); + expect(unified.locationString, scope.locationString); + expect(unified.toCsv(), 'SCOPES,${scope.toCsv()}'); + }); + }); + + group('mergeUnifiedPingLog', () { + test('merges scopes newest first alongside the other types', () { + final scope = _scope(timestamp: DateTime(2026, 9, 26, 10, 0, 30)); + final tx = TxLogEntry( + timestamp: DateTime(2026, 9, 26, 10, 0, 0), + latitude: 45.1, + longitude: -75.2, + power: 0.3, + events: const [], + ); + final rx = RxLogEntry( + timestamp: DateTime(2026, 9, 26, 10, 0, 45), + repeaterId: 'CD', + pathLength: 1, + header: 0x11, + latitude: 45.1, + longitude: -75.2, + ); + + final merged = mergeUnifiedPingLog( + tx: [tx], + rx: [rx], + disc: const [], + trace: const [], + scopes: [scope], + ); + + expect(merged.map((e) => e.type), + [PingLogType.rx, PingLogType.scopes, PingLogType.tx]); + }); + + test('an empty scopes list is a no-op', () { + final tx = TxLogEntry( + timestamp: DateTime(2026, 9, 26, 10), + latitude: 0, + longitude: 0, + power: 0.3, + events: const [], + ); + final merged = mergeUnifiedPingLog( + tx: [tx], + rx: const [], + disc: const [], + trace: const [], + scopes: const []); + expect(merged, hasLength(1)); + expect(merged.single.type, PingLogType.tx); + }); + }); +} diff --git a/test/models/map_view_state_test.dart b/test/models/map_view_state_test.dart new file mode 100644 index 00000000..9bc8d15d --- /dev/null +++ b/test/models/map_view_state_test.dart @@ -0,0 +1,121 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:mesh_mapper/models/map_view_state.dart'; + +void main() { + group('MapViewState defaults', () { + test('a first launch keeps today\'s layout and no remembered zoom', () { + const s = MapViewState(); + expect(s.zoom, isNull); + expect(s.controlsMinimized, isFalse); + expect(s.controlPanelShown, isTrue); + expect(s.landscapeMapControlsExpanded, isFalse); + expect(s.mapControlsExpanded, isTrue); + }); + + test('nothing stored reads as the defaults', () { + expect(MapViewState.fromStored(null), const MapViewState()); + expect(MapViewState.fromStored('junk'), const MapViewState()); + expect(MapViewState.fromStored({}), + const MapViewState()); + }); + + test('a malformed field falls back to its own default only', () { + final s = MapViewState.fromStored({ + 'zoom': 'twelve', + 'controlsMinimized': 1, + 'controlPanelShown': false, + 'mapControlsExpanded': null, + }); + expect(s.zoom, isNull); + expect(s.controlsMinimized, isFalse); + expect(s.controlPanelShown, isFalse); + expect(s.mapControlsExpanded, isTrue); + }); + }); + + group('MapViewState persistence', () { + test('round-trips every field through storage', () { + const s = MapViewState( + zoom: 12.4, + controlsMinimized: true, + controlPanelShown: false, + landscapeMapControlsExpanded: true, + mapControlsExpanded: false, + ); + expect(MapViewState.fromStored(s.toStorage()), s); + }); + + test('no zoom is written until one is recorded', () { + expect(const MapViewState().toStorage().containsKey('zoom'), isFalse); + }); + + test('a stored zoom outside the map range is clamped on read', () { + expect(MapViewState.fromStored({'zoom': 30}).zoom, MapViewState.maxZoom); + }); + + test('survives a Hive box close and reopen', () async { + final dir = await Directory.systemTemp.createTemp('map-view-state-'); + Hive.init(dir.path); + try { + const s = MapViewState(zoom: 9.75, controlsMinimized: true); + var box = await Hive.openBox('user_preferences'); + await box.put('map_view_state', s.toStorage()); + await box.close(); + box = await Hive.openBox('user_preferences'); + expect(MapViewState.fromStored(box.get('map_view_state')), s); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + }); + + group('MapViewState.clampZoom', () { + test('keeps an in-range zoom', () { + expect(MapViewState.clampZoom(12.4), 12.4); + }); + + test('clamps to the map\'s min and max', () { + expect(MapViewState.clampZoom(1.0), + closeTo(MapViewState.minZoom + MapViewState.zoomEpsilon, 1e-9)); + expect(MapViewState.clampZoom(22.0), MapViewState.maxZoom); + expect( + MapViewState.clampZoom(MapViewState.maxZoom), MapViewState.maxZoom); + }); + + test('nudges an integer zoom off the integer', () { + expect(MapViewState.clampZoom(14), closeTo(13.999, 1e-9)); + }); + + test('rejects non-numbers and non-finite values', () { + expect(MapViewState.clampZoom(null), isNull); + expect(MapViewState.clampZoom('12'), isNull); + expect(MapViewState.clampZoom(double.nan), isNull); + expect(MapViewState.clampZoom(double.infinity), isNull); + }); + }); + + group('MapViewState.zoomWorthSaving', () { + test('the first zoom is always worth saving', () { + expect(MapViewState.zoomWorthSaving(null, 15.0), isTrue); + }); + + test('a camera idle at the same zoom is not', () { + expect(MapViewState.zoomWorthSaving(15.0, 15.0), isFalse); + expect(MapViewState.zoomWorthSaving(15.0, 15.005), isFalse); + }); + + test('a real zoom change is', () { + expect(MapViewState.zoomWorthSaving(15.0, 14.5), isTrue); + expect(MapViewState.zoomWorthSaving(15.0, 15.02), isTrue); + }); + + test('a non-finite camera zoom never is', () { + expect(MapViewState.zoomWorthSaving(15.0, double.nan), isFalse); + expect(MapViewState.zoomWorthSaving(null, double.infinity), isFalse); + }); + }); +} diff --git a/test/models/repeater_scopes_checked_at_test.dart b/test/models/repeater_scopes_checked_at_test.dart new file mode 100644 index 00000000..9da93281 --- /dev/null +++ b/test/models/repeater_scopes_checked_at_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; + +/// `scopes_checked_at` is when the server last asked this repeater for its +/// scopes, across every phone. It is additive and lazy like the backbone +/// fields: absent on any server that predates it, and read by the due +/// rule's server-side check (Rule 1 in scope_discovery_rules.dart). +void main() { + final base = { + 'id': '4E', + 'hex_id': 'ab' * 32, + 'name': 'Hill', + 'lat': 1.0, + 'lon': 2.0, + 'last_heard': 0, + 'enabled': 1, + }; + + group('parsing', () { + test('an int timestamp parses as-is', () { + final r = Repeater.fromJson({...base, 'scopes_checked_at': 1790000000}); + expect(r.scopesCheckedAt, 1790000000); + }); + + test('missing reads null', () { + final r = Repeater.fromJson(base); + expect(r.scopesCheckedAt, isNull); + }); + + test('a non-numeric value reads null, never logged', () { + final r = Repeater.fromJson({...base, 'scopes_checked_at': 'x'}); + expect(r.scopesCheckedAt, isNull); + }); + + test('a num (e.g. 1.79e9) parses as an int', () { + final r = Repeater.fromJson({...base, 'scopes_checked_at': 1.79e9}); + expect(r.scopesCheckedAt, 1790000000); + }); + }); + + group('round trip', () { + test('absent stays absent, not an explicit null', () { + final json = Repeater.fromJson(base).toJson(); + expect(json.containsKey('scopes_checked_at'), isFalse); + }); + + test('a set value round-trips', () { + final json = + Repeater.fromJson({...base, 'scopes_checked_at': 1790000000}) + .toJson(); + expect(json['scopes_checked_at'], 1790000000); + final again = Repeater.fromJson({...base, ...json}); + expect(again.scopesCheckedAt, 1790000000); + }); + }); + + test('copyWith updates the field', () { + final r = Repeater.fromJson(base).copyWith(scopesCheckedAt: 1790000000); + expect(r.scopesCheckedAt, 1790000000); + }); +} diff --git a/test/models/repeater_scopes_test.dart b/test/models/repeater_scopes_test.dart new file mode 100644 index 00000000..17b8bd93 --- /dev/null +++ b/test/models/repeater_scopes_test.dart @@ -0,0 +1,200 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; +import 'package:mesh_mapper/models/repeater_scope.dart'; +import 'package:mesh_mapper/widgets/repeater_scope_chips.dart'; + +Map _base([Map extra = const {}]) => { + 'id': 'r1', + 'hex_id': 'AB', + 'name': 'Hill', + 'lat': 45.0, + 'lon': -75.0, + 'last_heard': 1, + 'enabled': 1, + ...extra, + }; + +void main() { + group('parsing', () { + test('an older server sends no scope fields: no chips', () { + final r = Repeater.fromJson(_base()); + expect(r.scopes, isEmpty); + expect(r.defaultScopeState, isNull); + expect(r.scopeChips, isEmpty); + }); + + test('reads every source and the default fields', () { + final r = Repeater.fromJson(_base({ + 'scopes': [ + { + 'scope': 'ottawa', + 'observed_at': 1700000000, + 'observed_pkts': 12, + 'proof': 'multibyte', + 'reported_at': null, + 'uploaded_at': 1700000100, + }, + {'scope': '*', 'reported_at': 1700000200}, + ], + 'default_scope': 'ottawa', + 'default_scope_state': 'named', + 'default_scope_at': 1700000300, + 'default_scope_src': 'advert', + })); + expect(r.scopes.map((s) => s.name), ['ottawa', '*']); + final o = r.scopes.first; + expect(o.observedAt, 1700000000); + expect(o.observedPkts, 12); + expect(o.proof, 'multibyte'); + expect(o.reportedAt, isNull); + expect(o.uploadedAt, 1700000100); + expect(o.sourceCount, 2); + expect(r.defaultScope, 'ottawa'); + expect(r.defaultScopeAt, 1700000300); + }); + + test('malformed scopes are ignored, not thrown', () { + for (final bad in [ + 'ottawa', + 42, + {'scope': 'x'}, + [null, 3, 'x', {'scope': ''}, {'scope': 7}, {'no': 'name'}], + ]) { + final r = Repeater.fromJson(_base({'scopes': bad})); + expect(r.scopes, isEmpty, reason: '$bad'); + } + }); + + test('a repeated name keeps its first entry', () { + final list = RepeaterScope.listFromJson([ + {'scope': 'a', 'reported_at': 5}, + {'scope': 'a', 'uploaded_at': 6}, + ]); + expect(list, hasLength(1)); + expect(list.single.reportedAt, 5); + expect(list.single.uploadedAt, isNull); + }); + + test('scope fields survive the cache round trip', () { + final r = Repeater.fromJson(_base({ + 'scopes': [ + {'scope': 'ottawa', 'reported_at': 1700000000}, + ], + 'default_scope_state': 'none', + 'default_scope_src': 'reported', + })); + final back = Repeater.fromJson(r.toJson()); + expect(back.scopes.single.name, 'ottawa'); + expect(back.scopes.single.reportedAt, 1700000000); + expect(back.defaultScopeState, 'none'); + expect(back.defaultScopeSrc, 'reported'); + }); + + test('no scope keys are written when there are none', () { + final json = Repeater.fromJson(_base()).toJson(); + expect(json.containsKey('scopes'), isFalse); + expect(json.containsKey('default_scope_state'), isFalse); + }); + }); + + group('chips', () { + test('star on the default, then more sources, then name', () { + final chips = repeaterScopeChips( + scopes: const [ + RepeaterScope(name: 'zeta', reportedAt: 1, uploadedAt: 2), + RepeaterScope(name: 'alpha', reportedAt: 1), + RepeaterScope(name: 'Beta', uploadedAt: 1), + RepeaterScope(name: 'home', reportedAt: 1), + ], + defaultScope: 'home', + defaultScopeState: 'named', + ); + expect(chips.map((c) => c.label), ['home', 'zeta', 'alpha', 'Beta']); + expect(chips.first.isDefault, isTrue); + expect(chips.skip(1).any((c) => c.isDefault), isFalse); + }); + + test('* reads Not set, never all, and takes the star for state none', () { + final chips = repeaterScopeChips( + scopes: const [RepeaterScope(name: '*', reportedAt: 1)], + defaultScopeState: 'none', + ); + expect(chips.single.label, 'Not set'); + expect(chips.single.isDefault, isTrue); + expect(chips.single.details.first, startsWith('Passes messages that')); + expect(chips.single.label.toLowerCase(), isNot(contains('all'))); + }); + + test('a named default with no scope entry still gets its own chip', () { + final chips = repeaterScopeChips( + scopes: const [], + defaultScope: 'gatineau', + defaultScopeState: 'named', + defaultScopeSrc: 'reported', + ); + expect(chips.single.label, 'gatineau'); + expect(chips.single.isDefault, isTrue); + expect(chips.single.details.single, contains('its observer report')); + }); + + test('an unconfirmed default shows a starred question mark', () { + final chips = repeaterScopeChips( + scopes: const [], + defaultScopeState: 'unknown', + ); + expect(chips.single.label, '?'); + expect(chips.single.isDefault, isTrue); + }); + + test('details name each source', () { + final chip = repeaterScopeChips(scopes: const [ + RepeaterScope( + name: 'x', + observedAt: 1, + observedPkts: 1, + proof: 'firmware', + reportedAt: 1, + uploadedAt: 1), + ]).single; + expect(chip.details, hasLength(3)); + expect(chip.details[0], contains('Seen forwarding 1 packet')); + expect(chip.details[0], contains('its firmware version')); + expect(chip.details[1], startsWith('Reported')); + expect(chip.details[2], startsWith("Uploaded by a wardriver's app")); + }); + }); + + group('widget', () { + Future pump(WidgetTester tester, List chips) => + tester.pumpWidget(MaterialApp( + home: Scaffold(body: RepeaterScopeChips(chips: chips)), + )); + + testWidgets('folds after four and expands on tap', (tester) async { + final chips = repeaterScopeChips(scopes: [ + for (final n in ['a', 'b', 'c', 'd', 'e', 'f']) + RepeaterScope(name: n, reportedAt: 1), + ]); + await pump(tester, chips); + expect(find.text('a'), findsOneWidget); + expect(find.text('e'), findsNothing); + expect(find.text('+2 more'), findsOneWidget); + await tester.tap(find.text('+2 more')); + await tester.pump(); + expect(find.text('f'), findsOneWidget); + expect(find.text('+2 more'), findsNothing); + }); + + testWidgets('tapping a chip shows where it came from', (tester) async { + await pump( + tester, + repeaterScopeChips( + scopes: const [RepeaterScope(name: 'ottawa', uploadedAt: 1)])); + await tester.tap(find.text('ottawa')); + await tester.pumpAndSettle(); + expect(find.textContaining("Uploaded by a wardriver's app"), + findsOneWidget); + }); + }); +} diff --git a/test/models/scope_log_entry_test.dart b/test/models/scope_log_entry_test.dart new file mode 100644 index 00000000..1bfd090a --- /dev/null +++ b/test/models/scope_log_entry_test.dart @@ -0,0 +1,120 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; + +void main() { + test('every outcome reads in plain words', () { + expect(ScopeLogOutcome.values.map((o) => o.label), [ + 'Answered', + 'No response from repeater', + 'Sent as a flood by the radio', + 'Unreadable answer', + 'Radio error', + 'Radio contact list full', + 'Not uploaded: hourly limit reached', + ]); + }); + + test('an entry keeps the names exactly as received', () { + final entry = ScopeLogEntry( + timestamp: DateTime(2026, 9, 26, 10), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const ['Ottawa', '*', 'west'], + ); + expect(entry.scopes, ['Ottawa', '*', 'west']); + expect(entry.outcome.label, 'Answered'); + final empty = ScopeLogEntry( + timestamp: DateTime(2026, 9, 26, 10), + latitude: 0, + longitude: 0, + repeaterId: 'CD', + pubkeyHex: 'CD', + outcome: ScopeLogOutcome.noResponse, + ); + expect(empty.scopes, isNull); + }); + + test('timeString is zero-padded HH:MM:SS', () { + final entry = ScopeLogEntry( + timestamp: DateTime(2026, 9, 26, 9, 4, 7), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const ['Ottawa'], + ); + expect(entry.timeString, '09:04:07'); + }); + + test('locationString is 5 decimal places', () { + final entry = ScopeLogEntry( + timestamp: DateTime(2026, 9, 26, 10), + latitude: 45.123456, + longitude: -75.234567, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + ); + expect(entry.locationString, '45.12346,-75.23457'); + }); + + group('toCsv', () { + test('an answered entry lists its scope names, semicolon-joined', () { + final entry = ScopeLogEntry( + timestamp: DateTime.utc(2026, 9, 26, 10, 0, 0), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const ['Ottawa', '*', 'west'], + ); + expect(entry.toCsv(), + '2026-09-26T10:00:00.000Z,45.1,-75.2,AB,answered,"Ottawa;*;west"'); + }); + + test('an outcome with no scopes carries an empty quoted field', () { + final entry = ScopeLogEntry( + timestamp: DateTime.utc(2026, 9, 26, 10, 0, 0), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.noResponse, + ); + expect(entry.toCsv(), + '2026-09-26T10:00:00.000Z,45.1,-75.2,AB,noResponse,""'); + }); + + test('a radio-contacts-full entry carries its own outcome word', () { + final entry = ScopeLogEntry( + timestamp: DateTime.utc(2026, 9, 26, 10, 0, 0), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.radioContactsFull, + ); + expect(entry.toCsv(), + '2026-09-26T10:00:00.000Z,45.1,-75.2,AB,radioContactsFull,""'); + }); + + test('an answered entry with an empty scope list still quotes empty', () { + final entry = ScopeLogEntry( + timestamp: DateTime.utc(2026, 9, 26, 10, 0, 0), + latitude: 0, + longitude: 0, + repeaterId: 'CD', + pubkeyHex: 'CD' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const [], + ); + expect( + entry.toCsv(), '2026-09-26T10:00:00.000Z,0.0,0.0,CD,answered,""'); + }); + }); +} diff --git a/test/models/scope_log_store_test.dart b/test/models/scope_log_store_test.dart new file mode 100644 index 00000000..a4e5c891 --- /dev/null +++ b/test/models/scope_log_store_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; + +/// `AppStateProvider` cannot be constructed in this suite (it opens Hive +/// boxes, BLE and GPS in its constructor), so `clearLogs`/`clearPings` +/// clearing scope entries cannot be driven through the provider directly. +/// `ScopeLogStore` is the class the provider owns and delegates +/// `_addScopeLogEntry`/`clearLogs`/`clearPings` to (each a one-line call: +/// `_scopeLog.add(entry)`, `_scopeLog.clear()`), so exercising this store's +/// own add/cap/clear is exercising the actual clearing behavior those three +/// call sites depend on. +ScopeLogEntry _entry(DateTime timestamp) => ScopeLogEntry( + timestamp: timestamp, + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const ['Ottawa'], + ); + +void main() { + test('starts empty', () { + expect(ScopeLogStore().entries, isEmpty); + }); + + test('add inserts newest first', () { + final store = ScopeLogStore(); + final first = _entry(DateTime(2026, 9, 26, 9)); + final second = _entry(DateTime(2026, 9, 26, 10)); + + store.add(first); + store.add(second); + + expect(store.entries, [second, first]); + }); + + test('caps at maxEntries, dropping the oldest', () { + final store = ScopeLogStore(maxEntries: 3); + final e0 = _entry(DateTime(2026, 9, 26, 9, 0)); + final e1 = _entry(DateTime(2026, 9, 26, 9, 1)); + final e2 = _entry(DateTime(2026, 9, 26, 9, 2)); + final e3 = _entry(DateTime(2026, 9, 26, 9, 3)); + + store.add(e0); + store.add(e1); + store.add(e2); + expect(store.entries, hasLength(3)); + + store.add(e3); + expect(store.entries, hasLength(3)); + expect(store.entries, [e3, e2, e1]); + expect(store.entries.contains(e0), isFalse); + }); + + test('defaults to the app-wide 500 cap', () { + final store = ScopeLogStore(); + expect(store.maxEntries, 500); + }); + + test('clear empties the store, this is what clearLogs/clearPings call', () { + final store = ScopeLogStore(); + store.add(_entry(DateTime(2026, 9, 26, 9))); + store.add(_entry(DateTime(2026, 9, 26, 10))); + expect(store.entries, isNotEmpty); + + store.clear(); + + expect(store.entries, isEmpty); + }); + + test('entries is unmodifiable', () { + final store = ScopeLogStore(); + store.add(_entry(DateTime(2026, 9, 26, 9))); + expect(() => store.entries.add(_entry(DateTime(2026, 9, 26, 10))), + throwsUnsupportedError); + }); +} diff --git a/test/models/user_preferences_gps_marker_color_test.dart b/test/models/user_preferences_gps_marker_color_test.dart new file mode 100644 index 00000000..6b732c26 --- /dev/null +++ b/test/models/user_preferences_gps_marker_color_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; + +void main() { + test('the GPS marker colour is the default by default', () { + const prefs = UserPreferences(); + expect(prefs.gpsMarkerColor, 'default'); + expect(prefs.toJson()['gpsMarkerColor'], 'default'); + }); + + test('a missing, null, unknown or non-string value reads as the default', + () { + expect(UserPreferences.fromJson({}).gpsMarkerColor, 'default'); + for (final value in [null, 'purple', '', 3, true]) { + expect( + UserPreferences.fromJson({'gpsMarkerColor': value}).gpsMarkerColor, + 'default', + reason: 'stored value $value'); + } + }); + + test('green round trips through json', () { + const prefs = UserPreferences(gpsMarkerColor: 'green'); + final back = UserPreferences.fromJson(prefs.toJson()); + expect(back.gpsMarkerColor, 'green'); + expect(back, prefs); + }); + + test('copyWith changes only the field it is given', () { + const prefs = + UserPreferences(gpsMarkerColor: 'green', gpsMarkerStyle: 'car'); + + final back = prefs.copyWith(gpsMarkerColor: 'default'); + expect(back.gpsMarkerColor, 'default'); + expect(back.gpsMarkerStyle, 'car'); + + final style = prefs.copyWith(gpsMarkerStyle: 'bike'); + expect(style.gpsMarkerColor, 'green'); + + expect(prefs.copyWith(), prefs); + }); + + test('equality and hashCode follow the field', () { + const green = UserPreferences(gpsMarkerColor: 'green'); + const alsoGreen = UserPreferences(gpsMarkerColor: 'green'); + const plain = UserPreferences(); + expect(green, alsoGreen); + expect(green.hashCode, alsoGreen.hashCode); + expect(green, isNot(plain)); + expect(green.hashCode, isNot(plain.hashCode)); + }); +} diff --git a/test/models/user_preferences_repeater_coverage_lines_test.dart b/test/models/user_preferences_repeater_coverage_lines_test.dart new file mode 100644 index 00000000..004e01dd --- /dev/null +++ b/test/models/user_preferences_repeater_coverage_lines_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; + +void main() { + test('repeater coverage lines are off by default', () { + const prefs = UserPreferences(); + expect(prefs.showRepeaterCoverageLines, isFalse); + expect(prefs.toJson()['showRepeaterCoverageLines'], false); + }); + + test('a missing or null value falls back to off', () { + expect(UserPreferences.fromJson({}).showRepeaterCoverageLines, isFalse); + expect( + UserPreferences.fromJson({'showRepeaterCoverageLines': null}) + .showRepeaterCoverageLines, + isFalse); + }); + + test('round trips through json', () { + const prefs = UserPreferences(showRepeaterCoverageLines: true); + final back = UserPreferences.fromJson(prefs.toJson()); + expect(back.showRepeaterCoverageLines, isTrue); + expect(back, prefs); + }); + + test('copyWith changes only the field it is given', () { + const prefs = + UserPreferences(showRepeaterCoverageLines: true, mapStyle: 'dark'); + + final off = prefs.copyWith(showRepeaterCoverageLines: false); + expect(off.showRepeaterCoverageLines, isFalse); + expect(off.mapStyle, 'dark'); + + final style = prefs.copyWith(mapStyle: 'liberty'); + expect(style.showRepeaterCoverageLines, isTrue); + + expect(prefs.copyWith(), prefs); + }); + + test('equality and hashCode follow the field', () { + const on = UserPreferences(showRepeaterCoverageLines: true); + const alsoOn = UserPreferences(showRepeaterCoverageLines: true); + const off = UserPreferences(); + expect(on, alsoOn); + expect(on.hashCode, alsoOn.hashCode); + expect(on, isNot(off)); + expect(on.hashCode, isNot(off.hashCode)); + }); +} diff --git a/test/models/user_preferences_scope_discovery_test.dart b/test/models/user_preferences_scope_discovery_test.dart new file mode 100644 index 00000000..c82ee370 --- /dev/null +++ b/test/models/user_preferences_scope_discovery_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; + +void main() { + test('scope discovery defaults to off with a 14 day window', () { + const prefs = UserPreferences(); + expect(prefs.scopeDiscoveryEnabled, isFalse); + expect(prefs.scopeDiscoveryDays, 14); + expect(ScopeDiscoveryDays.min, 7); + expect(ScopeDiscoveryDays.max, 365); + expect(ScopeDiscoveryDays.defaultDays, 14); + }); + + test('round trips through json', () { + const prefs = + UserPreferences(scopeDiscoveryEnabled: true, scopeDiscoveryDays: 30); + final back = UserPreferences.fromJson(prefs.toJson()); + expect(back.scopeDiscoveryEnabled, isTrue); + expect(back.scopeDiscoveryDays, 30); + expect(back, prefs); + }); + + test('stored 3 reads 7, stored 400 reads 365, missing reads 14', () { + expect( + UserPreferences.fromJson({'scopeDiscoveryDays': 3}).scopeDiscoveryDays, + 7); + expect( + UserPreferences.fromJson({'scopeDiscoveryDays': 400}) + .scopeDiscoveryDays, + 365); + expect(UserPreferences.fromJson({}).scopeDiscoveryDays, 14); + expect(UserPreferences.fromJson({}).scopeDiscoveryEnabled, isFalse); + }); + + test('copyWith changes only what it is given', () { + const prefs = UserPreferences(); + final changed = prefs.copyWith(scopeDiscoveryDays: 30); + expect(changed.scopeDiscoveryDays, 30); + expect(changed.scopeDiscoveryEnabled, isFalse); + expect( + prefs.copyWith(scopeDiscoveryEnabled: true).scopeDiscoveryEnabled, + isTrue); + }); + + test('equality includes both fields', () { + const base = UserPreferences(); + expect(base, const UserPreferences()); + expect(base, isNot(const UserPreferences(scopeDiscoveryEnabled: true))); + expect(base, isNot(const UserPreferences(scopeDiscoveryDays: 30))); + }); +} diff --git a/test/models/user_preferences_smart_ping_test.dart b/test/models/user_preferences_smart_ping_test.dart index 1b72c70e..fb5cba65 100644 --- a/test/models/user_preferences_smart_ping_test.dart +++ b/test/models/user_preferences_smart_ping_test.dart @@ -26,11 +26,18 @@ void main() { expect(SmartPingDays.defaultDays, 14); }); + test('delay only flood pings defaults to on', () { + expect(const UserPreferences().smartPingFloodOnly, isTrue); + expect(UserPreferences.fromJson({}).smartPingFloodOnly, isTrue); + }); + test('round trips through json', () { - const prefs = UserPreferences(smartPingEnabled: false, smartPingDays: 3); + const prefs = UserPreferences( + smartPingEnabled: false, smartPingDays: 3, smartPingFloodOnly: false); final back = UserPreferences.fromJson(prefs.toJson()); expect(back.smartPingEnabled, isFalse); expect(back.smartPingDays, 3); + expect(back.smartPingFloodOnly, isFalse); expect(back, prefs); }); @@ -50,5 +57,9 @@ void main() { expect(changed.smartPingDays, 30); expect(changed.smartPingEnabled, isTrue); expect(prefs.copyWith(smartPingEnabled: false).smartPingEnabled, isFalse); + final flood = prefs.copyWith(smartPingFloodOnly: false); + expect(flood.smartPingFloodOnly, isFalse); + expect(flood, isNot(prefs)); + expect(flood.copyWith(smartPingFloodOnly: true), prefs); }); } diff --git a/test/models/user_preferences_top_heard_test.dart b/test/models/user_preferences_top_heard_test.dart new file mode 100644 index 00000000..4e2be0a8 --- /dev/null +++ b/test/models/user_preferences_top_heard_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; + +void main() { + test('the row range is 3 to 8, defaulting to 3', () { + expect(UserPreferences.topHeardRowsMin, 3); + expect(UserPreferences.topHeardRowsMax, 8); + expect(UserPreferences.topHeardRowsDefault, 3); + }); + + test('Top Heard shows 3 rows with hex IDs by default', () { + const prefs = UserPreferences(); + expect(prefs.topHeardRows, 3); + expect(prefs.topHeardShowNames, isFalse); + expect(prefs.toJson()['topHeardRows'], 3); + expect(prefs.toJson()['topHeardShowNames'], false); + }); + + test('round trips non-default values through json', () { + const prefs = UserPreferences(topHeardRows: 6, topHeardShowNames: true); + final back = UserPreferences.fromJson(prefs.toJson()); + expect(back.topHeardRows, 6); + expect(back.topHeardShowNames, isTrue); + expect(back, prefs); + }); + + test('copyWith changes only the field it is given', () { + const prefs = UserPreferences(topHeardRows: 5, topHeardShowNames: true); + + final rows = prefs.copyWith(topHeardRows: 8); + expect(rows.topHeardRows, 8); + expect(rows.topHeardShowNames, isTrue); + + final names = prefs.copyWith(topHeardShowNames: false); + expect(names.topHeardShowNames, isFalse); + expect(names.topHeardRows, 5); + + expect(prefs.copyWith(), prefs); + }); + + test('missing keys fall back to the defaults', () { + final prefs = UserPreferences.fromJson({}); + expect(prefs.topHeardRows, 3); + expect(prefs.topHeardShowNames, isFalse); + }); + + test('the row count is clamped to 3..8', () { + int rows(Object? value) => + UserPreferences.fromJson({'topHeardRows': value}).topHeardRows; + + expect(rows(3), 3); + expect(rows(8), 8); + expect(rows(5), 5); + expect(rows(0), 3); + expect(rows(-4), 3); + expect(rows(2), 3); + expect(rows(9), 8); + expect(rows(99), 8); + }); + + test('a numeric row count is truncated, anything else is the default', () { + int rows(Object? value) => + UserPreferences.fromJson({'topHeardRows': value}).topHeardRows; + + expect(rows(5.0), 5); + expect(rows(5.9), 5); + expect(rows(double.nan), 3); + expect(rows(double.infinity), 3); + expect(rows('6'), 3); + expect(rows(null), 3); + expect(rows(true), 3); + expect(rows(const [6]), 3); + }); + + test('equality and hashCode follow both fields', () { + const base = UserPreferences(topHeardRows: 5, topHeardShowNames: true); + const same = UserPreferences(topHeardRows: 5, topHeardShowNames: true); + const otherRows = UserPreferences(topHeardRows: 6, topHeardShowNames: true); + const otherNames = + UserPreferences(topHeardRows: 5, topHeardShowNames: false); + + expect(base, same); + expect(base.hashCode, same.hashCode); + expect(base, isNot(otherRows)); + expect(base.hashCode, isNot(otherRows.hashCode)); + expect(base, isNot(otherNames)); + expect(base.hashCode, isNot(otherNames.hashCode)); + }); +} diff --git a/test/providers/auth_slot_estimate_test.dart b/test/providers/auth_slot_estimate_test.dart new file mode 100644 index 00000000..76d7a496 --- /dev/null +++ b/test/providers/auth_slot_estimate_test.dart @@ -0,0 +1,38 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The connection screen's slot count is the cached /status figure, less one +/// for the slot an /auth just took. A reused session (every auto-reconnect +/// inside the session's life) takes no new slot, but was counted as one, so +/// a reconnect loop walked the estimate down to zero. + +void main() { + test('a new session with TX takes a slot', () { + expect(authTookNewSlot({'success': true, 'tx_allowed': true}), isTrue); + }); + + test('a reused session takes no slot', () { + expect( + authTookNewSlot( + {'success': true, 'tx_allowed': true, 'resume_counter': 14}), + isFalse); + }); + + test('a reused session with no pings yet still takes no slot', () { + expect( + authTookNewSlot( + {'success': true, 'tx_allowed': true, 'resume_counter': 0}), + isFalse); + }); + + test('no TX means no slot', () { + expect(authTookNewSlot({'success': true, 'tx_allowed': false}), isFalse); + }); + + test('a server count is used as is, not adjusted', () { + expect( + authTookNewSlot( + {'success': true, 'tx_allowed': true, 'slots_available': 3}), + isFalse); + }); +} diff --git a/test/providers/disconnect_queue_upload_test.dart b/test/providers/disconnect_queue_upload_test.dart new file mode 100644 index 00000000..8d417cd0 --- /dev/null +++ b/test/providers/disconnect_queue_upload_test.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The bound on the queue upload a Disconnect or Close App tap makes before +/// it releases the session. The tap used to clear the queue without sending +/// it, so a TX still in its 5 s upload wait or an RX batch inside its 15 s +/// window was lost on almost every drive that ended with Stop and then +/// Disconnect. The upload must never hold the teardown open or abandon it. +void main() { + test('an upload that finishes is reported done', () async { + var ran = false; + expect(await uploadQueueBounded(() async => ran = true), isTrue); + expect(ran, isTrue); + }); + + test('a stalled upload does not hold the disconnect open', () async { + final stalled = Completer(); + addTearDown(() { + if (!stalled.isCompleted) stalled.complete(); + }); + + expect( + await uploadQueueBounded( + () => stalled.future, + limit: const Duration(milliseconds: 20), + ), + isFalse, + reason: 'the disconnect clears the queue and releases the session ' + 'once the bound runs out', + ); + }); + + test('a failed upload does not abandon the disconnect', () async { + expect( + await uploadQueueBounded(() async => throw StateError('no network')), + isFalse, + ); + }); + + test('the bound keeps the Disconnect tap quick', () { + expect(disconnectQueueUploadTimeout, const Duration(seconds: 5)); + }); +} diff --git a/test/providers/error_log_unseen_test.dart b/test/providers/error_log_unseen_test.dart new file mode 100644 index 00000000..04a42fbd --- /dev/null +++ b/test/providers/error_log_unseen_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The Log tab's red dot used to mean "the error log is not empty", so +/// reading every error left it on and only Clear all logs (which also wipes +/// the ping log) removed it (#617). It now means an error logged after the +/// last time the Errors tab was on screen. +void main() { + test('no errors, no dot', () { + expect(errorLogHasUnseen(hasEntries: false, logged: 0, seen: 0), isFalse); + }); + + test('errors never seen show the dot', () { + expect(errorLogHasUnseen(hasEntries: true, logged: 2, seen: 0), isTrue); + }); + + test('errors seen up to the newest clear it', () { + expect(errorLogHasUnseen(hasEntries: true, logged: 2, seen: 2), isFalse); + }); + + test('a newer error brings it back', () { + expect(errorLogHasUnseen(hasEntries: true, logged: 3, seen: 2), isTrue); + }); + + test('a cleared log shows no dot whatever the counts', () { + // Clear all logs empties the list; the next error logged is new again. + expect(errorLogHasUnseen(hasEntries: false, logged: 5, seen: 2), isFalse); + }); +} diff --git a/test/providers/go_online_zone_message_test.dart b/test/providers/go_online_zone_message_test.dart new file mode 100644 index 00000000..ba354d8a --- /dev/null +++ b/test/providers/go_online_zone_message_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The Go Online refusal outside every zone. It used to read "Could not +/// determine your zone. Check GPS and internet connection." even when the +/// server had answered plainly that the spot was 28 km outside the nearest +/// zone, so one tester retried 11 times. The check now runs before +/// wardriving stops, so the message also says Offline Mode stays on. +void main() { + test('names the nearest zone and its distance', () { + expect( + goOnlineOutsideZoneMessage( + {'name': 'Greater Montana, US', 'code': 'FCA', 'distance_km': 27.97}), + 'You are outside every MeshMapper zone. Nearest zone is ' + 'Greater Montana, US, 28.0km away. Offline Mode stays on.', + ); + }); + + test('uses miles for imperial units', () { + expect( + goOnlineOutsideZoneMessage( + {'name': 'Greater Montana, US', 'distance_km': 27.97}, + isImperial: true), + contains('17.4mi away'), + ); + }); + + test('without a nearest zone it still says what happened', () { + const plain = + 'You are outside every MeshMapper zone. Offline Mode stays on.'; + expect(goOnlineOutsideZoneMessage(null), plain); + expect(goOnlineOutsideZoneMessage({'name': 'Greater Montana, US'}), plain); + }); +} diff --git a/test/providers/reconnect_abandon_race_test.dart b/test/providers/reconnect_abandon_race_test.dart new file mode 100644 index 00000000..2cbf1c1a --- /dev/null +++ b/test/providers/reconnect_abandon_race_test.dart @@ -0,0 +1,153 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// An auto-reconnect that is abandoned (the 30 s budget, or the user's +/// Cancel) while its connect is still in flight must not tear down a newer +/// connection when that stale attempt finally ends. In one log the user +/// cancelled, connected again by hand, and the stale attempt's end then read +/// the new connection's "connected" step as its own and disconnected it. + +void main() { + group('shouldDisconnectOrphanedReconnect', () { + test('budget expires, the stale connect completes, nothing newer', () { + // The abandon stamped generation 8 and nobody connected since: the + // connection that is up is the stale attempt's own. + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: 8, currentGeneration: 8, connected: true), + isTrue, + ); + }); + + test('budget expires, the stale connect completes after a manual connect', + () { + // A manual connect bumped the generation: the connection is not ours. + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: 8, currentGeneration: 9, connected: true), + isFalse, + ); + }); + + test('cancel, then a manual connect, while the stale attempt fails', () { + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: 8, currentGeneration: 9, connected: true), + isFalse, + ); + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: 8, currentGeneration: 9, connected: false), + isFalse, + ); + }); + + test('a user Disconnect ended the reconnect: the orphan still closes', () { + // No abandon caught the attempt in flight, so nothing else closes a + // connection it completes afterwards. + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: null, currentGeneration: 8, connected: true), + isTrue, + ); + }); + + test('nothing is connected', () { + expect( + shouldDisconnectOrphanedReconnect( + abandonedAtGeneration: 8, currentGeneration: 8, connected: false), + isFalse, + ); + }); + }); + + group('reconnectBudgetGivesConnectGrace', () { + test('a connect in flight gets one grace period', () { + expect( + reconnectBudgetGivesConnectGrace( + connectInFlight: true, graceUsed: false), + isTrue); + }); + + test('the grace is bounded: a second expiry abandons', () { + expect( + reconnectBudgetGivesConnectGrace( + connectInFlight: true, graceUsed: true), + isFalse); + }); + + test('nothing in flight abandons at once', () { + expect( + reconnectBudgetGivesConnectGrace( + connectInFlight: false, graceUsed: false), + isFalse); + }); + }); + + // The connect workflow's auth step runs the provider's callback, which + // awaits a GPS fix and sometimes a radio rename before it POSTs. An + // abandon in that gap used to let the stale attempt POST /auth + // reason=connect anyway, alongside the abandon's own release. + group('authCallbackSuperseded', () { + test('the attempt that made the callback still owns the connect', () { + expect( + authCallbackSuperseded( + createdAtGeneration: 4, + currentGeneration: 4, + sameConnection: true), + isFalse); + }); + + test('an abandon or a newer connect moved the generation on', () { + expect( + authCallbackSuperseded( + createdAtGeneration: 4, + currentGeneration: 5, + sameConnection: true), + isTrue); + }); + + test('the connection it was made for is gone or replaced', () { + // The abandon disposes and drops the stale connection at once. + expect( + authCallbackSuperseded( + createdAtGeneration: 4, + currentGeneration: 4, + sameConnection: false), + isTrue); + }); + }); + + // The disconnect cleanup awaits the queue flush and the session release + // before it disposes the connection. Cancel, then a quick Connect, put a + // new connection in place during those awaits, and the cleanup's end used + // to dispose that one. + group('cleanupOwnsCurrentConnection', () { + test('nothing connected since the cleanup started', () { + expect( + cleanupOwnsCurrentConnection( + cleanupGeneration: 7, + currentGeneration: 7, + newerConnectLive: false), + isTrue); + }); + + test('a connect started during the cleanup owns what is current', () { + expect( + cleanupOwnsCurrentConnection( + cleanupGeneration: 7, + currentGeneration: 8, + newerConnectLive: true), + isFalse); + }); + + test('a connect that failed or was cancelled since owns nothing', () { + expect( + cleanupOwnsCurrentConnection( + cleanupGeneration: 7, + currentGeneration: 8, + newerConnectLive: false), + isTrue); + }); + }); +} diff --git a/test/providers/reconnect_claims_reconcile_test.dart b/test/providers/reconnect_claims_reconcile_test.dart new file mode 100644 index 00000000..a7462b33 --- /dev/null +++ b/test/providers/reconnect_claims_reconcile_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// Every connect refreshes the companion's repeater claims through the +/// server's `mine` action, which allows 60 calls an hour. A reconnect loop +/// spent that in minutes (HTTP 429). Auto-reconnects inside one session now +/// refresh at most once per [claimsReconcileReconnectSpacing]. + +void main() { + final t0 = DateTime(2026, 11, 8, 12); + + bool decide({ + bool autoReconnect = true, + String? lastSession = 'YOW-20261108-0001', + DateTime? lastAt, + String? session = 'YOW-20261108-0001', + required DateTime now, + }) => + shouldReconcileClaimsOnConnect( + autoReconnect: autoReconnect, + sessionId: session, + lastSessionId: lastSession, + lastAt: lastAt, + now: now, + ); + + test('a manual connect always refreshes', () { + expect(decide(autoReconnect: false, lastAt: t0, now: t0), isTrue); + }); + + test('a reconnect soon after the last refresh in the session skips', () { + expect( + decide(lastAt: t0, now: t0.add(const Duration(minutes: 2))), isFalse); + }); + + test('a reconnect past the spacing refreshes', () { + expect( + decide( + lastAt: t0, + now: t0.add(claimsReconcileReconnectSpacing)), + isTrue); + }); + + test('a reconnect into a new session refreshes', () { + expect( + decide( + lastAt: t0, + session: 'YOW-20261108-0002', + now: t0.add(const Duration(minutes: 1))), + isTrue); + }); + + test('a reconnect with no earlier refresh refreshes', () { + expect(decide(lastAt: null, now: t0), isTrue); + }); +} diff --git a/test/providers/repeater_list_state_test.dart b/test/providers/repeater_list_state_test.dart new file mode 100644 index 00000000..ab99ea4e --- /dev/null +++ b/test/providers/repeater_list_state_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; +import 'package:mesh_mapper/providers/repeater_list_state.dart'; + +void main() { + final repeater = Repeater.fromJson({ + 'id': 'ab', + 'hex_id': 'ab1234', + 'lat': 45, + 'lon': -75, + 'enabled': 1, + }); + final now = DateTime.utc(2026, 10, 4); + RepeaterListState loaded() => const RepeaterListState().afterFetch( + fetched: [repeater], + requestedZone: 'YOW', + requestedPreset: 'preset-a', + currentZone: 'YOW', + currentPreset: 'preset-a', + now: now, + ); + + test('a failed refresh preserves the valid list and its freshness timestamp', + () { + final state = loaded(); + final result = state.afterFetch( + fetched: null, + requestedZone: 'YOW', + requestedPreset: 'preset-a', + currentZone: 'YOW', + currentPreset: 'preset-a', + now: now.add(const Duration(hours: 1))); + expect(result, same(state)); + expect(result.repeaters.single.hexId, 'ab1234'); + expect(result.loadedAt, now); + }); + + for (final context in [ + ('GROUP', 'preset-a'), + ('YOW', 'preset-b'), + (null, null) + ]) { + test('context $context clears the old list before a request finishes', () { + final state = loaded().forContext(context.$1, context.$2); + expect(state.repeaters, isEmpty); + expect(state.loadedAt, isNull); + expect(state.zone, isNull); + }); + + test('a failed or late old-context fetch cannot restore $context', () { + for (final fetched in [ + null, + [repeater] + ]) { + final state = loaded().afterFetch( + fetched: fetched, + requestedZone: 'YOW', + requestedPreset: 'preset-a', + currentZone: context.$1, + currentPreset: context.$2, + now: now); + expect(state.repeaters, isEmpty); + expect(state.loadedAt, isNull); + } + }); + } + + test('a failed initial read stays unloaded', () { + final state = const RepeaterListState().afterFetch( + fetched: null, + requestedZone: 'YOW', + requestedPreset: null, + currentZone: 'YOW', + currentPreset: null, + now: now); + expect(state.repeaters, isEmpty); + expect(state.loadedAt, isNull); + }); + + test('a current group result replaces the old region list', () { + final groupRepeater = repeater.copyWith(name: 'Group result'); + final state = loaded().afterFetch( + fetched: [groupRepeater], + requestedZone: 'GROUP', + requestedPreset: null, + currentZone: 'GROUP', + currentPreset: null, + now: now); + expect(state.repeaters.single.name, 'Group result'); + expect(state.zone, 'GROUP'); + expect(state.preset, isNull); + expect(state.loadedAt, now); + }); + + test('a list keyed on the group survives a move between members', () { + final loaded = const RepeaterListState().afterFetch( + fetched: [repeater], + requestedZone: 'ONQC', + requestedPreset: null, + currentZone: 'ONQC', + currentPreset: null, + now: DateTime(2026, 10, 12), + ); + expect(loaded.repeaters, isNotEmpty); + // YOW -> YUL inside ONQC: the context key stays ONQC. + expect(identical(loaded.forContext('ONQC', null), loaded), isTrue); + // Leaving the group clears it, as today. + expect(loaded.forContext('SEA', null).repeaters, isEmpty); + }); +} diff --git a/test/providers/scope_cannot_ask_non_contacts_test.dart b/test/providers/scope_cannot_ask_non_contacts_test.dart new file mode 100644 index 00000000..dc43d727 --- /dev/null +++ b/test/providers/scope_cannot_ask_non_contacts_test.dart @@ -0,0 +1,21 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The flag flipping on drops one warning in the error log, once per +/// connection: `AppStateProvider` cannot be built in these tests (it needs a +/// live Bluetooth service, Hive boxes, and a dozen other services), so this +/// exercises the pure once-per-connection decision `_wireScopeCannotAskNonContacts` +/// makes at the call site instead. +void main() { + test('the first flip on a connection should log', () { + expect( + shouldLogScopeContactsFull(alreadyLoggedThisConnection: false), + isTrue); + }); + + test('a later flip on the same connection should not log again', () { + expect( + shouldLogScopeContactsFull(alreadyLoggedThisConnection: true), + isFalse); + }); +} diff --git a/test/providers/scope_discovery_firmware_test.dart b/test/providers/scope_discovery_firmware_test.dart new file mode 100644 index 00000000..77d0111e --- /dev/null +++ b/test/providers/scope_discovery_firmware_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// Below companion firmware v1.16.0 (code 13) the switch still saves, but +/// nothing is asked and nothing extra is sent, so the Settings tile grows an +/// extra line while connected to that radio. +void main() { + test('firmware below the floor while connected needs the note', () { + expect( + scopeDiscoveryFirmwareTooOld(connected: true, firmwareCode: 11), + isTrue); + }); + + test('firmware at the floor while connected needs no note', () { + expect( + scopeDiscoveryFirmwareTooOld(connected: true, firmwareCode: 13), + isFalse); + }); + + test('disconnected never needs the note, whatever the last firmware code', + () { + expect( + scopeDiscoveryFirmwareTooOld(connected: false, firmwareCode: 11), + isFalse); + }); + + test('unknown firmware code while connected reads as too old', () { + expect( + scopeDiscoveryFirmwareTooOld(connected: true, firmwareCode: null), + isTrue); + }); +} diff --git a/test/providers/stuck_countdown_test.dart b/test/providers/stuck_countdown_test.dart new file mode 100644 index 00000000..1ceb0f98 --- /dev/null +++ b/test/providers/stuck_countdown_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// The stuck-timer watchdog must not name a window that is merely waiting +/// for its next 500 ms tick to clear it. +void main() { + final deadline = DateTime(2026, 10, 6, 12); + + test('not running is never stuck', () { + expect( + countdownLooksStuck( + isRunning: false, + endTime: deadline, + now: deadline.add(const Duration(minutes: 5))), + isFalse); + }); + + test('100 ms past the deadline is not stuck yet', () { + expect( + countdownLooksStuck( + isRunning: true, + endTime: deadline, + now: deadline.add(const Duration(milliseconds: 100))), + isFalse); + }); + + test('before the deadline is not stuck', () { + expect( + countdownLooksStuck( + isRunning: true, + endTime: deadline, + now: deadline.subtract(const Duration(seconds: 1))), + isFalse); + }); + + test('past the grace is stuck', () { + expect( + countdownLooksStuck( + isRunning: true, + endTime: deadline, + now: deadline.add(stuckCountdownGrace)), + isTrue); + }); + + test('running with no deadline is stuck', () { + expect(countdownLooksStuck(isRunning: true, endTime: null, now: deadline), + isTrue); + }); +} diff --git a/test/providers/zone_check_retry_test.dart b/test/providers/zone_check_retry_test.dart new file mode 100644 index 00000000..df2d358b --- /dev/null +++ b/test/providers/zone_check_retry_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; + +/// A zone check that got no answer was retried every 5 s for as long as the +/// network stayed down: one Android phone whose background network was cut +/// logged about 500 tries, twelve a minute for 20 minutes at a time. In a +/// server outage every phone would hit /status that hard. Retries now back +/// off to once a minute, and any real answer starts again from 5 s. +void main() { + test('backs off 5, 10, 20, 40, then every 60 seconds', () { + expect([for (var n = 1; n <= 7; n++) zoneCheckNetworkRetrySeconds(n)], + [5, 10, 20, 40, 60, 60, 60]); + }); + + test('a long outage never overflows past the cap', () { + expect(zoneCheckNetworkRetrySeconds(500), 60); + }); + + test('the first failure retries quickly', () { + expect(zoneCheckNetworkRetrySeconds(0), 5); + expect(zoneCheckNetworkRetrySeconds(1), 5); + }); +} diff --git a/test/screens/connection_screen_onboarding_test.dart b/test/screens/connection_screen_onboarding_test.dart index cd4a6a14..840a5bcf 100644 --- a/test/screens/connection_screen_onboarding_test.dart +++ b/test/screens/connection_screen_onboarding_test.dart @@ -159,6 +159,8 @@ class _ConnectedAppState extends ChangeNotifier implements AppStateProvider { @override bool get isAirborne => false; @override + GpsStatus get gpsStatus => GpsStatus.locked; + @override bool get offlineMode => false; @override bool get maintenanceMode => false; diff --git a/test/screens/log_screen_scopes_test.dart b/test/screens/log_screen_scopes_test.dart new file mode 100644 index 00000000..a9502d07 --- /dev/null +++ b/test/screens/log_screen_scopes_test.dart @@ -0,0 +1,405 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/log_entry.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; +import 'package:mesh_mapper/screens/log_screen.dart'; +import 'package:mesh_mapper/utils/ping_colors.dart'; + +/// `AppStateProvider` (constructed by `LogScreen`, which owns the private +/// `_AllPingsTab`/`_AllPingsTabState`) cannot be built in this suite: its +/// constructor opens Hive boxes and starts BLE/GPS (see +/// `test/widgets/ping_controls_scope_badge_test.dart`, which hit the same +/// wall for the Task 7 badge). `AllPingsTab` is the public widget that +/// `_AllPingsTab` was renamed to precisely so a test can pump the real filter +/// row, search field and card list directly, without going through +/// `LogScreen`. It needs no Provider ancestor either, as long as the fixture +/// entries are all `ScopeLogEntry` (the only per-type card builder whose +/// `AppStateProvider` read is deferred to its card's own tap, never the +/// build) and nothing taps a card body. `LogFilterSegment` and `ScopeLogCard` +/// are additionally pumped standalone below for the narrower, presentational +/// assertions (colour, "99+" cap, exact scope-name text) that do not need the +/// surrounding tab at all. +ScopeLogEntry _entry({ + DateTime? timestamp, + String repeaterId = 'AB', + ScopeLogOutcome outcome = ScopeLogOutcome.answered, + List? scopes, +}) { + return ScopeLogEntry( + timestamp: timestamp ?? DateTime(2026, 9, 26, 9, 4, 7), + latitude: 45.1, + longitude: -75.2, + repeaterId: repeaterId, + pubkeyHex: repeaterId * 32, + outcome: outcome, + scopes: scopes, + ); +} + +UnifiedPingLogEntry _scopeUnified(ScopeLogEntry entry) => UnifiedPingLogEntry( + type: PingLogType.scopes, timestamp: entry.timestamp, entry: entry); + +void main() { + group('AllPingsTab (real wiring)', () { + testWidgets( + 'tapping SCP hides the rendered scope cards, tapping again shows them', + (tester) async { + final ottawa = _entry(repeaterId: 'AB', scopes: const ['Ottawa']); + final west = _entry( + repeaterId: 'CD', + timestamp: DateTime(2026, 9, 26, 9, 5), + scopes: const ['west']); + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: AllPingsTab( + allEntries: [_scopeUnified(ottawa), _scopeUnified(west)], + repeaters: const [], + txCount: 0, + rxCount: 0, + discCount: 0, + traceCount: 0, + scopeCount: 2, + ), + ), + )); + + expect(find.byType(ScopeLogCard), findsNWidgets(2)); + + final scpSegment = find.descendant( + of: find.byType(LogFilterSegment), matching: find.text('SCP')); + expect(scpSegment, findsOneWidget); + + await tester.tap(scpSegment); + await tester.pump(); + expect(find.byType(ScopeLogCard), findsNothing); + + await tester.tap(scpSegment); + await tester.pump(); + expect(find.byType(ScopeLogCard), findsNWidgets(2)); + }); + + testWidgets( + 'typing a scope name into the search field shows only that card', + (tester) async { + final ottawa = _entry(repeaterId: 'AB', scopes: const ['Ottawa']); + final west = _entry( + repeaterId: 'CD', + timestamp: DateTime(2026, 9, 26, 9, 5), + scopes: const ['west']); + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: AllPingsTab( + allEntries: [_scopeUnified(ottawa), _scopeUnified(west)], + repeaters: const [], + txCount: 0, + rxCount: 0, + discCount: 0, + traceCount: 0, + scopeCount: 2, + ), + ), + )); + + expect(find.byType(ScopeLogCard), findsNWidgets(2)); + + await tester.enterText(find.byType(TextField), 'Ottawa'); + await tester.pump(); + + expect(find.byType(ScopeLogCard), findsOneWidget); + expect(find.text('AB'), findsOneWidget); + expect(find.text('CD'), findsNothing); + + // Scope names are case-sensitive: the lowercase form matches neither + // card. + await tester.enterText(find.byType(TextField), 'ottawa'); + await tester.pump(); + + expect(find.byType(ScopeLogCard), findsNothing); + }); + }); + + group('LogFilterSegment (SCP)', () { + testWidgets('renders the SCP label and a count pill', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Row( + children: [ + LogFilterSegment( + type: PingLogType.scopes, + label: 'SCP', + count: 12, + color: PingColors.scopes, + active: true, + onTap: () {}, + ), + ], + ), + ), + )); + + expect(find.text('SCP'), findsOneWidget); + expect(find.text('12'), findsOneWidget); + }); + + testWidgets('tapping calls onTap', (tester) async { + var tapped = false; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Row( + children: [ + LogFilterSegment( + type: PingLogType.scopes, + label: 'SCP', + count: 3, + color: PingColors.scopes, + active: false, + onTap: () => tapped = true, + ), + ], + ), + ), + )); + + await tester.tap(find.text('SCP')); + expect(tapped, isTrue); + }); + + testWidgets('a count above 99 caps the pill at 99+', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Row( + children: [ + LogFilterSegment( + type: PingLogType.scopes, + label: 'SCP', + count: 140, + color: PingColors.scopes, + active: true, + onTap: () {}, + ), + ], + ), + ), + )); + + expect(find.text('99+'), findsOneWidget); + }); + + testWidgets('no pill shows when the count is zero', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Row( + children: [ + LogFilterSegment( + type: PingLogType.scopes, + label: 'SCP', + count: 0, + color: PingColors.scopes, + active: true, + onTap: () {}, + ), + ], + ), + ), + )); + + expect(find.text('0'), findsNothing); + }); + }); + + group('filterUnifiedPingLog', () { + test('toggling scopes off hides scope entries, keeping the rest', () { + final scope = _entry(); + final scopeUnified = UnifiedPingLogEntry( + type: PingLogType.scopes, timestamp: scope.timestamp, entry: scope); + final tx = TxLogEntry( + timestamp: DateTime(2026, 9, 26, 10), + latitude: 45.1, + longitude: -75.2, + power: 0.3, + events: const [], + ); + final txUnified = UnifiedPingLogEntry( + type: PingLogType.tx, timestamp: tx.timestamp, entry: tx); + final all = [scopeUnified, txUnified]; + + const everyType = { + PingLogType.tx, + PingLogType.rx, + PingLogType.disc, + PingLogType.trace, + PingLogType.scopes, + }; + expect(filterUnifiedPingLog(all, everyType), all); + + const withoutScopes = { + PingLogType.tx, + PingLogType.rx, + PingLogType.disc, + PingLogType.trace, + }; + expect(filterUnifiedPingLog(all, withoutScopes), [txUnified]); + }); + }); + + group('scopeEntryMatchesSearch', () { + test('an empty query matches everything', () { + expect(scopeEntryMatchesSearch(_entry(), ''), isTrue); + }); + + test('matches the repeater id, case-insensitively', () { + expect(scopeEntryMatchesSearch(_entry(repeaterId: 'AB'), 'ab'), isTrue); + }); + + test('matches a scope name, case-sensitively', () { + final entry = _entry(scopes: const ['Ottawa', 'west']); + expect(scopeEntryMatchesSearch(entry, 'Ottawa'), isTrue); + expect(scopeEntryMatchesSearch(entry, 'ottawa'), isFalse); + }); + + test('matches the outcome words, case-insensitively', () { + final entry = _entry(outcome: ScopeLogOutcome.noResponse); + expect(scopeEntryMatchesSearch(entry, 'no response'), isTrue); + }); + + test('no match falls through to false', () { + expect(scopeEntryMatchesSearch(_entry(), 'nowhere'), isFalse); + }); + }); + + group('ScopeLogCard', () { + testWidgets('shows the SCP badge, time, location and repeater id', + (tester) async { + final entry = _entry(scopes: const ['Ottawa']); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: ScopeLogCard(entry: entry, onTap: () {})), + )); + + expect(find.text('SCP'), findsOneWidget); + expect(find.text(entry.timeString), findsOneWidget); + expect(find.text(entry.locationString), findsOneWidget); + expect(find.text('AB'), findsOneWidget); + }); + + for (final brightness in Brightness.values) { + testWidgets( + 'the SCP label and scope chips use the ${brightness.name} ink', + (tester) async { + final entry = _entry(scopes: const ['Ottawa']); + await tester.pumpWidget(MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold(body: ScopeLogCard(entry: entry, onTap: () {})), + )); + final ink = PingColors.scopesFor(brightness); + expect(tester.widget(find.text('SCP')).style?.color, ink); + expect(tester.widget(find.text('Ottawa')).style?.color, ink); + }); + } + + testWidgets('an answered card shows its scope names exactly, case kept', + (tester) async { + final entry = _entry(scopes: const ['Ottawa', '*', 'west']); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: ScopeLogCard(entry: entry, onTap: () {})), + )); + + expect(find.text('Answered'), findsOneWidget); + expect(find.text('Ottawa'), findsOneWidget); + expect(find.text('*'), findsOneWidget); + expect(find.text('west'), findsOneWidget); + expect(find.text('Carries no scopes'), findsNothing); + }); + + testWidgets('an empty answer shows "Carries no scopes"', (tester) async { + final entry = _entry(scopes: const []); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: ScopeLogCard(entry: entry, onTap: () {})), + )); + + expect(find.text('Carries no scopes'), findsOneWidget); + }); + + testWidgets('a no-response outcome shows its own words, no scope section', + (tester) async { + final entry = _entry(outcome: ScopeLogOutcome.noResponse, scopes: null); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: ScopeLogCard(entry: entry, onTap: () {})), + )); + + expect(find.text('No response from repeater'), findsOneWidget); + expect(find.text('Carries no scopes'), findsNothing); + }); + + testWidgets('tapping the card calls onTap', (tester) async { + var tapped = false; + final entry = _entry(); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: ScopeLogCard(entry: entry, onTap: () => tapped = true)), + )); + + await tester.tap(find.byType(ScopeLogCard)); + expect(tapped, isTrue); + }); + }); + + group('buildAllPingsCsv (the unfiltered "Copy CSV" export)', () { + test( + 'a scope row is byte-identical to the filtered/searched export\'s ' + 'UnifiedPingLogEntry.toCsv() row for the same entry', () { + final entry = _entry(scopes: const ['Ottawa', '*']); + final unifiedRow = _scopeUnified(entry).toCsv(); + + final csv = buildAllPingsCsv( + tx: const [], + rx: const [], + disc: const [], + trace: const [], + scopes: [entry], + ); + + expect(unifiedRow, startsWith('SCOPES,')); + expect(csv, contains(unifiedRow)); + }); + + test('omits the SCP section entirely when there are no scope entries', () { + final csv = buildAllPingsCsv( + tx: const [], + rx: const [], + disc: const [], + trace: const [], + scopes: const [], + ); + expect(csv, isNot(contains('SCP'))); + }); + + test('every scope row in a multi-entry export carries the SCOPES prefix', + () { + final ottawa = _entry(repeaterId: 'AB', scopes: const ['Ottawa']); + final noReply = _entry( + repeaterId: 'CD', + outcome: ScopeLogOutcome.noResponse, + timestamp: DateTime(2026, 9, 26, 9, 5)); + + final csv = buildAllPingsCsv( + tx: const [], + rx: const [], + disc: const [], + trace: const [], + scopes: [ottawa, noReply], + ); + + final rows = csv + .split('\n') + .where((line) => line.isNotEmpty && !line.startsWith('---')) + .skip(1) // the header row + .toList(); + expect(rows, hasLength(2)); + for (final row in rows) { + expect(row, startsWith('SCOPES,')); + } + }); + }); +} diff --git a/test/screens/log_screen_scrollbar_test.dart b/test/screens/log_screen_scrollbar_test.dart new file mode 100644 index 00000000..603e4146 --- /dev/null +++ b/test/screens/log_screen_scrollbar_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/log_entry.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; +import 'package:mesh_mapper/screens/log_screen.dart'; + +/// A long ping log had no scrollbar, so there was no telling how far down it +/// you were (#616). Phones draw none unless the list asks for one. The list +/// keeps its own scroll controller: on iOS and Android a list without one +/// inherits the screen's primary controller, and the two log tabs share one +/// TabBarView, so a Scrollbar on the inherited controller would see two lists. +/// Scope entries only, as in log_screen_scopes_test.dart: their cards need no +/// AppStateProvider to build. +void main() { + List entries(int count) => [ + for (var i = 0; i < count; i++) + () { + final entry = ScopeLogEntry( + timestamp: DateTime(2026, 9, 26, 9, 0, i), + latitude: 45.1, + longitude: -75.2, + repeaterId: 'AB', + pubkeyHex: 'AB' * 32, + outcome: ScopeLogOutcome.answered, + scopes: const ['Ottawa'], + ); + return UnifiedPingLogEntry( + type: PingLogType.scopes, + timestamp: entry.timestamp, + entry: entry); + }(), + ]; + + testWidgets('the ping list has a draggable scrollbar on phones', + (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: AllPingsTab( + allEntries: entries(60), + repeaters: const [], + txCount: 0, + rxCount: 0, + discCount: 0, + traceCount: 0, + scopeCount: 60, + ), + ), + )); + + final scrollbar = find.byType(Scrollbar); + expect(scrollbar, findsOneWidget); + final widget = tester.widget(scrollbar); + expect(widget.controller, isNotNull, + reason: 'its own controller, never the inherited primary one'); + expect(widget.interactive, isTrue); + + await tester.drag(find.byType(ListView), const Offset(0, -600)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(widget.controller!.offset, greaterThan(0)); + }, + variant: const TargetPlatformVariant( + {TargetPlatform.iOS, TargetPlatform.android})); +} diff --git a/test/screens/onboarding/onboarding_guide_screen_test.dart b/test/screens/onboarding/onboarding_guide_screen_test.dart index 54f6aa94..ba2192b0 100644 --- a/test/screens/onboarding/onboarding_guide_screen_test.dart +++ b/test/screens/onboarding/onboarding_guide_screen_test.dart @@ -9,6 +9,7 @@ import 'package:mesh_mapper/screens/onboarding/onboarding_guide_pages.dart'; import 'package:mesh_mapper/screens/onboarding/onboarding_guide_screen.dart'; import 'package:mesh_mapper/utils/ping_colors.dart'; import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; Widget host({TargetPlatform platform = TargetPlatform.android}) { return MaterialApp( @@ -33,6 +34,9 @@ Future openDetails(WidgetTester tester, String title) async { void main() { testWidgets('page 6 locks setup and swiping during completion', (tester) async { + // Location disclosure already agreed, so setup opens the background + // dialog straight away. + SharedPreferences.setMockInitialValues({'location_disclosure_shown': true}); final persistence = Completer(); final appState = _UnusedAppState(); addTearDown(appState.dispose); @@ -705,7 +709,7 @@ void main() { ); await goToPage(tester, 4); - expect(find.textContaining('External Antenna: Yes / No'), findsOneWidget); + expect(find.textContaining('Antenna: Internal / External'), findsOneWidget); await goToPage(tester, 9); expect(find.text('Legend & Info'), findsOneWidget); diff --git a/test/screens/settings/nickname_removal_batch_test.dart b/test/screens/settings/nickname_removal_batch_test.dart new file mode 100644 index 00000000..44bd3311 --- /dev/null +++ b/test/screens/settings/nickname_removal_batch_test.dart @@ -0,0 +1,33 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/screens/settings/repeater_nicknames_page.dart'; +import 'package:mesh_mapper/utils/repeater_nicknames.dart'; + +void main() { + final keyA = '5007${'A' * 60}'; + final keyB = '40E6${'B' * 60}'; + const mell = RepeaterNickname( + nickname: 'Mell', name: 'Mellionnec Repeater', hex: '5007'); + const goar = RepeaterNickname(nickname: 'Goar', name: 'Goariva', hex: '40E6'); + + test('one removal is named', () { + final batch = NicknameRemovalBatch()..add(keyA, mell); + expect(batch.message, 'Removed Mell'); + }); + + test('a second removal joins the first, and Undo gets both', () { + final batch = NicknameRemovalBatch() + ..add(keyA, mell) + ..add(keyB, goar); + expect(batch.message, 'Removed 2 nicknames'); + + final taken = batch.take(); + expect(taken, {keyA: mell, keyB: goar}); + expect(batch.take(), isEmpty, reason: 'take leaves the batch empty'); + }); + + test('clear ends the batch without restoring', () { + final batch = NicknameRemovalBatch()..add(keyA, mell); + batch.clear(); + expect(batch.take(), isEmpty); + }); +} diff --git a/test/screens/settings/repeater_nickname_list_test.dart b/test/screens/settings/repeater_nickname_list_test.dart new file mode 100644 index 00000000..a49f260e --- /dev/null +++ b/test/screens/settings/repeater_nickname_list_test.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/screens/settings/repeater_nicknames_page.dart'; +import 'package:mesh_mapper/utils/repeater_nicknames.dart'; + +final String _mellKey = '5007${'A' * 60}'; +final String _goarKey = '40E6${'B' * 60}'; + +const _mell = RepeaterNickname( + nickname: 'Mell', + name: 'Mellionnec Repeater', + hex: '5007', +); +const _goar = RepeaterNickname(nickname: 'Goar', name: '', hex: '40E6'); + +void main() { + final edits = <(String, RepeaterNickname)>[]; + final removals = <(String, RepeaterNickname)>[]; + var adds = 0; + + setUp(() { + edits.clear(); + removals.clear(); + adds = 0; + }); + + Widget host(List> entries) => MaterialApp( + home: Scaffold( + body: RepeaterNicknameList( + entries: entries, + onEdit: (key, entry) => edits.add((key, entry)), + onRemove: (key, entry) => removals.add((key, entry)), + onAdd: () => adds++, + ), + ), + ); + + testWidgets('the empty state explains and offers Add', (tester) async { + await tester.pumpWidget(host(const [])); + + expect( + find.text('Give repeaters your own short names, like Mell for 5007. ' + 'They show instead of the ID in Top Heard, and as the name on the ' + 'Live Activity, CarPlay, Apple Watch and Siri.'), + findsOneWidget, + ); + expect( + find.text('You can also tap a repeater on the map.'), findsOneWidget); + + await tester.tap(find.text('Add nickname')); + expect(adds, 1); + }); + + testWidgets('each entry shows its hex, nickname and server name', + (tester) async { + await tester.pumpWidget(host([MapEntry(_mellKey, _mell)])); + + expect(find.text('Nicknames'), findsOneWidget); + expect(find.text('5007'), findsOneWidget); + expect(find.text('Mell'), findsOneWidget); + expect(find.text('Mellionnec Repeater'), findsOneWidget); + expect(find.text('Add nickname'), findsNothing); + }); + + testWidgets('an entry with no server name has no subtitle', (tester) async { + await tester.pumpWidget(host([MapEntry(_goarKey, _goar)])); + + final tile = tester.widget(find.byType(ListTile)); + expect(tile.subtitle, isNull); + }); + + testWidgets('delete removes that entry by key', (tester) async { + await tester.pumpWidget(host([ + MapEntry(_mellKey, _mell), + MapEntry(_goarKey, _goar), + ])); + + await tester.tap(find.byTooltip('Remove').last); + + expect(removals, [(_goarKey, _goar)]); + expect(edits, isEmpty); + }); + + testWidgets('tapping an entry edits it', (tester) async { + await tester.pumpWidget(host([ + MapEntry(_mellKey, _mell), + MapEntry(_goarKey, _goar), + ])); + + await tester.tap(find.text('Mell')); + + expect(edits, [(_mellKey, _mell)]); + expect(removals, isEmpty); + }); +} diff --git a/test/services/android_altitude_channel_test.dart b/test/services/android_altitude_channel_test.dart new file mode 100644 index 00000000..bb10459d --- /dev/null +++ b/test/services/android_altitude_channel_test.dart @@ -0,0 +1,63 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/android_altitude_channel.dart'; + +/// The Dart side of the Android altitude channel: one method, no arguments, +/// and every failure answers null so the resolver stores unknown. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('meshmapper/altitude'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test('parses a fused answer', () async { + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'describeLastFix'); + expect(call.arguments, isNull); + return { + 'sdk': 34, + 'fixes': [ + { + 'source': 'fused', + 'timeMs': 1760000000000, + 'lat': 45.0, + 'lon': -75.0, + 'hasAltitude': true, + 'altitude': 120.0, + 'hasVerticalAccuracy': true, + 'verticalAccuracy': 8.0, + 'hasMsl': true, + 'msl': 84.0, + 'hasMslAccuracy': true, + 'mslAccuracy': 4.0, + 'isMock': false, + } + ], + }; + }); + final answer = await AndroidAltitudeChannel(channel: channel).describeLastFix(); + expect(answer!.sdk, 34); + expect(answer.fixes.single.msl, 84.0); + }); + + test('a platform exception answers null', () async { + messenger.setMockMethodCallHandler( + channel, (call) async => throw PlatformException(code: 'boom')); + expect(await AndroidAltitudeChannel(channel: channel).describeLastFix(), + isNull); + }); + + test('a missing plugin answers null', () async { + // No handler registered: the binding throws MissingPluginException. + expect(await AndroidAltitudeChannel(channel: channel).describeLastFix(), + isNull); + }); + + test('a non-map answer is null', () async { + messenger.setMockMethodCallHandler(channel, (call) async => 'nope'); + expect(await AndroidAltitudeChannel(channel: channel).describeLastFix(), + isNull); + }); +} diff --git a/test/services/api_queue_altitude_test.dart b/test/services/api_queue_altitude_test.dart new file mode 100644 index 00000000..8814a47d --- /dev/null +++ b/test/services/api_queue_altitude_test.dart @@ -0,0 +1,130 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// Every enqueue method passes the altitude trio through to the item it +/// builds. Offline mode is used because its rows are the item's own JSON, +/// held in memory with no Hive box to open. +void main() { + const ts = 1768762843; + final pubkey = 'ab' * 32; + + ApiQueueService queue() => + ApiQueueService(apiService: ApiService())..offlineMode = true; + + void expectTrio(Map row, String ref, int acc) { + expect(row['altitude'], 84); + expect(row['altitude_ref'], ref); + expect(row['altitude_acc'], acc); + } + + test('enqueueTx', () async { + final q = queue(); + await q.enqueueTx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: '4e(12.25)', + timestamp: ts, + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'msl', + altitudeAccuracy: 6.0, + ); + expectTrio(q.getOfflinePingsSnapshot().single, 'msl', 6); + }); + + test('enqueueRx', () async { + final q = queue(); + await q.enqueueRx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: '4e(12.0)', + timestamp: ts, + repeaterId: '4e', + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'ellipsoid', + altitudeAccuracy: 9.0, + ); + expectTrio(q.getOfflinePingsSnapshot().single, 'ellipsoid', 9); + }); + + test('enqueueDisc', () async { + final q = queue(); + await q.enqueueDisc( + latitude: 45.0, + longitude: -75.0, + repeaterId: '4e', + nodeType: 'repeater', + localSnr: 10.0, + localRssi: -90, + remoteSnr: 8.0, + pubkeyFull: pubkey, + timestamp: ts, + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'msl', + altitudeAccuracy: 3.0, + ); + expectTrio(q.getOfflinePingsSnapshot().single, 'msl', 3); + }); + + test('enqueueDiscDrop', () async { + final q = queue(); + await q.enqueueDiscDrop( + latitude: 45.0, + longitude: -75.0, + timestamp: ts, + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'msl', + altitudeAccuracy: 2.0, + ); + expectTrio(q.getOfflinePingsSnapshot().single, 'msl', 2); + }); + + test('enqueueTrace', () async { + final q = queue(); + await q.enqueueTrace( + latitude: 45.0, + longitude: -75.0, + repeaterId: '4e', + localSnr: 10.0, + localRssi: -90, + remoteSnr: 8.0, + timestamp: ts, + externalAntenna: false, + altitude: 84.0, + altitudeRef: 'ellipsoid', + altitudeAccuracy: 7.0, + ); + expectTrio(q.getOfflinePingsSnapshot().single, 'ellipsoid', 7); + }); + + test('an unlabelled altitude leaves no altitude on the row', () async { + final q = queue(); + await q.enqueueTx( + latitude: 45.0, + longitude: -75.0, + heardRepeats: 'None', + timestamp: ts, + externalAntenna: false, + altitude: 84.0, + ); + final row = q.getOfflinePingsSnapshot().single; + expect(row.containsKey('altitude'), isFalse); + expect(row.containsKey('altitude_ref'), isFalse); + }); + + test('altitudeLabelSummary counts labelled rows by type, skipping DEFER', () { + expect( + altitudeLabelSummary([ + {'type': 'TX', 'altitude_ref': 'msl'}, + {'type': 'TX'}, + {'type': 'RX', 'altitude_ref': 'ellipsoid'}, + {'type': 'DEFER'}, + ]), + 'altitude_ref 2/3 (TX 1/2, RX 1/1)'); + expect(altitudeLabelSummary(const []), 'altitude_ref 0/0'); + }); +} diff --git a/test/services/api_queue_offline_chunked_upload_test.dart b/test/services/api_queue_offline_chunked_upload_test.dart new file mode 100644 index 00000000..fe121dd4 --- /dev/null +++ b/test/services/api_queue_offline_chunked_upload_test.dart @@ -0,0 +1,261 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/offline_session_service.dart'; + +/// `runOfflineChunkedUpload` is the orchestration `app_state_provider.dart`'s +/// offline upload delegates to (review round 1, finding 5: no +/// `AppStateProvider` harness exists in this repo, so the piece that +/// actually carries the bug risk is extracted here and tested directly): +/// strip SCOPES rows the upload auth cannot accept, move every remaining +/// SCOPES row after every other row (DISC before SCOPES), persist that +/// final order BEFORE the first chunk is built, then upload fixed-size +/// chunks in order, stopping at the first one that does not succeed. +/// +/// Persisting before chunking is the point (finding 2): the caller's later +/// partial-upload cleanup removes a PREFIX of the STORED rows by uploaded +/// count, and that prefix only lines up with what was actually sent when +/// the file already holds the same order that was chunked. These tests +/// drive a REAL `OfflineSessionService` (SharedPreferences-backed) and +/// re-read it through a FRESH instance, so persistence is proven after a +/// reload, not merely against the instance that wrote it. +/// +/// Forwarding to the custom API is decided by `runOfflineChunkedUpload` +/// itself (its `forwardChunk` sink, which the provider wires to the custom +/// API forward), never by the test's upload callback, so a regression in +/// what production forwards shows up here. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + Map row(String type, int seq) => {'type': type, 'seq': seq}; + + /// Reads the stored session back through a FRESH service instance, so + /// what is checked is what reached SharedPreferences, not the calling + /// instance's memory. + Future> storedPings(String filename) async { + final reloaded = OfflineSessionService(); + await reloaded.init(); + return reloaded.getSession(filename)!.data['pings'] as List; + } + + test( + 'key absent: the stored file is already stripped and reordered when ' + 'the first chunk goes out, chunk 1 succeeds and chunk 2 fails, the ' + 'retained rows are exactly the unsent ones, and only chunk 1 is ' + 'forwarded, once', () async { + SharedPreferences.setMockInitialValues({}); + final service = OfflineSessionService(); + await service.init(); + + final stored = [ + row('SCOPES', 0), + row('RX', 1), + row('DISC', 2), + row('SCOPES', 3), + row('RX', 4), + row('RX', 5), + ]; + await service.updateCurrentSession(stored, deviceName: 'Test'); + final filename = service.sessions.single.filename; + + final forwarded = >>{}; + final forwardOrder = []; + final uploadCalls = []; + List? storedAtFirstChunk; + + final result = await runOfflineChunkedUpload( + stored, + scopeDiscoveryOffered: false, // the key was absent + batchSize: 2, + persistRows: (ordered) => service.replacePings(filename, ordered), + uploadChunk: (chunk, chunkNumber, totalChunks) async { + uploadCalls.add(chunkNumber); + if (chunkNumber == 1) { + // The moment the first chunk is sent, the stored file must + // already hold exactly the list being chunked. + storedAtFirstChunk = await storedPings(filename); + return true; + } + return false; // the second chunk fails + }, + forwardChunk: (chunk, chunkNumber) { + forwardOrder.add(chunkNumber); + forwarded[chunkNumber] = chunk; + }, + ); + + final expectedOrder = [row('RX', 1), row('DISC', 2), row('RX', 4), row('RX', 5)]; + expect(storedAtFirstChunk, expectedOrder, + reason: 'stripped before the first chunk was sent'); + expect(result.removedScopesCount, 2); + expect(result.orderedRows, expectedOrder); + + expect(uploadCalls, [1, 2]); + expect(result.uploadedCount, 2); + expect(forwardOrder, [1], reason: 'forwarded once, and only chunk 1'); + expect(forwarded[1], [row('RX', 1), row('DISC', 2)]); + + // What app_state_provider.dart does next: prune the uploaded prefix by + // count against the stored (already reordered) file. + await service.removeProcessedPings(filename, result.uploadedCount); + final retained = await storedPings(filename); + expect(retained, [row('RX', 4), row('RX', 5)], + reason: 'retained rows are exactly the ones not uploaded'); + + // Nothing retained was forwarded, and nothing forwarded is retained. + final forwardedRows = forwarded.values.expand((c) => c).toList(); + for (final r in retained) { + expect(forwardedRows, isNot(contains(r))); + } + }); + + test( + 'key present: SCOPES are kept but moved after every other row, and ' + 'the stored file already holds that order when the first chunk goes ' + 'out; a failing middle chunk stops the upload and nothing after it is ' + 'sent or forwarded', () async { + SharedPreferences.setMockInitialValues({}); + final service = OfflineSessionService(); + await service.init(); + + final stored = [ + row('SCOPES', 0), + row('DISC', 1), + row('RX', 2), + row('SCOPES', 3), + row('DISC', 4), + ]; + await service.updateCurrentSession(stored, deviceName: 'Test'); + final filename = service.sessions.single.filename; + + final forwardOrder = []; + final forwardedRows = >[]; + final uploadCalls = []; + List? storedAtFirstChunk; + + final result = await runOfflineChunkedUpload( + stored, + scopeDiscoveryOffered: true, // the key was present + batchSize: 2, + persistRows: (ordered) => service.replacePings(filename, ordered), + uploadChunk: (chunk, chunkNumber, totalChunks) async { + uploadCalls.add(chunkNumber); + if (chunkNumber == 1) { + storedAtFirstChunk = await storedPings(filename); + } + return chunkNumber == 1; + }, + forwardChunk: (chunk, chunkNumber) { + forwardOrder.add(chunkNumber); + forwardedRows.addAll(chunk); + }, + ); + + final expectedOrder = [ + row('DISC', 1), + row('RX', 2), + row('DISC', 4), + row('SCOPES', 0), + row('SCOPES', 3), + ]; + expect(result.removedScopesCount, 0); + expect(storedAtFirstChunk, expectedOrder); + expect(result.orderedRows, expectedOrder); + expect(uploadCalls, [1, 2], reason: 'chunk 3 is never attempted'); + expect(forwardOrder, [1]); + expect(forwardedRows, [row('DISC', 1), row('RX', 2)]); + + await service.removeProcessedPings(filename, result.uploadedCount); + expect(await storedPings(filename), + [row('DISC', 4), row('SCOPES', 0), row('SCOPES', 3)]); + }); + + test('every chunk succeeds: each is forwarded exactly once, in order', + () async { + final stored = [row('DISC', 0), row('SCOPES', 1), row('RX', 2)]; + final forwardOrder = []; + final forwardedRows = >[]; + + final result = await runOfflineChunkedUpload( + stored, + scopeDiscoveryOffered: true, + batchSize: 2, + persistRows: (ordered) async {}, + uploadChunk: (chunk, chunkNumber, totalChunks) async => true, + forwardChunk: (chunk, chunkNumber) { + forwardOrder.add(chunkNumber); + forwardedRows.addAll(chunk); + }, + ); + + expect(result.uploadedCount, 3); + expect(forwardOrder, [1, 2]); + expect(forwardedRows, [row('DISC', 0), row('RX', 2), row('SCOPES', 1)]); + }); + + test('no SCOPES rows at all: persistRows is never called (nothing to ' + 'strip or reorder, the stored order already matches)', () async { + var persistCalls = 0; + final stored = [row('TX', 0), row('RX', 1)]; + + final result = await runOfflineChunkedUpload( + stored, + scopeDiscoveryOffered: false, + batchSize: 50, + persistRows: (ordered) async => persistCalls++, + uploadChunk: (chunk, chunkNumber, totalChunks) async => true, + forwardChunk: (chunk, chunkNumber) {}, + ); + + expect(persistCalls, 0); + expect(result.orderedRows, stored); + expect(result.uploadedCount, 2); + expect(result.removedScopesCount, 0); + }); + + test('a stored row with a bare altitude loses it before upload and forward, ' + 'a labelled row keeps the trio', () async { + final uploaded = >[]; + final forwarded = >[]; + final result = await runOfflineChunkedUpload( + [ + {'type': 'TX', 'lat': 45.0, 'lon': -75.0, 'altitude': 84}, + { + 'type': 'RX', + 'lat': 45.0, + 'lon': -75.0, + 'altitude': 90, + 'altitude_ref': 'msl', + 'altitude_acc': 4, + }, + { + 'type': 'TX', + 'lat': 45.0, + 'lon': -75.0, + 'altitude': 91, + 'altitude_ref': 'bogus', + }, + ], + scopeDiscoveryOffered: true, + batchSize: 50, + persistRows: (_) async {}, + uploadChunk: (chunk, _, __) async { + uploaded.addAll(chunk); + return true; + }, + forwardChunk: (chunk, _) => forwarded.addAll(chunk), + ); + expect(result.uploadedCount, 3); + for (final rows in [uploaded, forwarded]) { + expect(rows[0].containsKey('altitude'), isFalse); + expect(rows[0].containsKey('altitude_ref'), isFalse); + expect(rows[1]['altitude'], 90); + expect(rows[1]['altitude_ref'], 'msl'); + expect(rows[1]['altitude_acc'], 4); + expect(rows[2].containsKey('altitude'), isFalse, + reason: 'an unknown reference word is as good as none'); + expect(rows[2].containsKey('altitude_ref'), isFalse); + } + }); +} diff --git a/test/services/api_queue_scope_replay_forward_test.dart b/test/services/api_queue_scope_replay_forward_test.dart new file mode 100644 index 00000000..da3fd208 --- /dev/null +++ b/test/services/api_queue_scope_replay_forward_test.dart @@ -0,0 +1,104 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/api_service.dart'; +import 'package:mesh_mapper/services/custom_api_service.dart'; + +/// The queue builds a batch with SCOPES while scope discovery is offered. +/// If a live auth withdraws it while the first POST is failing on a dead +/// keep-alive socket, the replay leaves the answers out, and so must the +/// forward to the third-party endpoint that follows a successful upload. +void main() { + const key = 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2'; + + test('a replay that dropped SCOPES does not forward them either', () async { + var offered = true; + var attempts = 0; + final posted = >[]; + late ApiService api; + Future auth() => api.requestAuth( + reason: 'connect', publicKey: 'AB' * 32, lat: 45.0, lon: -75.0); + api = ApiService(client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20260927-0001', + 'tx_allowed': true, + 'rx_allowed': true, + if (offered) 'scope_discovery': false, + }), + 200); + } + posted.add((json.decode(request.body) as Map)['data'] as List); + attempts++; + if (attempts == 1) { + offered = false; + await auth(); + throw http.ClientException( + 'Connection closed before full header was received', request.url); + } + return http.Response(json.encode({'success': true}), 200); + })); + await auth(); + + final forwarded = >[]; + final custom = CustomApiService( + prefsGetter: () => const UserPreferences( + customApiEnabled: true, + customApiUrl: 'https://example.invalid/ingest', + customApiKey: 'k'), + client: MockClient((request) async { + forwarded.add((json.decode(request.body) as Map)['data'] as List); + return http.Response('{}', 200); + }), + ); + final queue = ApiQueueService(apiService: api) + ..customApiService = custom; + queue.scopesAllowedGetter = () => api.scopeDiscoveryOffered; + final uploaded = <(int, List)>[]; + queue.onUploadSuccess = + (count, items) => uploaded.add((count, [for (final i in items) i.type])); + + await queue.enqueueDisc( + latitude: 45.0, + longitude: -75.0, + repeaterId: 'A3', + nodeType: 'REPEATER', + localSnr: 10.5, + localRssi: -88, + remoteSnr: 8.25, + pubkeyFull: key, + timestamp: 1757400000, + externalAntenna: false, + ); + await queue.enqueueScopes( + publicKeyHex: key, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: queue.generation, + ); + + await queue.flushQueue(); + for (var i = 0; i < 5; i++) { + await Future.delayed(Duration.zero); + } + + expect(posted.first.map((e) => e['type']).toSet(), {'DISC', 'SCOPES'}); + expect(posted.last.map((e) => e['type']), ['DISC']); + expect(forwarded, hasLength(1)); + expect(forwarded.single.map((e) => e['type']), ['DISC']); + expect(queue.queueSize, 0); + // Only what the replay actually sent counts as uploaded. + expect(uploaded, hasLength(1)); + expect(uploaded.single.$1, 1); + expect(uploaded.single.$2, ['DISC']); + api.dispose(); + }); +} diff --git a/test/services/api_queue_scopes_test.dart b/test/services/api_queue_scopes_test.dart new file mode 100644 index 00000000..f832e423 --- /dev/null +++ b/test/services/api_queue_scopes_test.dart @@ -0,0 +1,1100 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/models/api_queue_item.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// SCOPES is a repeater's answer to a direct scope discovery question, sent +/// only after a discovery found it. It is modelled on DEFER (the public key +/// rides in the heardRepeats slot, the scopes list gets its own field), but +/// unlike DEFER it depends on another queued item: the server refuses a +/// SCOPES whose DISC only arrives in a LATER batch or chunk, so the queue +/// must never upload one ahead of the DISC it depends on. +void main() { + ApiQueueService newQueue() => ApiQueueService(apiService: ApiService()); + + const key1 = 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2'; + const key2 = 'B4C3D2E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2C3'; + + Future enqueueDisc(ApiQueueService queue, + {String pubkeyFull = key1, int timestamp = 1757400000}) => + queue.enqueueDisc( + latitude: 45.0, + longitude: -75.0, + repeaterId: pubkeyFull.substring(0, 2), + nodeType: 'REPEATER', + localSnr: 10.5, + localRssi: -88, + remoteSnr: 8.25, + pubkeyFull: pubkeyFull, + timestamp: timestamp, + externalAntenna: false, + ); + + group('ApiQueueItem.fromScopes JSON shape', () { + test('carries public_key, scopes, timestamp, lat and lon', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1, + scopes: ['ROOM1', '*'], + lat: 45.26974, + lon: -75.77746, + timestamp: 1757400000, + ); + expect(item.toApiJson(), { + 'type': 'SCOPES', + 'public_key': key1, + 'scopes': ['ROOM1', '*'], + 'timestamp': 1757400000, + 'lat': 45.26974, + 'lon': -75.77746, + }); + }); + + test('an empty scopes list is kept as an empty array', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1, + scopes: const [], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ); + expect(item.toApiJson()['scopes'], []); + }); + + test('33 names, case and the * wildcard are kept exactly as given', () { + final names = [ + for (var i = 0; i < 32; i++) 'name$i', + '*', + ]; + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1, + scopes: names, + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ); + final scopes = item.toApiJson()['scopes'] as List; + expect(scopes, hasLength(33)); + expect(scopes.last, '*'); + expect(scopes, names, + reason: 'case and punctuation are passed through unchanged'); + }); + + test('radio_freq rides along when set, never auto_mode', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + radioFreq: '910.525,62.5,7,5', + ); + final json = item.toApiJson(); + expect(json['radio_freq'], '910.525,62.5,7,5'); + expect(json.containsKey('auto_mode'), isFalse); + }); + + test('timestamp is always an integer number of seconds', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ); + expect(item.toApiJson()['timestamp'], isA()); + expect(item.toApiJson()['timestamp'], 1757400000); + }); + + test('the public key is normalized to 64 upper-case hex', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: key1.toLowerCase(), + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ); + expect(item.toApiJson()['public_key'], key1); + }); + + test('a 0x prefix and surrounding whitespace are normalized away', () { + final item = ApiQueueItem.fromScopes( + publicKeyHex: ' 0x${key1.toLowerCase()} ', + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ); + expect(item.heardRepeats, key1); + expect(item.toApiJson()['public_key'], key1); + }); + + for (final bad in { + 'empty': '', + 'too short': key1.substring(0, 63), + 'too long': '${key1}A', + 'not hex': 'G${key1.substring(1)}', + 'inner whitespace': '${key1.substring(0, 32)} ${key1.substring(32)}', + 'a short id': 'A3B2C1', + }.entries) { + test('a malformed key (${bad.key}) throws ArgumentError', () { + expect( + () => ApiQueueItem.fromScopes( + publicKeyHex: bad.value, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + ), + throwsArgumentError, + ); + }); + } + }); + + group('enqueueScopes', () { + test('returns true and lands in the memory fallback with no init()', + () async { + final queue = newQueue(); + var updates = 0; + queue.onQueueUpdated = (_) => updates++; + + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.26974, + lon: -75.77746, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + + expect(ok, isTrue); + expect(queue.queueSize, 1); + expect(updates, 1); + final json = await queue.extractAllAsJson(); + expect(json.single['type'], 'SCOPES'); + expect(json.single['public_key'], key1); + }); + + test('false for non-finite lat/lon, nothing queued', () async { + final queue = newQueue(); + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: double.nan, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + expect(ok, isFalse); + expect(queue.queueSize, 0); + }); + + test('false on a generation mismatch, nothing queued', () async { + final queue = newQueue(); + final staleGeneration = queue.generation; + await queue.clearOnDisconnect(); // bumps generation + + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: staleGeneration, + ); + expect(ok, isFalse); + expect(queue.queueSize, 0); + }); + + test('false for an invalid public key, nothing queued: the server ' + 'rejects the whole item otherwise', () async { + final queue = newQueue(); + final ok = await queue.enqueueScopes( + publicKeyHex: 'not-a-key', + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + expect(ok, isFalse); + expect(queue.queueSize, 0); + }); + + test('a lower-case key is normalized and still accepted', () async { + final queue = newQueue(); + final ok = await queue.enqueueScopes( + publicKeyHex: key1.toLowerCase(), + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + expect(ok, isTrue); + final json = await queue.extractAllAsJson(); + expect(json.single['public_key'], key1); + }); + + test('an explicit radioFreq is used over the getter, and the getter is ' + 'the fallback when none is given', () async { + final queue = newQueue(); + queue.radioConfigGetter = () => '910.525,62.5,7,5'; + + await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + radioFreq: '906.875,250,10,5', + ); + await queue.enqueueScopes( + publicKeyHex: key2, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: queue.generation, + ); + + final json = await queue.extractAllAsJson(); + expect(json[0]['radio_freq'], '906.875,250,10,5', + reason: 'the explicit value Task 6 passes wins'); + expect(json[1]['radio_freq'], '910.525,62.5,7,5', + reason: 'no explicit value falls back to the live radio getter, ' + 'the same as every other item type'); + }); + + test('a disconnect racing the pending Hive write inserts nothing', + () async { + final dir = await Directory.systemTemp.createTemp('mm_scopes_'); + Hive.init(dir.path); + try { + final queue = newQueue(); + await queue.init(); + final gen = queue.generation; + + // Started but not yet awaited: this runs synchronously up to its + // internal `await box.add(item)` and then suspends. + final enqueueFuture = queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: gen, + ); + + // clearOnDisconnect() bumps the generation synchronously, before its + // own first internal await, so this is guaranteed to happen before + // the pending write above is checked against it. + await queue.clearOnDisconnect(); + + final result = await enqueueFuture; + expect(result, isFalse); + expect(queue.queueSize, 0); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + + test('a normal Hive write succeeds and is not a memory fallback', + () async { + final dir = await Directory.systemTemp.createTemp('mm_scopes_'); + Hive.init(dir.path); + try { + final queue = newQueue(); + await queue.init(); + + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + + expect(ok, isTrue); + expect(queue.queueSize, 1); + // Prove it is really in Hive, not the memory fallback: reopen the + // box directly (the service's own box is still the open instance, + // so this reads it, not a different one). + final reopened = await Hive.openBox('api_queue'); + expect(reopened.length, 1); + expect(reopened.getAt(0)!.type, 'SCOPES'); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + + test( + 'a failed Hive write recovers (deletes and reopens the box), and ' + 'the SCOPES retry is refused because recovery wiped the queue', + () async { + final dir = await Directory.systemTemp.createTemp('mm_scopes_'); + Hive.init(dir.path); + try { + final queue = newQueue(); + await queue.init(); + + // Close the box out from under the service without clearing its + // `_box` reference (queue.testBox stays pointed at the now-closed + // instance): the next write on it throws exactly like a corrupted + // box would in production, which is what drives `_recoverBox()`. + await queue.testBox!.close(); + + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + + // Recovery deleted the box from disk, which is a new queue + // generation: the answer may depend on a DISC that went with it. + expect(ok, isFalse); + expect(queue.queueSize, 0); + // The recovered box is fresh and open, and nothing landed in it. + expect(queue.testBox!.isOpen, isTrue); + final reopened = await Hive.openBox('api_queue'); + expect(reopened.length, 0); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + + test( + 'Hive unavailable (the box could not be reached at all) falls back ' + 'to memory', () async { + final queue = newQueue(); + // No init(): `_box` is null from the start, the same end state a + // write-then-recovery failure reaches (both leave `_box` null before + // the write attempt below), so both take the identical fallback + // line. Explicitly nulling `testBox` here isolates that shared + // fallback from the recovery machinery covered by the test above. + queue.testBox = null; + + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + + expect(ok, isTrue); + expect(queue.queueSize, 1); + final json = await queue.extractAllAsJson(); + expect(json.single['type'], 'SCOPES'); + }); + + // A disconnect that lands while the FIRST Hive write is failing (or + // while its recovery runs) must not let the recovery retry, the retry + // itself, or the memory fallback put the answer back into a cleared + // queue. Each of these fails if the generation check guarding its step + // is removed from enqueueScopes. + group('a disconnect while the first Hive write is failing', () { + late Directory dir; + late Box recoveredInner; + + setUp(() async { + dir = await Directory.systemTemp.createTemp('mm_scopes_race_'); + Hive.init(dir.path); + // No init() here (it would open the real queue box), so register + // the adapter it would have, or a real write could never land. + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(ApiQueueItemAdapter()); + } + recoveredInner = await Hive.openBox('scopes_recovered'); + }); + + tearDown(() async { + await Hive.close(); + await dir.delete(recursive: true); + }); + + Future enqueue(ApiQueueService queue, int gen) => + queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: gen, + ); + + for (final clearWhile in ['the write is failing', 'recovery runs']) { + test( + 'recovery: cleared while $clearWhile, the recovered box is never ' + 'written to and nothing is inserted', () async { + final queue = newQueue(); + final gen = queue.generation; + Future? clearing; + final failing = _ScriptedBox(null) + ..failAdd = true + ..beforeAdd = clearWhile == 'the write is failing' + ? () async { + clearing = queue.clearOnDisconnect(); + } + : null; + if (clearWhile == 'recovery runs') { + // Fires inside _recoverBox, after the corrupt box is deleted and + // before the fresh one is opened. + queue.onStorageCleanup = (_) { + clearing = queue.clearOnDisconnect(); + }; + } + final recovered = _ScriptedBox(recoveredInner); + queue.testBox = failing; + queue.reopenBoxForRecovery = () async => recovered; + + final ok = await enqueue(queue, gen); + await clearing; + + expect(ok, isFalse); + expect(failing.addCalls, 1); + expect(recovered.addCalls, 0, + reason: 'the retry must not be attempted after the clear'); + expect(recoveredInner.length, 0); + expect(queue.heldItems, isEmpty); + }); + } + + // A clear racing the recovered retry, or the memory fallback after + // it, can no longer be reached from here: recovery is itself a new + // generation, so enqueueScopes refuses before the retry runs. The + // checks stay in place as a guard should that ever change. + + // Recovery deletes the queue box from disk, which erases every item + // in it just as a clear does. A SCOPES whose DISC was in that box + // must not land after it: selection would read the missing DISC as + // already delivered and upload an answer the server refuses, while + // the runner stamps its cache and stops asking for the whole window. + test( + 'recovery: a DISC queued in the box that recovery wipes refuses its ' + 'SCOPES retry, and nothing is inserted', () async { + final queue = newQueue(); + final discInner = await Hive.openBox('scopes_failing'); + final failing = _ScriptedBox(discInner); + final recovered = _ScriptedBox(recoveredInner); + queue.testBox = failing; + queue.reopenBoxForRecovery = () async => recovered; + + await enqueueDisc(queue); + expect(discInner.values.single.type, 'DISC'); + final gen = queue.generation; + failing.failAdd = true; + + final ok = await enqueue(queue, gen); + + expect(ok, isFalse, + reason: 'enqueue false is what keeps the runner from stamping'); + expect(queue.generation, isNot(gen)); + expect(recovered.addCalls, 0, + reason: 'the retry must not run against the wiped queue'); + expect(recoveredInner.length, 0); + expect(queue.heldItems, isEmpty); + }); + + // The bump must land before recovery's first await. A second SCOPES + // enqueue that fails while the first one's recovery is still closing + // the box skips recovery (one runs at a time) and would otherwise + // retry against the closed box and fall back to memory under the old + // generation, just before recovery erased its DISC. + test( + 'two concurrent enqueues: the second fails while the first ' + "one's recovery is closing the box, and both refuse", () async { + final queue = newQueue(); + final discInner = await Hive.openBox('scopes_failing'); + final closing = Completer(); + final closeStarted = Completer(); + final failing = _ScriptedBox(discInner) + ..onClose = () async { + closeStarted.complete(); + await closing.future; + }; + final recovered = _ScriptedBox(recoveredInner); + queue.testBox = failing; + queue.reopenBoxForRecovery = () async => recovered; + + await enqueueDisc(queue); + final gen = queue.generation; + failing.failAdd = true; + + final first = enqueue(queue, gen); + await closeStarted.future; + expect(queue.generation, isNot(gen), + reason: 'bumped before recovery waits on the close'); + final second = await enqueue(queue, gen); + closing.complete(); + + expect(second, isFalse); + expect(await first, isFalse); + expect(recovered.addCalls, 0); + expect(recoveredInner.length, 0); + expect(queue.heldItems, isEmpty, + reason: 'nothing in memory: neither answer may be stamped'); + }); + + test('with no clear, a recovery on its own still refuses the retry: ' + 'the box it wiped was the queue', () async { + final queue = newQueue(); + final failing = _ScriptedBox(null)..failAdd = true; + final recovered = _ScriptedBox(recoveredInner); + queue.testBox = failing; + queue.reopenBoxForRecovery = () async => recovered; + + final ok = await enqueue(queue, queue.generation); + + expect(ok, isFalse); + expect(recovered.addCalls, 0); + expect(recoveredInner.length, 0); + expect(queue.heldItems, isEmpty); + }); + + }); + + group('offline mode', () { + ApiQueueService offlineQueue() => newQueue()..offlineMode = true; + + test('lands in the offline payload', () async { + final queue = offlineQueue(); + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + expect(ok, isTrue); + expect(queue.offlinePingCount, 1); + expect(queue.queueSize, 0); + }); + + test('the airborne pause drops it like any other offline row', + () async { + final queue = offlineQueue(); + queue.setOfflineRecordingPaused(true); + final ok = await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + expect(ok, isFalse); + expect(queue.offlinePingCount, 0); + }); + }); + }); + + test('extractAllAsJson keeps SCOPES untagged', () async { + final queue = newQueue(); + await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400000, + expectedGeneration: queue.generation, + ); + final json = await queue.extractAllAsJson(); + expect(json.single['type'], 'SCOPES'); + expect(json.single.containsKey('wire_tag'), isFalse); + }); + + test('withoutScopesItems leaves every other type in order', () { + final rows = [ + {'type': 'TX'}, + {'type': 'SCOPES'}, + {'type': 'RX'}, + {'type': 'SCOPES'}, + {'type': 'DISC'}, + {'type': 'DEFER'}, + ]; + expect(withoutScopesItems(rows).map((r) => r['type']), + ['TX', 'RX', 'DISC', 'DEFER']); + }); + + test('orderDiscBeforeScopes is a stable partition, storage order does not ' + 'matter (an export that stored a SCOPES in Hive ahead of a memory ' + 'DISC must still put the DISC first)', () { + final rows = [ + {'type': 'SCOPES', 'public_key': key1}, + {'type': 'RX'}, + {'type': 'DISC', 'repeater_id': 'a3'}, + {'type': 'SCOPES', 'public_key': key2}, + ]; + expect(orderDiscBeforeScopes(rows).map((r) => r['type']), + ['RX', 'DISC', 'SCOPES', 'SCOPES']); + }); + + test( + 'extractAllAsJson puts DISC before SCOPES even when SCOPES was queued ' + 'first (proves the reorder, not just insertion order)', () async { + final queue = newQueue(); + // Enqueued in the "wrong" order: without the reorder this would come + // back SCOPES-then-DISC, and a chunk boundary right after the SCOPES row + // would upload it a whole chunk ahead of the DISC it depends on. + await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: queue.generation, + ); + await enqueueDisc(queue, pubkeyFull: key1, timestamp: 1757400000); + + final json = await queue.extractAllAsJson(); + expect(json.map((j) => j['type']), ['DISC', 'SCOPES']); + }); + + group('selectBatchWithScopesDependency', () { + ApiQueueItem disc(String key, {int retryCount = 0}) => ApiQueueItem( + type: 'DISC', + latitude: 45.0, + longitude: -75.0, + timestamp: DateTime.fromMillisecondsSinceEpoch(1757400000000), + heardRepeats: 'a3:REPEATER:10.50:-88:8.25:$key', + canUploadAfter: 0, + externalAntenna: false, + retryCount: retryCount, + ); + + ApiQueueItem scopes(String key) => ApiQueueItem( + type: 'SCOPES', + latitude: 45.0, + longitude: -75.0, + timestamp: DateTime.fromMillisecondsSinceEpoch(1757400000000), + heardRepeats: key, + canUploadAfter: 0, + externalAntenna: false, + scopes: const ['*'], + ); + + ApiQueueItem rx() => ApiQueueItem( + type: 'RX', + latitude: 45.0, + longitude: -75.0, + timestamp: DateTime.fromMillisecondsSinceEpoch(1757400000000), + heardRepeats: '4e(12.0)', + canUploadAfter: 0, + externalAntenna: false, + ); + + test('a SCOPES rides along when its DISC is in the same batch', () { + final d = disc(key1); + final s = scopes(key1); + final selected = selectBatchWithScopesDependency( + eligible: [d, s], + allQueued: [d, s], + batchSize: 50, + ); + expect(selected, [d, s]); + }); + + test('a SCOPES is released when no DISC for its key remains anywhere ' + '(its DISC already went out in an earlier batch)', () { + final s = scopes(key1); + final selected = selectBatchWithScopesDependency( + eligible: [s], + allQueued: [s], // the matching DISC is gone from the queue entirely + batchSize: 50, + ); + expect(selected, [s]); + }); + + test('a DISC in retry backoff holds back its SCOPES', () { + // The SCOPES' own DISC (key1) is only reachable through allQueued, + // still climbing the retry ladder (not eligible for this batch). An + // unrelated, eligible DISC (key2) fills the batch instead. + final backedOffTwin = disc(key1, retryCount: 1); + final s = scopes(key1); + final otherDisc = disc(key2); + final selected = selectBatchWithScopesDependency( + eligible: [otherDisc, s], + allQueued: [otherDisc, s, backedOffTwin], + batchSize: 50, + ); + expect(selected, [otherDisc], + reason: 'the SCOPES cannot go out: its DISC is still queued ' + '(in backoff) and is not in this batch'); + }); + + test('a run of 50 blocked SCOPES never crowds out the DISC items behind ' + 'them', () { + final blockedScopes = + List.generate(50, (i) => scopes('C' * 63 + i.toString())); + final theirDiscs = + blockedScopes.map((s) => disc(s.heardRepeats, retryCount: 1)).toList(); + final laterDisc = disc(key2); + final eligible = [...blockedScopes, laterDisc]; + final allQueued = [...blockedScopes, ...theirDiscs, laterDisc]; + + final selected = selectBatchWithScopesDependency( + eligible: eligible, + allQueued: allQueued, + batchSize: 50, + ); + + expect(selected, [laterDisc], + reason: 'every blocked SCOPES is held back, so the DISC behind ' + 'them still fills the batch instead of losing its slot'); + }); + + test('storage origin does not matter to the rule: a mix of items that ' + 'would come from Hive and from the memory fallback is treated the ' + 'same', () { + final hiveStyleDisc = disc(key1); + final memoryStyleScopes = scopes(key1); + final selected = selectBatchWithScopesDependency( + eligible: [hiveStyleDisc, memoryStyleScopes], + allQueued: [hiveStyleDisc, memoryStyleScopes], + batchSize: 50, + ); + expect(selected, [hiveStyleDisc, memoryStyleScopes]); + }); + + test('DISC and other non-SCOPES items are always selected regardless of ' + 'any SCOPES dependency', () { + final d = disc(key1); + final r = rx(); + final selected = selectBatchWithScopesDependency( + eligible: [d, r], + allQueued: [d, r], + batchSize: 50, + ); + expect(selected, [d, r]); + }); + }); + + group('the batch builder and the scope discovery upload door', () { + Future<({ApiQueueService queue, List>> posted})> + build({ + required List outcomes, + }) async { + final posted = >>[]; + var call = 0; + final api = ApiService(client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20260926-0001', + 'tx_allowed': true, + 'rx_allowed': true, + }), + 200, + ); + } + final body = json.decode(request.body) as Map; + final data = (body['data'] as List).cast>(); + posted.add(data); + final outcome = outcomes[call.clamp(0, outcomes.length - 1)]; + call++; + if (outcome == UploadOutcome.retryable) { + return http.Response(json.encode({'success': false}), 200); + } + return http.Response(json.encode({'success': true}), 200); + })); + await api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.0, + lon: -75.0, + accuracyMeters: 5, + ); + final queue = ApiQueueService(apiService: api); + return (queue: queue, posted: posted); + } + + test('drops SCOPES when the key is absent, keeps DISC either way', + () async { + final t = await build(outcomes: [UploadOutcome.success]); + t.queue.scopesAllowedGetter = () => false; + await enqueueDisc(t.queue, pubkeyFull: key1); + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + + await t.queue.flushQueue(); + + expect(t.posted.single.map((p) => p['type']), ['DISC']); + expect(t.queue.queueSize, 0); + }); + + test('keeps SCOPES when the key is present and false (not enforced)', + () async { + final t = await build(outcomes: [UploadOutcome.success]); + t.queue.scopesAllowedGetter = () => true; + await enqueueDisc(t.queue, pubkeyFull: key1); + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + + await t.queue.flushQueue(); + + expect(t.posted.single.map((p) => p['type']).toSet(), {'DISC', 'SCOPES'}); + }); + + test('a batch that fails and retries re-sends its SCOPES with its DISC, ' + 'nothing duplicated', () async { + final t = await build(outcomes: [UploadOutcome.retryable, UploadOutcome.success]); + t.queue.scopesAllowedGetter = () => true; + await enqueueDisc(t.queue, pubkeyFull: key1); + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + + await t.queue.flushQueue(); // fails, both items marked for retry + // Reset the backoff so the second attempt is immediately eligible. + for (final item in t.queue.heldItems) { + item.retryCount = 0; + item.lastRetryAt = null; + } + await t.queue.flushQueue(); // succeeds + + expect(t.posted, hasLength(2)); + expect(t.posted[0].map((p) => p['type']).toSet(), {'DISC', 'SCOPES'}); + expect(t.posted[1].map((p) => p['type']).toSet(), {'DISC', 'SCOPES'}); + expect(t.queue.queueSize, 0); + }); + + test('an item dropped at the upload door is never forwarded', () async { + // CustomApiService.forwardPings is called with the exact `pings` list + // that goes to MeshMapper (`api_queue_service.dart`'s + // `customApiService?.forwardPings(pings)`), so proving a dropped + // SCOPES never reaches that list (asserted on `posted`, the actual + // MeshMapper upload body) proves it is never forwarded either. + final t = await build(outcomes: [UploadOutcome.success]); + t.queue.scopesAllowedGetter = () => false; + await enqueueDisc(t.queue, pubkeyFull: key1); + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + + await t.queue.flushQueue(); + + expect(t.posted.single.any((p) => p['type'] == 'SCOPES'), isFalse); + }); + + test( + 'a SCOPES item that survives the drop attempt is still excluded ' + 'from the batch and never forwarded: exclusion cannot depend on ' + 'the drop having succeeded', () async { + final t = await build(outcomes: [UploadOutcome.success]); + await enqueueDisc(t.queue, pubkeyFull: key1); + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + + // The drop pass (`_dropDisallowedScopesItems`, the FIRST call) sees + // the feature as allowed and removes nothing, standing in for a Hive + // deletion that was attempted and failed (logged, otherwise + // harmless): either way, the SCOPES item is still sitting in storage + // when selection runs. Every LATER call (the batch-selection filter) + // sees it as disallowed, so the exclusion there must not depend on + // the drop pass having actually removed anything. + var calls = 0; + t.queue.scopesAllowedGetter = () { + calls++; + return calls > 1 ? false : true; + }; + + await t.queue.flushQueue(); + + expect(calls, greaterThan(1)); + expect(t.posted.single.map((p) => p['type']), ['DISC']); + }); + + test('overlapping flushes upload the queued items only once', () async { + final t = await build(outcomes: [UploadOutcome.success]); + await enqueueDisc(t.queue, pubkeyFull: key1); + + // Neither is awaited before the other starts: both calls run + // synchronously up to their own first internal await, exactly the + // window the batch timer and the ping flush timer can both land in. + final first = t.queue.flushQueue(); + final second = t.queue.flushQueue(); + await Future.wait([first, second]); + + expect(t.posted, hasLength(1), + reason: 'the guard must already be claimed by the time the ' + 'second flush checks it, or the same DISC item is selected, ' + 'uploaded and forwarded twice'); + expect(t.posted.single, hasLength(1)); + }); + + test( + 'a real mix of one Hive item and one memory-fallback item uploads ' + 'DISC before SCOPES through the queue itself', () async { + final dir = await Directory.systemTemp.createTemp('mm_scopes_mixed_'); + Hive.init(dir.path); + try { + final t = await build(outcomes: [UploadOutcome.success]); + await t.queue.init(); // now Hive-backed, same temp dir + t.queue.scopesAllowedGetter = () => true; + + await enqueueDisc(t.queue, pubkeyFull: key1); // real Hive write + + // Force exactly the next write to memory without touching the + // already-committed Hive item: nulling `_box` (not closing or + // deleting it) skips straight to the memory-fallback branch. + final realBox = t.queue.testBox; + t.queue.testBox = null; + await t.queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: t.queue.generation, + ); + t.queue.testBox = realBox; + + // Both items are now genuinely visible: the DISC via the real + // (still open) Hive box, the SCOPES via the memory queue. + expect(t.queue.heldItems.map((i) => i.type).toSet(), {'DISC', 'SCOPES'}); + expect(t.queue.heldItems.where((i) => i.isInBox).single.type, 'DISC'); + expect(t.queue.heldItems.where((i) => !i.isInBox).single.type, 'SCOPES'); + + await t.queue.flushQueue(); + + expect(t.posted.single.map((p) => p['type']).toSet(), {'DISC', 'SCOPES'}); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + + test( + 'a real mix of one Hive item and one memory-fallback item exports ' + 'DISC before SCOPES through the queue itself', () async { + final dir = await Directory.systemTemp.createTemp('mm_scopes_mixed2_'); + Hive.init(dir.path); + try { + final queue = newQueue(); + await queue.init(); + + // Enqueue the SCOPES row FIRST but keep it in Hive too (both + // items real Hive rows initially), forcing the second one (DISC) + // to memory instead, so raw storage order alone (Hive-then-memory + // concatenation) would put SCOPES first without the reorder. + await queue.enqueueScopes( + publicKeyHex: key1, + scopes: ['*'], + lat: 45.0, + lon: -75.0, + timestamp: 1757400001, + expectedGeneration: queue.generation, + ); + + final realBox = queue.testBox; + queue.testBox = null; + await enqueueDisc(queue, pubkeyFull: key1, timestamp: 1757400000); + queue.testBox = realBox; + + expect(queue.heldItems.where((i) => i.isInBox).single.type, 'SCOPES'); + expect(queue.heldItems.where((i) => !i.isInBox).single.type, 'DISC'); + + final json = await queue.extractAllAsJson(); + expect(json.map((j) => j['type']), ['DISC', 'SCOPES']); + } finally { + await Hive.close(); + await dir.delete(recursive: true); + } + }); + }); +} + +enum UploadOutcome { success, retryable } + +/// A queue box whose writes a test can script. With no [inner] box it holds +/// nothing (the corrupt box a failing write came from); with one, it +/// forwards to that real box so a write that lands really lands. +class _ScriptedBox implements Box { + _ScriptedBox(this.inner); + + final Box? inner; + + /// Throw on every add, the way a corrupt box does. + bool failAdd = false; + + /// Runs (and is awaited) inside every add, before it fails or lands. + Future Function()? beforeAdd; + + int addCalls = 0; + + @override + Future add(ApiQueueItem value) async { + addCalls++; + await beforeAdd?.call(); + if (failAdd) throw HiveError('scripted write failure'); + return inner!.add(value); + } + + @override + Future clear() async => await inner?.clear() ?? 0; + + /// Runs (and is awaited) inside close, before it returns. + Future Function()? onClose; + + @override + Future close() async => await onClose?.call(); + + @override + int get length => inner?.length ?? 0; + + @override + Iterable get values => inner?.values ?? const []; + + @override + bool get isOpen => true; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/test/services/api_queue_upload_pause_test.dart b/test/services/api_queue_upload_pause_test.dart new file mode 100644 index 00000000..88c76010 --- /dev/null +++ b/test/services/api_queue_upload_pause_test.dart @@ -0,0 +1,213 @@ +import 'dart:convert'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/api_service.dart'; +import 'package:mesh_mapper/services/network_state_service.dart'; + +import 'test_network_state_source.dart'; + +/// A group handoff releases the old session while the radio stays up, so the +/// queue's own timers must not start a batch under that session in the +/// meantime (the server answers a batch that lands after the close with +/// bad_session, which ends the connection), and an upload already on the +/// wire must be answered before the release goes out. +void main() { + ({ + ApiQueueService queue, + ApiService api, + TestNetworkStateSource network, + List uploads, + }) build({Duration uploadDelay = Duration.zero}) { + final network = TestNetworkStateSource(NetworkState.unconstrained); + final uploads = []; + final api = ApiService( + networkState: network, + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20260912-0001', + 'tx_allowed': true, + 'rx_allowed': true, + }), + 200, + ); + } + if (uploadDelay > Duration.zero) { + await Future.delayed(uploadDelay); + } + uploads.add(DateTime.now()); + return http.Response(json.encode({'success': true}), 200); + }), + ); + final queue = ApiQueueService(apiService: api, networkState: network); + return (queue: queue, api: api, network: network, uploads: uploads); + } + + void connect(FakeAsync async, ApiService api, ApiQueueService queue) { + api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.27, + lon: -75.78, + ); + // Starts the periodic batch timer, as the real connect does. + queue.clearBeforeConnect(); + async.flushMicrotasks(); + } + + void enqueueTx(FakeAsync async, ApiQueueService queue) { + queue.enqueueTx( + latitude: 45.27, + longitude: -75.78, + heardRepeats: '4e(12.25)', + timestamp: 1789200000, + externalAntenna: false, + ); + async.flushMicrotasks(); + } + + void dispose( + ({ + ApiQueueService queue, + ApiService api, + TestNetworkStateSource network, + List uploads, + }) built) { + built.queue.dispose(); + built.api.dispose(); + built.network.close(); + } + + test('a pause holds the ping flush and the batch timer until the resume', + () { + fakeAsync((async) { + final built = build(); + connect(async, built.api, built.queue); + enqueueTx(async, built.queue); + + built.queue.pauseScheduledUploads(); + expect(built.queue.scheduledUploadsPaused, isTrue); + async.elapse(const Duration(seconds: 40)); + expect(built.uploads, isEmpty, + reason: 'neither the 5 s ping flush nor the 15 s batch timer ' + 'may fire while paused'); + + built.queue.resumeScheduledUploads(); + expect(built.queue.scheduledUploadsPaused, isFalse); + async.elapse(const Duration(seconds: 5)); + expect(built.uploads, hasLength(1), + reason: 'the resume schedules the flush the pause interrupted'); + + dispose(built); + }); + }); + + test('an enqueue during the pause is flushed once resumed', () { + fakeAsync((async) { + final built = build(); + connect(async, built.api, built.queue); + + built.queue.pauseScheduledUploads(); + enqueueTx(async, built.queue); + async.elapse(const Duration(seconds: 40)); + expect(built.uploads, isEmpty); + + built.queue.resumeScheduledUploads(); + async.elapse(const Duration(seconds: 5)); + expect(built.uploads, hasLength(1)); + + dispose(built); + }); + }); + + test('an explicit upload still runs while paused', () { + fakeAsync((async) { + final built = build(); + connect(async, built.api, built.queue); + + built.queue.pauseScheduledUploads(); + enqueueTx(async, built.queue); + built.queue.forceUploadWithHoldWait(); + async.flushMicrotasks(); + expect(built.uploads, hasLength(1), + reason: 'the handoff drains the queue while holding the pause'); + + dispose(built); + }); + }); + + test('a disconnect during the pause drops it, so the resume restarts nothing', + () { + fakeAsync((async) { + final built = build(); + connect(async, built.api, built.queue); + + built.queue.pauseScheduledUploads(); + built.queue.clearOnDisconnect(); + async.flushMicrotasks(); + expect(built.queue.scheduledUploadsPaused, isFalse); + + built.queue.resumeScheduledUploads(); + async.elapse(const Duration(seconds: 60)); + expect(built.uploads, isEmpty); + + dispose(built); + }); + }); + + test('a repeated pause or resume is a no-op', () { + fakeAsync((async) { + final built = build(); + built.queue.resumeScheduledUploads(); + expect(built.queue.scheduledUploadsPaused, isFalse); + built.queue.pauseScheduledUploads(); + built.queue.pauseScheduledUploads(); + expect(built.queue.scheduledUploadsPaused, isTrue); + built.queue.resumeScheduledUploads(); + built.queue.resumeScheduledUploads(); + expect(built.queue.scheduledUploadsPaused, isFalse); + dispose(built); + }); + }); + + test('waiting for an upload answers at once when idle, waits for one on ' + 'the wire, and gives up at its bound', () { + fakeAsync((async) { + final built = build(uploadDelay: const Duration(seconds: 3)); + connect(async, built.api, built.queue); + + bool? idle; + built.queue.waitForUploadToFinish().then((v) => idle = v); + async.flushMicrotasks(); + expect(idle, isTrue, reason: 'nothing in flight'); + + enqueueTx(async, built.queue); + built.queue.forceUploadWithHoldWait(); + async.flushMicrotasks(); + expect(built.queue.isUploading, isTrue); + + bool? bounded; + built.queue + .waitForUploadToFinish(limit: const Duration(seconds: 1)) + .then((v) => bounded = v); + async.elapse(const Duration(seconds: 1)); + expect(bounded, isFalse, reason: 'still on the wire at the bound'); + expect(built.queue.isUploading, isTrue); + + bool? finished; + built.queue.waitForUploadToFinish().then((v) => finished = v); + async.elapse(const Duration(seconds: 2)); + expect(finished, isTrue, reason: 'the upload landed inside the bound'); + expect(built.queue.isUploading, isFalse); + expect(built.uploads, hasLength(1)); + + dispose(built); + }); + }); +} diff --git a/test/services/api_service_border_test.dart b/test/services/api_service_border_test.dart new file mode 100644 index 00000000..98b20fc1 --- /dev/null +++ b/test/services/api_service_border_test.dart @@ -0,0 +1,211 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/io_client.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// Sends every request to a local server instead of meshmapper.net, keeping +/// the abort trigger so the real IOClient abort path runs. +class _LocalClient extends http.BaseClient { + final Uri base; + final IOClient inner = IOClient(HttpClient()); + int sent = 0; + + _LocalClient(this.base); + + @override + Future send(http.BaseRequest request) async { + sent++; + final trigger = request is http.Abortable ? request.abortTrigger : null; + final local = http.AbortableRequest( + request.method, base.replace(path: request.url.path), + abortTrigger: trigger) + ..headers.addAll(request.headers) + ..bodyBytes = request is http.Request ? request.bodyBytes : const []; + return inner.send(local); + } + + @override + void close() => inner.close(); +} + +void main() { + HttpServer? server; + late _LocalClient client; + + tearDown(() async { + client.close(); + await server?.close(force: true); + }); + + test('a slow /border body is aborted at the timeout, not left downloading', + () async { + // A raw socket, because HttpServer does not report the client hanging up. + final hungUp = Completer(); + final raw = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + var connections = 0; + raw.listen((socket) async { + if (++connections > 1) { + // The follow-up request: a small, complete answer. + final body = json.encode({ + 'success': true, + 'polygons': [ + { + 'code': 'AKL', + 'polygon': [ + [1, 2], + [3, 4], + ], + }, + ], + }); + socket.listen((_) {}, onError: (_) {}); + socket.write('HTTP/1.1 200 OK\r\n' + 'Content-Type: application/json\r\n' + 'Content-Length: ${body.length}\r\n\r\n$body'); + await socket.flush(); + await socket.close(); + return; + } + socket.listen((_) {}, onDone: () { + if (!hungUp.isCompleted) hungUp.complete(); + }, onError: (_) { + if (!hungUp.isCompleted) hungUp.complete(); + }); + // Headers for a 4.8 MB body, then a dribble of it, like a group border + // over a slow mobile link. + socket.write('HTTP/1.1 200 OK\r\n' + 'Content-Type: application/json\r\n' + 'Content-Length: 4800000\r\n\r\n{"polygons":['); + try { + while (!hungUp.isCompleted) { + socket.write('{"code":"AKL","polygon":[[1,2],[3,4]]},'); + await socket.flush(); + await Future.delayed(const Duration(milliseconds: 20)); + } + } catch (_) {} + await socket.close(); + }); + addTearDown(raw.close); + client = _LocalClient(Uri.parse('http://127.0.0.1:${raw.port}')); + final api = ApiService( + client: client, borderTimeout: const Duration(milliseconds: 300)); + + final stopwatch = Stopwatch()..start(); + final result = await api.fetchBorderPolygons( + lat: -36.85, lon: 174.76, appVersion: 'APP-TEST'); + stopwatch.stop(); + + expect(result, isNull); + expect(stopwatch.elapsed, lessThan(const Duration(seconds: 5))); + expect(client.sent, 1); + // The phone closed the connection: the download really stopped. + await hungUp.future.timeout(const Duration(seconds: 5)); + + // The aborted connection is not reused: the same client asks again and + // gets a whole answer. + final again = await api + .fetchBorderPolygons(lat: -36.85, lon: 174.76, appVersion: 'APP-TEST') + .timeout(const Duration(seconds: 5)); + expect(again!.polygons.single['code'], 'AKL'); + expect(client.sent, 2); + expect(connections, 2); + }); + + test('a /border answer within the allowance is parsed', () async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server!.listen((request) async { + request.response + ..headers.contentType = ContentType.json + ..write(json.encode({ + 'success': true, + 'border_hash': 'abc123', + 'polygons': [ + { + 'code': 'AKL', + 'polygon': [ + [1, 2], + [3, 4], + ], + }, + ], + })); + await request.response.close(); + }); + client = _LocalClient(Uri.parse('http://127.0.0.1:${server!.port}')); + final api = ApiService(client: client); + + final result = await api.fetchBorderPolygons( + lat: -36.85, lon: 174.76, appVersion: 'APP-TEST'); + + expect(result!.polygons, hasLength(1)); + expect(result.polygons.first['code'], 'AKL'); + expect(result.borderHash, 'abc123'); + }); + + test('an answer without border_hash is returned with no hash', () async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server!.listen((request) async { + request.response + ..headers.contentType = ContentType.json + ..write(json.encode({ + 'success': true, + 'border_hash': '', + 'polygons': [ + {'code': 'AKL', 'polygon': []}, + ], + })); + await request.response.close(); + }); + client = _LocalClient(Uri.parse('http://127.0.0.1:${server!.port}')); + final api = ApiService(client: client); + + final result = await api.fetchBorderPolygons( + lat: -36.85, lon: 174.76, appVersion: 'APP-TEST'); + + expect(result!.polygons, hasLength(1)); + expect(result.borderHash, isNull); + }); + + test('a 503 border_unavailable is a failure', () async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server!.listen((request) async { + request.response + ..statusCode = 503 + ..headers.contentType = ContentType.json + ..headers.set('Retry-After', '300') + ..write(json.encode({ + 'success': false, + 'reason': 'border_unavailable', + })); + await request.response.close(); + }); + client = _LocalClient(Uri.parse('http://127.0.0.1:${server!.port}')); + final api = ApiService(client: client); + + final result = await api.fetchBorderPolygons( + lat: -36.85, lon: 174.76, appVersion: 'APP-TEST'); + + expect(result, isNull); + expect(client.sent, 1); + }); + + test('a server that never answers the headers is aborted too', () async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server!.listen((_) {}); + client = _LocalClient(Uri.parse('http://127.0.0.1:${server!.port}')); + final api = ApiService( + client: client, borderTimeout: const Duration(milliseconds: 300)); + + final result = await api + .fetchBorderPolygons(lat: -36.85, lon: 174.76, appVersion: 'APP-TEST') + .timeout(const Duration(seconds: 5)); + + expect(result, isNull); + // An abort is never sent again. + expect(client.sent, 1); + }); +} diff --git a/test/services/api_service_fresh_tile_test.dart b/test/services/api_service_fresh_tile_test.dart index cc6e6a67..04a69fc9 100644 --- a/test/services/api_service_fresh_tile_test.dart +++ b/test/services/api_service_fresh_tile_test.dart @@ -18,6 +18,7 @@ void main() { 'x': '4173', 'y': '6157', 'gsize': '100', + 'cf': '2', 'fresh': '1', 'f_freq': '910.525', 'f_bw': '62.5', @@ -123,4 +124,55 @@ void main() { expect(result.changed, isNull); expect(result.body, isNull); }); + + group('a missing verdict says why', () { + test('an absent header on a 200 reads as no verdict, not a failure', + () async { + final api = ApiService(client: MockClient((_) async { + return http.Response.bytes([1], 200); + })); + + final result = + await api.freshenVectorTile(zone: 'yow', z: 14, x: 1, y: 2); + + expect(result.changed, isNull); + expect(result.noVerdictReason, 'header absent'); + }); + + test('a non-2xx names its status', () async { + final api = ApiService(client: MockClient((_) async { + return http.Response('', 503); + })); + + final result = + await api.freshenVectorTile(zone: 'yow', z: 13, x: 1, y: 2); + + expect(result.changed, isNull); + expect(result.noVerdictReason, 'HTTP 503'); + }); + + test('a transport error reads as a failed request', () async { + final api = ApiService(client: MockClient((_) async { + throw http.ClientException('connection reset'); + })); + + final result = + await api.freshenVectorTile(zone: 'yow', z: 13, x: 1, y: 2); + + expect(result.changed, isNull); + expect(result.noVerdictReason, 'request failed'); + }); + + test('a verdict carries no reason', () async { + final api = ApiService(client: MockClient((_) async { + return http.Response('', 204, headers: {'x-tile-changed': '0'}); + })); + + final result = + await api.freshenVectorTile(zone: 'yow', z: 12, x: 1, y: 2); + + expect(result.changed, isFalse); + expect(result.noVerdictReason, isNull); + }); + }); } diff --git a/test/services/api_service_heartbeat_test.dart b/test/services/api_service_heartbeat_test.dart index 63e1612e..0feff0d6 100644 --- a/test/services/api_service_heartbeat_test.dart +++ b/test/services/api_service_heartbeat_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:clock/clock.dart'; @@ -6,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:mesh_mapper/services/api_service.dart'; +import 'package:mesh_mapper/services/idle_session.dart'; /// Regression tests for the 2026-08-29 heartbeat POST storm (361k requests in /// 64 minutes from one device). @@ -221,4 +223,258 @@ void main() { }); }); }); + + group('an expired keepalive while idle (#563)', () { + /// A server whose session has lapsed: every heartbeat answers + /// session_expired until a new /auth mints a fresh session. + ({ + ApiService api, + int Function() auths, + int Function() heartbeats, + int Function() recoveries, + }) buildLapsed(bool Function() idle) { + var auths = 0; + var heartbeats = 0; + var recoveries = 0; + var lapsed = false; + late final ApiService api; + api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + auths++; + // The first auth is the connect; the test then lets it lapse. + lapsed = auths == 1; + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'session-$auths', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + }), + 200, + ); + } + heartbeats++; + if (lapsed) { + return http.Response( + json.encode({ + 'success': false, + 'reason': 'session_expired', + 'message': 'expired for test', + }), + 401, + ); + } + return http.Response( + json.encode({ + 'success': true, + 'expires_at': clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + }), + 200, + ); + }), + ); + api.onSessionExpiredRecovery = () async { + recoveries++; + await api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.0, + lon: -75.0, + ); + return SessionRecoveryResult.recovered; + }; + api.isSessionIdle = idle; + return ( + api: api, + auths: () => auths, + heartbeats: () => heartbeats, + recoveries: () => recoveries, + ); + } + + void connectAndRunToFirstKeepalive(FakeAsync async, ApiService api) { + api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.0, + lon: -75.0, + ); + async.flushMicrotasks(); + api.enableHeartbeat(); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 241)); + async.flushMicrotasks(); + } + + bool idleWith({bool autoPingEnabled = false, int queuedItems = 0}) => + sessionIsIdle( + autoPingEnabled: autoPingEnabled, + autoPingStarting: false, + pendingDisable: false, + pingSending: false, + pingInProgress: false, + repeaterAdminOpen: false, + queuedItems: queuedItems, + ); + + test('idle: no recovery, the keepalive stops, the next action recovers', + () { + fakeAsync((async) { + final origin = DateTime.utc(2026, 9, 28, 22); + withClock(Clock(() => origin.add(async.elapsed)), () { + final built = buildLapsed(() => idleWith()); + connectAndRunToFirstKeepalive(async, built.api); + + expect(built.heartbeats(), 1); + expect(built.recoveries(), 0, + reason: 'an idle app must not mint a session nobody will use'); + expect(built.auths(), 1); + expect(built.api.sessionId, 'session-1', + reason: 'the lapsed session is left in place, not cleared'); + + async.elapse(const Duration(minutes: 30)); + expect(built.heartbeats(), 1, + reason: 'the keepalive stops instead of retrying'); + expect(built.recoveries(), 0); + + // The next Start or manual ping runs the session check, which + // posts its own heartbeat and recovers on the expired answer. + ({bool isValid, String? reason, String? message})? check; + built.api.checkSessionValid(lat: 45.0, lon: -75.0).then((r) { + check = r; + }); + async.flushMicrotasks(); + expect(check?.isValid, isTrue); + expect(built.recoveries(), 1); + expect(built.api.sessionId, 'session-2'); + + // The recovered session owns a keepalive again. + final before = built.heartbeats(); + async.elapse(const Duration(seconds: 241)); + expect(built.heartbeats(), before + 1, + reason: 'the recovered session schedules its own keepalive'); + }); + }); + }); + + test('a running mode still recovers as before', () { + fakeAsync((async) { + final origin = DateTime.utc(2026, 9, 28, 22); + withClock(Clock(() => origin.add(async.elapsed)), () { + final built = buildLapsed(() => idleWith(autoPingEnabled: true)); + connectAndRunToFirstKeepalive(async, built.api); + + expect(built.recoveries(), 1); + expect(built.auths(), 2); + expect(built.api.sessionId, 'session-2'); + }); + }); + }); + + test('queued items still recover as before', () { + fakeAsync((async) { + final origin = DateTime.utc(2026, 9, 28, 22); + withClock(Clock(() => origin.add(async.elapsed)), () { + final built = buildLapsed(() => idleWith(queuedItems: 3)); + connectAndRunToFirstKeepalive(async, built.api); + + expect(built.recoveries(), 1); + expect(built.auths(), 2); + expect(built.api.sessionId, 'session-2'); + }); + }); + }); + test('a late expired answer for a replaced session leaves its keepalive', + () { + fakeAsync((async) { + final origin = DateTime.utc(2026, 9, 28, 22); + withClock(Clock(() => origin.add(async.elapsed)), () { + var auths = 0; + var recoveries = 0; + final heartbeatSessions = []; + final held = Completer(); + http.Response expired() => http.Response( + json.encode({ + 'success': false, + 'reason': 'session_expired', + 'message': 'expired for test', + }), + 401, + ); + late final ApiService api; + api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + auths++; + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'session-$auths', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + }), + 200, + ); + } + final body = json.decode(request.body) as Map; + final sid = body['session_id'] as String; + heartbeatSessions.add(sid); + if (sid == 'session-1') { + // The scheduled keepalive is held in flight; the manual + // check that follows is answered at once. + if (heartbeatSessions.length == 1) return held.future; + return expired(); + } + return http.Response( + json.encode({ + 'success': true, + 'expires_at': + clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + }), + 200, + ); + }), + ); + api.onSessionExpiredRecovery = () async { + recoveries++; + await api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.0, + lon: -75.0, + ); + return SessionRecoveryResult.recovered; + }; + api.isSessionIdle = () => idleWith(); + connectAndRunToFirstKeepalive(async, api); + expect(heartbeatSessions, ['session-1']); + + // A manual action recovers to session-2 while the keepalive for + // session-1 is still waiting on its answer. + ({bool isValid, String? reason, String? message})? check; + api.checkSessionValid(lat: 45.0, lon: -75.0).then((r) { + check = r; + }); + async.flushMicrotasks(); + expect(check?.isValid, isTrue); + expect(api.sessionId, 'session-2'); + expect(recoveries, 1); + + // The stale answer lands with the app idle. + held.complete(expired()); + async.flushMicrotasks(); + expect(api.sessionId, 'session-2'); + expect(recoveries, 1, reason: 'a stale answer must not re-mint'); + + async.elapse(const Duration(seconds: 241)); + expect(heartbeatSessions.last, 'session-2', + reason: "the replacement session's keepalive survives"); + }); + }); + }); + }); } diff --git a/test/services/api_service_keep_policy_test.dart b/test/services/api_service_keep_policy_test.dart new file mode 100644 index 00000000..1e13e3d0 --- /dev/null +++ b/test/services/api_service_keep_policy_test.dart @@ -0,0 +1,146 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// A group handoff releases the old session and mints a new one at once. +/// For those two round trips the app is still connected, and the UI reads +/// txAllowed, the channels and the enforce flags on every notify: a plain +/// release zeroed them, so the Active button vanished, the status bar went +/// red with "at capacity" and Smart Pinging dropped its tiles. A keepPolicy +/// release clears only the session itself. +void main() { + ApiService build() => ApiService( + client: MockClient((request) async { + final body = json.decode(request.body) as Map; + if (body['reason'] == 'connect') { + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20261012-0001', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': 1800000000, + 'channels': ['#ottawa'], + 'enforce_hybrid': true, + 'hop_bytes': 2, + 'smart_ping': true, + 'smart_ping_days': 7, + 'scope_discovery': true, + }), + 200, + ); + } + return http.Response(json.encode({'success': true}), 200); + }), + ); + + Future connect(ApiService api) => api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.27, + lon: -75.78, + ); + + test('a keepPolicy release clears the session but keeps the zone policy', + () async { + final api = build(); + await connect(api); + expect(api.hasSession, isTrue); + expect(api.txAllowed, isTrue); + + await api.requestAuth( + reason: 'disconnect', publicKey: 'AB', keepPolicy: true); + + expect(api.hasSession, isFalse); + expect(api.sessionId, isNull); + expect(api.txAllowed, isTrue, reason: 'the Active button stays'); + expect(api.rxAllowed, isTrue); + expect(api.channels, ['#ottawa']); + expect(api.enforceHybrid, isTrue); + expect(api.apiHopBytes, 2); + expect(api.enforceSmartPing, isTrue); + expect(api.scopeDiscoveryOffered, isTrue); + + // The mint that follows overwrites every kept field. + await connect(api); + expect(api.hasSession, isTrue); + expect(api.txAllowed, isTrue); + api.dispose(); + }); + + test('a plain release still clears the policy with the session', () async { + final api = build(); + await connect(api); + + await api.requestAuth(reason: 'disconnect', publicKey: 'AB'); + + expect(api.hasSession, isFalse); + expect(api.txAllowed, isFalse); + expect(api.rxAllowed, isFalse); + expect(api.channels, isEmpty); + expect(api.enforceHybrid, isFalse); + expect(api.apiHopBytes, 1); + expect(api.scopeDiscoveryOffered, isFalse); + api.dispose(); + }); + + test('a release that lands after a new session was stored keeps the new one', + () async { + final releaseGate = Completer(); + var auths = 0; + final api = ApiService( + client: MockClient((request) async { + final body = json.decode(request.body) as Map; + if (body['reason'] == 'connect') { + auths++; + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20261012-000$auths', + 'tx_allowed': true, + 'rx_allowed': true, + }), + 200, + ); + } + await releaseGate.future; + return http.Response(json.encode({'success': true}), 200); + }), + ); + await connect(api); + expect(api.sessionId, 'YOW-20261012-0001'); + + // The release of the first session is on the wire when a reconnect's + // connect auth stores a second one. + final release = api.requestAuth( + reason: 'disconnect', publicKey: 'AB', keepPolicy: true); + await connect(api); + expect(api.sessionId, 'YOW-20261012-0002'); + + releaseGate.complete(); + await release; + expect(api.sessionId, 'YOW-20261012-0002', + reason: 'the old release must not null the session that replaced it'); + expect(api.hasSession, isTrue); + api.dispose(); + }); + + test('clearSession forgets a kept policy when no mint follows', () async { + final api = build(); + await connect(api); + await api.requestAuth( + reason: 'disconnect', publicKey: 'AB', keepPolicy: true); + expect(api.txAllowed, isTrue); + + api.clearSession(); + + expect(api.hasSession, isFalse); + expect(api.txAllowed, isFalse); + expect(api.channels, isEmpty); + api.dispose(); + }); +} diff --git a/test/services/api_service_repeaters_test.dart b/test/services/api_service_repeaters_test.dart new file mode 100644 index 00000000..6334c505 --- /dev/null +++ b/test/services/api_service_repeaters_test.dart @@ -0,0 +1,258 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_lifecycle.dart'; + +void main() { + const filter = {'f_freq': '910.525', 'f_bw': '62.5', 'f_sf': '7'}; + final body = jsonEncode([ + { + 'id': 'ab', + 'hex_id': 'ab1234', + 'name': 'Enabled', + 'enabled': 1, + 'lat': 45, + 'lon': -75, + 'last_heard': 1 + }, + { + 'id': 'cd', + 'hex_id': 'cd1234', + 'name': 'Disabled', + 'enabled': 0, + 'lat': 45, + 'lon': -75, + 'last_heard': 1 + }, + ]); + + for (final host in ['YOW', 'GROUP']) { + for (final preset in [null, filter]) { + test('$host sends the App key without a session, preset=$preset', + () async { + http.Request? seen; + final api = ApiService(client: MockClient((request) async { + seen = request; + return http.Response(body, 200); + })) + ..radioFilterGetter = () => preset; + addTearDown(api.dispose); + expect(api.sessionId, isNull); + final result = await api.fetchRepeaters(host); + expect(seen!.method, 'GET'); + expect(seen!.headers['X-API-Key'], ApiService.apiKey); + expect(seen!.url.host, '${host.toLowerCase()}.meshmapper.net'); + expect(seen!.url.path, '/get_repeaters.php'); + expect(seen!.url.queryParameters, preset ?? {}); + expect(result.map((r) => r.name), ['Enabled']); + expect(api.sessionId, isNull); + }); + } + } + + for (final status in [401, 403, 429, 500]) { + test('$status is a failure, never an empty success or anonymous retry', + () async { + var calls = 0; + final api = ApiService(client: MockClient((request) async { + calls++; + expect(request.headers['X-API-Key'], ApiService.apiKey); + return http.Response('{"error":"rejected"}', status); + })); + addTearDown(api.dispose); + await expectLater( + api.fetchRepeaters('YOW'), + throwsA( + isA() + .having((e) => e.statusCode, 'HTTP status', status) + .having((e) => e.isAuthenticationFailure, 'auth failure', + status == 401 || status == 403), + )); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + expect(calls, 1); + }); + } + + for (final retryAfter in ['120', 'bad', null]) { + test('429 honors backoff ($retryAfter) without blocking another host', + () async { + var now = DateTime.utc(2026, 10, 4); + final calls = []; + final api = ApiService( + now: () => now, + client: MockClient((request) async { + calls.add(request.url.host); + if (calls.length == 1) { + return http.Response('', 429, + headers: {if (retryAfter != null) 'retry-after': retryAfter}); + } + return http.Response('[]', 200); + })); + addTearDown(api.dispose); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + await expectLater(api.fetchRepeaters('yow'), throwsException); + expect(await api.fetchRepeaters('GROUP'), isEmpty); + final wait = retryAfter == '120' ? 120 : 75; + now = now.add(Duration(seconds: wait - 1)); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + expect(calls.length, 2); + now = now.add(const Duration(seconds: 1)); + expect(await api.fetchRepeaters('YOW'), isEmpty); + expect(calls.length, 3); + }); + } + + test('overlapping failures never shorten a server backoff', () async { + var now = DateTime.utc(2026, 10, 4); + final responses = [Completer(), Completer()]; + var calls = 0; + final api = ApiService( + now: () => now, + client: MockClient((_) { + final call = calls++; + return call < 2 + ? responses[call].future + : Future.value(http.Response('[]', 200)); + })); + addTearDown(api.dispose); + final first = expectLater(api.fetchRepeaters('YOW'), throwsException); + final second = expectLater(api.fetchRepeaters('YOW'), throwsException); + responses[0] + .complete(http.Response('', 429, headers: {'retry-after': '600'})); + await first; + responses[1].complete(http.Response('', 500)); + await second; + now = now.add(const Duration(seconds: 60)); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + expect(calls, 2); + now = now.add(const Duration(seconds: 540)); + expect(await api.fetchRepeaters('YOW'), isEmpty); + expect(calls, 3); + }); + + test('the same App key is sent after session acquisition and on refresh', + () async { + final headers = >[]; + final api = ApiService(client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response( + jsonEncode({ + 'success': true, + 'session_id': 'test-session', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + }), + 200); + } + headers.add(request.headers); + return http.Response(body, 200); + })); + addTearDown(api.dispose); + await api.fetchRepeaters('YOW'); + await api.requestAuth( + reason: 'connect', publicKey: 'AB', lat: 45, lon: -75); + expect(api.sessionId, 'test-session'); + await api.fetchRepeaters('YOW'); + await api.fetchRepeaters('GROUP'); + expect(headers.length, 3); + for (final h in headers) { + expect(h['X-API-Key'], ApiService.apiKey); + expect(h.containsKey('session_id'), isFalse); + } + }); + + test('the 15 second repeater timeout is preserved', () { + fakeAsync((time) { + final response = Completer(); + final api = ApiService(client: MockClient((_) => response.future)); + Object? failure; + api.fetchRepeaters('YOW').then((_) => fail('must time out'), + onError: (Object e) { + failure = e; + }); + time.elapse(const Duration(seconds: 14)); + expect(failure, isNull); + time.elapse(const Duration(seconds: 1)); + expect(failure, isA()); + response.complete(http.Response('[]', 200)); + time.flushMicrotasks(); + api.dispose(); + }); + }); + + for (final changePreset in [false, true]) { + test( + 'a delayed list is discarded after ${changePreset ? 'preset' : 'region/group'} changes', + () async { + final response = Completer(); + final api = ApiService(client: MockClient((_) => response.future)); + addTearDown(api.dispose); + var zone = 'YOW'; + String? preset; + final lifecycle = + ScopeLifecycle(cancelHostRunner: (_) {}, onBadgeChanged: () {}); + final pending = lifecycle.resultIfStillCurrent( + fetch: api.fetchRepeaters(zone), + zone: zone, + preset: preset, + currentZone: () => zone, + currentPreset: () => preset, + ); + if (changePreset) { + preset = '910.525,62.5,7'; + } else { + zone = 'GROUP'; + } + response.complete(http.Response(body, 200)); + expect(await pending, isNull); + }); + } + + for (final error in [ + TimeoutException('timeout'), + http.ClientException('offline'), + const FormatException('invalid') + ]) { + test('$error is a failure instead of an empty list', () async { + final api = ApiService(client: MockClient((_) async => throw error)); + addTearDown(api.dispose); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + }); + } + + test('malformed response is a failure', () async { + final api = + ApiService(client: MockClient((_) async => http.Response('{}', 200))); + addTearDown(api.dispose); + await expectLater(api.fetchRepeaters('YOW'), throwsException); + }); + + for (final status in [401, 403, 429, 500]) { + test('scope refresh rejects $status instead of replacing a loaded list', + () async { + var statusCode = 200; + final api = ApiService( + client: MockClient((_) async => http.Response(body, statusCode))); + addTearDown(api.dispose); + await api.fetchRepeaters('YOW'); + final lifecycle = + ScopeLifecycle(cancelHostRunner: (_) {}, onBadgeChanged: () {}); + statusCode = status; + final result = await lifecycle.resultIfStillCurrent( + fetch: api.fetchRepeaters('YOW'), + zone: 'YOW', + preset: null, + currentZone: () => 'YOW', + currentPreset: () => null, + ); + expect(result, isNull); + }); + } +} diff --git a/test/services/api_service_scope_discovery_test.dart b/test/services/api_service_scope_discovery_test.dart new file mode 100644 index 00000000..f9370125 --- /dev/null +++ b/test/services/api_service_scope_discovery_test.dart @@ -0,0 +1,111 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// Scope discovery rides two `/auth` fields, same shape as Smart Pinging. +/// The key's PRESENCE is the gate: a server that predates the feature never +/// sends it, and the app must never ask a repeater for its scopes without it. +void main() { + Map authBody(Map extra) => { + 'success': true, + 'session_id': 'YOW-20260905-0001', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': DateTime.now().millisecondsSinceEpoch ~/ 1000 + 300, + ...extra, + }; + + Future authed(Map extra, + {bool skipSessionStore = false}) async { + final api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response(json.encode(authBody(extra)), 200); + } + return http.Response('{}', 404); + }), + ); + // requestAuth throws without coordinates on a connect, so a fix is + // part of the request shape here (as in api_service_smart_ping_test). + await api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.42, + lon: -75.70, + skipSessionStore: skipSessionStore, + ); + return api; + } + + group('auth parsing', () { + test('key absent: not offered, not enforced, 14 days', () async { + final api = await authed({}); + expect(api.scopeDiscoveryOffered, isFalse); + expect(api.enforceScopeDiscovery, isFalse); + expect(api.apiScopeRefreshDays, 14); + }); + + test('false: offered, not enforced', () async { + final api = await authed({'scope_discovery': false}); + expect(api.scopeDiscoveryOffered, isTrue); + expect(api.enforceScopeDiscovery, isFalse); + }); + + test('true and 1 both enforce', () async { + expect((await authed({'scope_discovery': true})).enforceScopeDiscovery, + isTrue); + expect( + (await authed({'scope_discovery': 1})).enforceScopeDiscovery, + isTrue); + }); + + test('days: 3 reads as 7, "x" as 14, 30 as 30', () async { + expect( + (await authed({'scope_discovery': true, 'scope_refresh_days': 3})) + .apiScopeRefreshDays, + 7); + expect( + (await authed( + {'scope_discovery': true, 'scope_refresh_days': 'x'})) + .apiScopeRefreshDays, + 14); + expect( + (await authed({'scope_discovery': true, 'scope_refresh_days': 30})) + .apiScopeRefreshDays, + 30); + }); + + test('a later auth without the key withdraws the offer', () async { + var body = authBody({'scope_discovery': true}); + final api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response(json.encode(body), 200); + } + return http.Response('{}', 404); + }), + ); + await api.requestAuth( + reason: 'connect', publicKey: 'AB' * 32, lat: 45.42, lon: -75.70); + expect(api.scopeDiscoveryOffered, isTrue); + + body = authBody({}); + await api.requestAuth( + reason: 'connect', publicKey: 'AB' * 32, lat: 45.42, lon: -75.70); + expect(api.scopeDiscoveryOffered, isFalse); + }); + + test('skipSessionStore auth leaves the fields alone', () async { + final api = await authed( + {'scope_discovery': true, 'scope_refresh_days': 30}, + skipSessionStore: true, + ); + expect(api.scopeDiscoveryOffered, isFalse); + expect(api.enforceScopeDiscovery, isFalse); + expect(api.apiScopeRefreshDays, 14); + }); + }); +} diff --git a/test/services/api_service_scope_replay_test.dart b/test/services/api_service_scope_replay_test.dart new file mode 100644 index 00000000..54f82b76 --- /dev/null +++ b/test/services/api_service_scope_replay_test.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// A wardrive batch that lands on a closed keep-alive socket is replayed +/// once. If a live auth withdrew scope discovery while that first attempt +/// was failing, the replay must not carry the SCOPES answers the queue only +/// selected because the gate was open when the batch was built. +void main() { + Map authBody({required bool offered}) => { + 'success': true, + 'session_id': 'YOW-20260927-0001', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': DateTime.now().millisecondsSinceEpoch ~/ 1000 + 300, + if (offered) 'scope_discovery': false, + }; + + Future auth(ApiService api) => api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.42, + lon: -75.70, + ); + + final disc = {'type': 'DISC', 'lat': 45.42, 'lon': -75.70}; + final scopes = {'type': 'SCOPES', 'repeater_id': 'AB'}; + + ({ApiService api, List> bodies}) build({ + required bool withdrawDuringFirstAttempt, + }) { + final bodies = >[]; + var offered = true; + var wardriveAttempts = 0; + late ApiService api; + api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + return http.Response(json.encode(authBody(offered: offered)), 200); + } + final body = json.decode(request.body) as Map; + bodies.add(body['data'] as List); + wardriveAttempts++; + if (wardriveAttempts == 1) { + if (withdrawDuringFirstAttempt) { + offered = false; + await auth(api); + } + throw http.ClientException( + 'Connection closed before full header was received', + request.url, + ); + } + return http.Response( + json.encode({'success': true, 'expires_at': 1789185716}), 200); + }), + ); + return (api: api, bodies: bodies); + } + + test('a replay after the gate closed carries no SCOPES', () async { + final t = build(withdrawDuringFirstAttempt: true); + await auth(t.api); + expect(t.api.scopeDiscoveryOffered, isTrue); + + final result = await t.api.uploadBatch([disc, scopes]); + + expect(t.api.scopeDiscoveryOffered, isFalse); + expect(t.bodies.length, 2); + expect(t.bodies.first.map((e) => e['type']), ['DISC', 'SCOPES']); + expect(t.bodies.last.map((e) => e['type']), ['DISC']); + expect(result, UploadResult.success); + t.api.dispose(); + }); + + test('a replay with the gate still open is sent unchanged', () async { + final t = build(withdrawDuringFirstAttempt: false); + await auth(t.api); + + final result = await t.api.uploadBatch([disc, scopes]); + + expect(t.bodies.length, 2); + expect(t.bodies.last.map((e) => e['type']), ['DISC', 'SCOPES']); + expect(result, UploadResult.success); + t.api.dispose(); + }); + + test('a replay left with nothing but SCOPES is not sent at all', () async { + final t = build(withdrawDuringFirstAttempt: true); + await auth(t.api); + + final result = await t.api.uploadBatch([scopes]); + + expect(t.bodies.length, 1); + expect(result, UploadResult.unreachable); + t.api.dispose(); + }); +} diff --git a/test/services/api_service_smart_ping_test.dart b/test/services/api_service_smart_ping_test.dart index e4b43c2d..5ad8c8e4 100644 --- a/test/services/api_service_smart_ping_test.dart +++ b/test/services/api_service_smart_ping_test.dart @@ -70,6 +70,41 @@ void main() { }); }); + group('flood only parsing', () { + test('a missing field reads true', () async { + final api = await authed({'smart_ping': true}); + expect(api.apiSmartPingFloodOnly, isTrue); + }); + + test('false and 0 read false', () async { + expect( + (await authed({'smart_ping_flood_only': false})) + .apiSmartPingFloodOnly, + isFalse); + expect( + (await authed({'smart_ping_flood_only': 0})).apiSmartPingFloodOnly, + isFalse); + }); + + test('true and a string read true', () async { + expect( + (await authed({'smart_ping_flood_only': true})) + .apiSmartPingFloodOnly, + isTrue); + expect( + (await authed({'smart_ping_flood_only': 'false'})) + .apiSmartPingFloodOnly, + isTrue); + }); + + test('clearing the session reads true again', () async { + final api = await authed({'smart_ping_flood_only': false}); + expect(api.apiSmartPingFloodOnly, isFalse); + api.clearSession(); + expect(api.apiSmartPingFloodOnly, isTrue); + }); + }); + group('fetchRecentCoverageTile', () { http.Request? seen; ApiService answering(http.Response Function() responder) => ApiService( @@ -92,6 +127,7 @@ void main() { 'x': '2385', 'y': '2926', 'gsize': '300', + 'cf': '2', 'f_days': '14', 'f_types': 'green,cyan', }); diff --git a/test/services/api_service_stale_upload_answer_test.dart b/test/services/api_service_stale_upload_answer_test.dart new file mode 100644 index 00000000..9e0b23d6 --- /dev/null +++ b/test/services/api_service_stale_upload_answer_test.dart @@ -0,0 +1,99 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; + +/// An upload refusal is about the session the batch was sent under. A +/// Disconnect now uploads the queue before it releases the session, and on a +/// slow network that POST can still be out when the release lands, or when +/// the user has already reconnected. Its `bad_session` answer used to clear +/// whatever session was current and fire the session-error disconnect, so a +/// stale answer for the old session tore down the new connection. +void main() { + ({ApiService api, Completer gate, List errors}) build() { + var auths = 0; + final gate = Completer(); + final errors = []; + final api = ApiService( + client: MockClient((request) async { + if (request.url.path.endsWith('/auth')) { + auths++; + return http.Response( + json.encode({ + 'success': true, + 'session_id': 'session-$auths', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + DateTime.now().millisecondsSinceEpoch ~/ 1000 + 3600, + }), + 200, + ); + } + await gate.future; + return http.Response( + json.encode({ + 'success': false, + 'reason': 'bad_session', + 'message': 'closed for test', + }), + 401, + ); + }), + ); + api.onSessionError = (reason, message, {subReason}) async { + errors.add(reason ?? 'null'); + }; + return (api: api, gate: gate, errors: errors); + } + + Future connect(ApiService api) => api.requestAuth( + reason: 'connect', + publicKey: 'AB', + lat: 45.0, + lon: -75.0, + ); + + final batch = [ + {'type': 'RX', 'lat': 45.0, 'lon': -75.0} + ]; + + test('a refusal for a released session is ignored', () async { + final built = build(); + await connect(built.api); + + final upload = built.api.uploadBatch(batch); + built.api.clearSession(); + built.gate.complete(); + + expect(await upload, UploadResult.held); + expect(built.errors, isEmpty); + }); + + test('a refusal for a replaced session leaves the new one alone', () async { + final built = build(); + await connect(built.api); + expect(built.api.sessionId, 'session-1'); + + final upload = built.api.uploadBatch(batch); + await connect(built.api); + built.gate.complete(); + + expect(await upload, UploadResult.held); + expect(built.api.sessionId, 'session-2'); + expect(built.errors, isEmpty); + }); + + test('a refusal for the current session still ends it', () async { + final built = build(); + await connect(built.api); + built.gate.complete(); + + expect(await built.api.uploadBatch(batch), UploadResult.nonRetryable); + expect(built.api.sessionId, isNull); + expect(built.errors, ['bad_session']); + }); +} diff --git a/test/services/app_intents/last_companion_connection_test.dart b/test/services/app_intents/last_companion_connection_test.dart index d36c7a81..48f6d1c8 100644 --- a/test/services/app_intents/last_companion_connection_test.dart +++ b/test/services/app_intents/last_companion_connection_test.dart @@ -130,4 +130,52 @@ void main() { expect(resolve().disposition, ExternalCommandDisposition.admitted); }); }); + + group('answer window', () { + test('waits the full quick-answer time when the deadline is far off', () { + expect( + lastCompanionAnswerWindow(now.add(const Duration(seconds: 25)), + now: now), + lastCompanionQuickAnswer, + ); + }); + + test('answers before the deadline after a slow cold launch', () { + // 8 seconds left: answer 3 seconds clear of it. + expect( + lastCompanionAnswerWindow(now.add(const Duration(seconds: 8)), + now: now), + const Duration(seconds: 5), + ); + }); + + test('answers at once when the margin is already gone', () { + expect( + lastCompanionAnswerWindow(now.add(const Duration(seconds: 2)), + now: now), + Duration.zero, + ); + expect( + lastCompanionAnswerWindow(now.subtract(const Duration(seconds: 1)), + now: now), + Duration.zero, + ); + }); + + test('an older native build sending no deadline gets the quick answer', + () { + expect(lastCompanionAnswerWindow(null, now: now), + lastCompanionQuickAnswer); + }); + + test('always answers inside the native 25 second budget', () { + // The deadline native code sends is at most 25 seconds out, so the + // answer lands with the margin still to spare. + final window = lastCompanionAnswerWindow( + now.add(const Duration(seconds: 25)), + now: now); + expect(window + lastCompanionAnswerMargin, + lessThanOrEqualTo(const Duration(seconds: 25))); + }); + }); } diff --git a/test/services/app_intents/siri_snapshot_builder_test.dart b/test/services/app_intents/siri_snapshot_builder_test.dart index cbf56680..65737d27 100644 --- a/test/services/app_intents/siri_snapshot_builder_test.dart +++ b/test/services/app_intents/siri_snapshot_builder_test.dart @@ -4,6 +4,7 @@ import 'package:mesh_mapper/models/repeater.dart'; import 'package:mesh_mapper/services/app_intents/siri_snapshot_builder.dart'; import 'package:mesh_mapper/services/app_intents/siri_snapshot_models.dart'; import 'package:mesh_mapper/services/watch/watch_models.dart'; +import 'package:mesh_mapper/utils/repeater_nicknames.dart'; void main() { final now = DateTime.fromMillisecondsSinceEpoch(1787535920000); @@ -708,4 +709,53 @@ void main() { expect(catalog.first.id, 'SEA|repeater-7'); expect(catalog[1].id, 'SEA|repeater-0'); }); + + test('a nickname names the observation but not the Shortcuts catalogue', () { + final fullKey = '4E5D82AA'.padRight(64, '0'); + final keyed = Repeater( + id: 'database-123', + hexId: fullKey, + name: 'Capitol Hill', + lat: 47.6202, + lon: -122.3194, + lastHeard: 1787535900, + enabled: 1, + iata: 'SEA', + ); + final tx = [ + TxLogEntry( + timestamp: now, + latitude: 47.6, + longitude: -122.3, + power: 1, + events: [RxEvent(repeaterId: '4E5D', snr: 8.5, rssi: -91)], + ), + ]; + SiriRecentHeard heard(Map nicknames) => + SiriSnapshotBuilder.buildRecentHeard( + txEntries: tx, + rxEntries: const [], + discoveryEntries: const [], + traceEntries: const [], + repeaters: [keyed], + hopBytes: 2, + now: now, + nicknames: nicknames, + ); + + final nicknamed = heard({ + fullKey: const RepeaterNickname( + nickname: 'Mell', name: 'Capitol Hill', hex: '4E5D82AA'), + }).observations.single; + expect(nicknamed.name, 'Mell'); + expect(nicknamed.entityId, 'SEA|database-123', + reason: 'a nickname never changes the entity identity'); + + expect(heard(const {}).observations.single.name, 'Capitol Hill', + reason: 'without nicknames the server name is unchanged'); + + expect(SiriSnapshotBuilder.buildRepeaterCatalog([keyed]).single.name, + 'Capitol Hill', + reason: 'Shortcuts entities keep the server name'); + }); } diff --git a/test/services/background_location_policy_test.dart b/test/services/background_location_policy_test.dart new file mode 100644 index 00000000..5e969e64 --- /dev/null +++ b/test/services/background_location_policy_test.dart @@ -0,0 +1,290 @@ +import 'dart:ui' show AppLifecycleState; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/services/background_location_policy.dart'; + +/// When GPS and Android's session service may run in the background. +/// +/// One test per row of the policy table, so a change to the rule shows up as a +/// named failure instead of a drive that goes quiet. +void main() { + group('radioSessionActive', () { + bool active( + ConnectionStep step, { + bool autoReconnecting = false, + bool connectRerunPending = false, + }) => + radioSessionActive( + step: step, + autoReconnecting: autoReconnecting, + connectRerunPending: connectRerunPending, + ); + + for (final step in ConnectionStep.values) { + final quiet = + step == ConnectionStep.disconnected || step == ConnectionStep.error; + test('$step with no flags is ${quiet ? 'inactive' : 'active'}', () { + expect(active(step), !quiet); + }); + } + + test('disconnected with autoReconnecting is active', () { + expect( + active(ConnectionStep.disconnected, autoReconnecting: true), isTrue); + }); + + test('disconnected with a connect re-run pending is active', () { + expect(active(ConnectionStep.disconnected, connectRerunPending: true), + isTrue); + }); + + test('error with either flag is active', () { + expect(active(ConnectionStep.error, autoReconnecting: true), isTrue); + expect(active(ConnectionStep.error, connectRerunPending: true), isTrue); + }); + }); + + group('gpsRunDecision', () { + GpsRunDecision decide( + AppLifecycleState? lifecycle, { + required bool radioActive, + required bool isIos, + }) => + gpsRunDecision( + lifecycle: lifecycle, + radioActive: radioActive, + isIos: isIos, + ); + + for (final isIos in [false, true]) { + final os = isIos ? 'iOS' : 'Android'; + + test('resumed with no radio session runs on $os', () { + expect( + decide(AppLifecycleState.resumed, radioActive: false, isIos: isIos), + GpsRunDecision.run); + }); + + for (final state in [ + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.detached, + ]) { + test('$state with no radio session stops on $os', () { + expect(decide(state, radioActive: false, isIos: isIos), + GpsRunDecision.stop); + }); + } + + test('inactive with no radio session keeps on $os', () { + expect( + decide(AppLifecycleState.inactive, + radioActive: false, isIos: isIos), + GpsRunDecision.keep); + }); + + test('unknown lifecycle with no radio session keeps on $os', () { + expect(decide(null, radioActive: false, isIos: isIos), + GpsRunDecision.keep); + }); + } + + test('paused with a radio session runs on Android', () { + expect(decide(AppLifecycleState.paused, radioActive: true, isIos: false), + GpsRunDecision.run); + }); + + test('paused with a radio session keeps on iOS', () { + expect(decide(AppLifecycleState.paused, radioActive: true, isIos: true), + GpsRunDecision.keep); + }); + + test('unknown lifecycle with a radio session runs on Android', () { + expect(decide(null, radioActive: true, isIos: false), GpsRunDecision.run); + }); + + test('resumed with a radio session runs on iOS', () { + expect(decide(AppLifecycleState.resumed, radioActive: true, isIos: true), + GpsRunDecision.run); + }); + }); + + // The startup permission check (MainScaffold) asks for a GPS start once it + // finds location granted. On a background launch (iOS woke the app, no + // radio) that start used to run straight away and send the first fix to + // /status. It now waits for the app to come on screen, where the policy + // sync makes the first, full start. + group('deferGpsStartAfterPermission', () { + bool defer( + AppLifecycleState? lifecycle, { + bool radioActive = false, + required bool isIos, + bool keepTracking = false, + bool policyApplies = true, + bool alreadyWatching = false, + }) => + deferGpsStartAfterPermission( + keepTracking: keepTracking, + alreadyWatching: alreadyWatching, + policyApplies: policyApplies, + decision: gpsRunDecision( + lifecycle: lifecycle, + radioActive: radioActive, + isIos: isIos, + ), + ); + + for (final isIos in [false, true]) { + final os = isIos ? 'iOS' : 'Android'; + + test('a foreground cold start with permission granted starts on $os', + () { + expect(defer(AppLifecycleState.resumed, isIos: isIos), isFalse); + }); + + test('a first-time grant with the app back on screen starts on $os', () { + expect(defer(AppLifecycleState.resumed, isIos: isIos), isFalse); + }); + + test('a grant read while the system dialog still holds the app ' + 'inactive waits, and the resume starts it on $os', () { + expect(defer(AppLifecycleState.inactive, isIos: isIos), isTrue); + expect( + gpsRunDecision( + lifecycle: AppLifecycleState.resumed, + radioActive: false, + isIos: isIos), + GpsRunDecision.run); + }); + + test('a background launch does not start on $os', () { + expect(defer(null, isIos: isIos), isTrue); + expect(defer(AppLifecycleState.paused, isIos: isIos), isTrue); + expect(defer(AppLifecycleState.hidden, isIos: isIos), isTrue); + expect(defer(AppLifecycleState.detached, isIos: isIos), isTrue); + }); + + test('the quiet restart on return to the app is never held on $os', () { + expect(defer(null, isIos: isIos, keepTracking: true), isFalse); + }); + + // A held start marks GPS stopped by the policy. A stream that is + // already running would then read as stopped without being stopped. + test('a stream already running is never marked held on $os', () { + expect(defer(null, isIos: isIos, alreadyWatching: true), isFalse); + expect( + defer(AppLifecycleState.paused, + isIos: isIos, alreadyWatching: true), + isFalse); + }); + + test('the simulator and web are not held on $os', () { + expect(defer(null, isIos: isIos, policyApplies: false), isFalse); + }); + } + + test('a backgrounded Android app with a radio session starts', () { + expect( + defer(AppLifecycleState.paused, radioActive: true, isIos: false), + isFalse); + }); + + test('a backgrounded iOS app with a radio session waits for the screen', + () { + expect(defer(AppLifecycleState.paused, radioActive: true, isIos: true), + isTrue); + }); + }); + + group('shouldStartConnectionService', () { + bool start({ + bool followsConnection = true, + bool running = false, + bool starting = false, + bool sessionActive = true, + ConnectionStep step = ConnectionStep.transportConnecting, + AppLifecycleState? lifecycle = AppLifecycleState.resumed, + bool locationGranted = true, + }) => + shouldStartConnectionService( + followsConnection: followsConnection, + running: running, + starting: starting, + sessionActive: sessionActive, + step: step, + lifecycle: lifecycle, + locationGranted: locationGranted, + ); + + test('baseline starts', () { + expect(start(), isTrue); + }); + + test('does not start when the service does not follow the connection', () { + expect(start(followsConnection: false), isFalse); + }); + + test('does not start when it is already running', () { + expect(start(running: true), isFalse); + }); + + test('does not start while a start is in flight', () { + expect(start(starting: true), isFalse); + }); + + test('does not start without a radio session', () { + expect(start(sessionActive: false), isFalse); + }); + + test('does not start while disconnecting', () { + expect(start(step: ConnectionStep.disconnecting), isFalse); + }); + + test('does not start when paused', () { + expect(start(lifecycle: AppLifecycleState.paused), isFalse); + }); + + test('does not start when inactive', () { + expect(start(lifecycle: AppLifecycleState.inactive), isFalse); + }); + + test('does not start with an unknown lifecycle', () { + expect(start(lifecycle: null), isFalse); + }); + + test('does not start without location permission', () { + expect(start(locationGranted: false), isFalse); + }); + }); + + group('shouldStopServiceAtCleanupEnd', () { + test('stops when following and no session is left', () { + expect( + shouldStopServiceAtCleanupEnd( + followsConnection: true, sessionActive: false), + isTrue); + }); + + test('keeps going when following and a session is still live', () { + expect( + shouldStopServiceAtCleanupEnd( + followsConnection: true, sessionActive: true), + isFalse); + }); + + test('stops when not following, even with a live session', () { + expect( + shouldStopServiceAtCleanupEnd( + followsConnection: false, sessionActive: true), + isTrue); + }); + + test('stops when not following and no session', () { + expect( + shouldStopServiceAtCleanupEnd( + followsConnection: false, sessionActive: false), + isTrue); + }); + }); +} diff --git a/test/services/background_service_test.dart b/test/services/background_service_test.dart new file mode 100644 index 00000000..61b06c0f --- /dev/null +++ b/test/services/background_service_test.dart @@ -0,0 +1,552 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_background_service/flutter_background_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/background_service.dart'; +import 'package:mesh_mapper/utils/debug_logger_io.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('meshmapper/session_service'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + /// Captures every debug line written from here to the end of the test. + List captureLogs() { + final logs = []; + final originalPrint = debugPrint; + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) logs.add(message); + }; + DebugLogger.setEnabled(true); + addTearDown(() { + debugPrint = originalPrint; + DebugLogger.setEnabled(false); + }); + return logs; + } + + group('BackgroundServiceManager.waitUntilStopped', () { + test('returns at once when the service is already gone', () async { + var calls = 0; + final elapsed = await BackgroundServiceManager.waitUntilStopped( + isRunning: () async { + calls++; + return false; + }, + pollInterval: const Duration(milliseconds: 5), + timeout: const Duration(milliseconds: 200), + ); + expect(elapsed, isNotNull); + expect(calls, 1); + }); + + test('keeps polling until the service reports stopped', () async { + var calls = 0; + final elapsed = await BackgroundServiceManager.waitUntilStopped( + isRunning: () async => ++calls < 3, + pollInterval: const Duration(milliseconds: 5), + timeout: const Duration(seconds: 2), + ); + expect(elapsed, isNotNull); + expect(calls, 3); + }); + + test('gives up at the bound and returns null', () async { + final elapsed = await BackgroundServiceManager.waitUntilStopped( + isRunning: () async => true, + pollInterval: const Duration(milliseconds: 5), + timeout: const Duration(milliseconds: 40), + ); + expect(elapsed, isNull); + }); + + test('a throwing check counts as still running', () async { + var calls = 0; + final elapsed = await BackgroundServiceManager.waitUntilStopped( + isRunning: () async { + calls++; + if (calls == 1) throw StateError('channel'); + return false; + }, + pollInterval: const Duration(milliseconds: 5), + timeout: const Duration(seconds: 1), + ); + expect(elapsed, isNotNull); + expect(calls, 2); + }); + }); + + group('BackgroundServiceManager on the Android session service', () { + late List calls; + late FutureOr Function() startReply; + late Map status; + + List methods() => calls.map((c) => c.method).toList(); + int count(String method) => methods().where((m) => m == method).length; + + setUp(() { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + BackgroundServiceManager.debugInstallService(null); + calls = []; + startReply = () => {'started': true, 'error': null}; + status = {'running': true, 'lastError': null}; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + switch (call.method) { + case 'start': + return startReply(); + case 'status': + return status; + default: + return null; + } + }); + }); + + tearDown(() { + messenger.setMockMethodCallHandler(channel, null); + BackgroundServiceManager.debugInstallService(null); + debugDefaultTargetPlatformOverride = null; + }); + + test('the service follows the connection on Android only', () { + expect(BackgroundServiceManager.followsConnection, isTrue); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + expect(BackgroundServiceManager.followsConnection, isFalse); + }); + + test('a start the caller no longer wants sends nothing', () { + fakeAsync((async) { + BackgroundServiceManager.startService( + title: 'T', body: 'B', mayStart: () => false); + async.flushMicrotasks(); + expect(calls, isEmpty); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a start sends the content and keepAwake, then counts as running', + () { + fakeAsync((async) { + BackgroundServiceManager.startService( + title: 'T', body: 'B', keepAwake: true, mayStart: () => true); + async.flushMicrotasks(); + expect(methods(), ['start']); + expect(calls.single.arguments, + {'title': 'T', 'body': 'B', 'keepAwake': true}); + expect(BackgroundServiceManager.isRunning, isTrue); + }); + }); + + test('keepAwake defaults to false, so existing callers stay as they are', + () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(calls.single.arguments, + {'title': 'T', 'body': 'B', 'keepAwake': false}); + }); + }); + + test('a refused start leaves the service counted as stopped', () { + fakeAsync((async) { + final logs = captureLogs(); + startReply = () => {'started': false, 'error': 'X'}; + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(BackgroundServiceManager.isRunning, isFalse); + expect(logs.join('\n'), contains('X')); + }); + }); + + test('a start whose channel call fails does not throw', () { + fakeAsync((async) { + startReply = () => throw PlatformException(code: 'boom'); + Object? error; + BackgroundServiceManager.startService(title: 'T', body: 'B') + .catchError((Object e) => error = e); + async.flushMicrotasks(); + expect(error, isNull); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a stop is always sent, even with nothing counted as running', () { + fakeAsync((async) { + // A stop that lands while a start is still on its way to the service. + expect(BackgroundServiceManager.isRunning, isFalse); + BackgroundServiceManager.stopService(); + async.flushMicrotasks(); + expect(methods(), ['stop']); + }); + }); + + test('a stop clears the running flag', () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(BackgroundServiceManager.isRunning, isTrue); + BackgroundServiceManager.stopService(); + async.flushMicrotasks(); + expect(methods(), ['start', 'stop']); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a start reply that lands after a stop does not count as running', () { + fakeAsync((async) { + final reply = Completer(); + startReply = () => reply.future; + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(methods(), ['start']); + + BackgroundServiceManager.stopService(); + async.flushMicrotasks(); + reply.complete({'started': true, 'error': null}); + async.flushMicrotasks(); + + expect(methods(), ['start', 'stop']); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a stop that fails on the channel does not throw', () { + fakeAsync((async) { + messenger.setMockMethodCallHandler( + channel, (call) async => throw PlatformException(code: 'boom')); + Object? error; + BackgroundServiceManager.stopService() + .catchError((Object e) => error = e); + async.flushMicrotasks(); + expect(error, isNull); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('two identical updates send one', () { + fakeAsync((async) { + BackgroundServiceManager.updateNotification( + title: 'T', body: 'B', keepAwake: true); + BackgroundServiceManager.updateNotification( + title: 'T', body: 'B', keepAwake: true); + async.flushMicrotasks(); + expect(methods(), ['update']); + expect(calls.single.arguments, + {'title': 'T', 'body': 'B', 'keepAwake': true}); + }); + }); + + test('a changed update is sent', () { + fakeAsync((async) { + BackgroundServiceManager.updateNotification(title: 'T', body: 'B'); + BackgroundServiceManager.updateNotification(title: 'T', body: 'C'); + async.flushMicrotasks(); + expect(count('update'), 2); + }); + }); + + test('a stop or a start lets the same update through again', () { + fakeAsync((async) { + BackgroundServiceManager.updateNotification(title: 'T', body: 'B'); + BackgroundServiceManager.stopService(); + BackgroundServiceManager.updateNotification(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(count('update'), 2, reason: 'reset by the stop'); + + BackgroundServiceManager.startService(title: 'S', body: 'S'); + async.flushMicrotasks(); + BackgroundServiceManager.updateNotification(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(count('update'), 3, reason: 'reset by the start'); + }); + }); + + test('a resume finds the service gone and counts it as stopped', () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(BackgroundServiceManager.isRunning, isTrue); + + status = {'running': false, 'lastError': null}; + BackgroundServiceManager.healAfterResume(sessionActive: true); + async.flushMicrotasks(); + expect(BackgroundServiceManager.isRunning, isFalse); + expect(count('stop'), 0); + }); + }); + + test('a resume with no radio session stops a running service', () { + fakeAsync((async) { + status = {'running': true, 'lastError': null}; + BackgroundServiceManager.healAfterResume(sessionActive: false); + async.flushMicrotasks(); + expect(methods(), ['status', 'stop']); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a resume keeps a service the radio session still needs', () { + fakeAsync((async) { + status = {'running': true, 'lastError': null}; + BackgroundServiceManager.healAfterResume(sessionActive: true); + async.flushMicrotasks(); + expect(methods(), ['status']); + expect(BackgroundServiceManager.isRunning, isTrue); + }); + }); + + test('a resume reports an error the service left behind', () { + fakeAsync((async) { + final logs = captureLogs(); + status = {'running': false, 'lastError': 'SecurityException: denied'}; + BackgroundServiceManager.healAfterResume(sessionActive: true); + async.flushMicrotasks(); + expect(logs.join('\n'), + contains('[BACKGROUND] Service failed to start: SecurityException: ' + 'denied')); + }); + }); + + test('the startup cleanup sends stop', () { + fakeAsync((async) { + BackgroundServiceManager.cleanupOrphanedService(); + async.flushMicrotasks(); + expect(methods(), ['stop']); + }); + }); + + test('a live stop sends stop', () { + fakeAsync((async) { + var done = false; + BackgroundServiceManager.stopLiveService('exit app') + .then((_) => done = true); + async.flushMicrotasks(); + expect(methods(), ['stop']); + expect(done, isTrue); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('the status check reports a start that failed in the service', () { + fakeAsync((async) { + final logs = captureLogs(); + status = { + 'running': false, + 'lastError': 'ForegroundServiceStartNotAllowedException: background', + }; + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.flushMicrotasks(); + expect(BackgroundServiceManager.isRunning, isTrue); + + async.elapse(const Duration(milliseconds: 1400)); + expect(count('status'), 0, reason: 'not before about 1500 ms'); + async.elapse(const Duration(milliseconds: 200)); + expect(count('status'), 1); + expect( + logs.join('\n'), + contains('[BACKGROUND] Service failed to start: ' + 'ForegroundServiceStartNotAllowedException: background')); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('the status check logs nothing when there is no error', () { + fakeAsync((async) { + final logs = captureLogs(); + status = {'running': true, 'lastError': null}; + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.elapse(const Duration(seconds: 2)); + expect(count('status'), 1); + expect(logs.join('\n'), isNot(contains('Service failed to start'))); + expect(BackgroundServiceManager.isRunning, isTrue); + }); + }); + + test('the status check is skipped after a stop', () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'T', body: 'B'); + async.elapse(const Duration(milliseconds: 500)); + BackgroundServiceManager.stopService(); + async.elapse(const Duration(seconds: 5)); + expect(count('status'), 0); + }); + }); + + test('the status check is skipped after another start', () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'A', body: 'a'); + async.elapse(const Duration(milliseconds: 1000)); + BackgroundServiceManager.startService(title: 'B', body: 'b'); + async.elapse(const Duration(milliseconds: 1000)); + expect(count('status'), 0, reason: 'the first start check is skipped'); + async.elapse(const Duration(seconds: 1)); + expect(count('status'), 1, reason: 'only the second start checks'); + }); + }); + }); + + group('BackgroundServiceManager on the iOS plugin path', () { + late _FakeService fake; + late List channelCalls; + + setUp(() { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + fake = _FakeService(); + BackgroundServiceManager.debugInstallService(fake); + channelCalls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + channelCalls.add(call); + return null; + }); + }); + + tearDown(() { + messenger.setMockMethodCallHandler(channel, null); + BackgroundServiceManager.debugInstallService(null); + debugDefaultTargetPlatformOverride = null; + }); + + test('a start and a stop go to the plugin, never the session channel', () { + fakeAsync((async) { + BackgroundServiceManager.startService(title: 'A', body: 'a'); + async.flushMicrotasks(); + expect(fake.starts, 1); + expect(BackgroundServiceManager.isRunning, isTrue); + + BackgroundServiceManager.stopService(); + async.flushMicrotasks(); + expect(fake.invoked.last, 'stop'); + expect(BackgroundServiceManager.isRunning, isFalse); + expect(channelCalls, isEmpty); + }); + }); + + test('a stop that arrives during a start is still honoured', () { + fakeAsync((async) { + // The disconnect lands while the plugin is still starting the service. + fake.onStart = () => BackgroundServiceManager.stopService(); + BackgroundServiceManager.startService(title: 'A', body: 'a'); + async.flushMicrotasks(); + expect(fake.starts, 1); + expect(fake.invoked.last, 'stop'); + expect(BackgroundServiceManager.isRunning, isFalse); + }); + }); + + test('a live stop leaves iOS alone', () { + fakeAsync((async) { + fake.running = true; + BackgroundServiceManager.stopLiveService('exit app'); + async.flushMicrotasks(); + expect(fake.invoked, isEmpty); + expect(channelCalls, isEmpty); + }); + }); + }); + + group('Android manifest', () { + // Comments stripped: they name the removed permissions on purpose. + final manifest = File('android/app/src/main/AndroidManifest.xml') + .readAsStringSync() + .replaceAll(RegExp(r'', dotAll: true), ''); + + /// Every element with this tag, as its opening tag's source text. + List elements(String tag) => RegExp('<$tag\\b[^>]*>') + .allMatches(manifest) + .map((m) => m.group(0)!) + .toList(); + + String attribute(String element, String name) => + RegExp('$name="([^"]*)"').firstMatch(element)?.group(1) ?? ''; + + test('the session service is foreground, private and ends with the task', + () { + final service = elements('service').singleWhere( + (s) => attribute(s, 'android:name') == '.MeshMapperSessionService'); + expect( + attribute(service, 'android:foregroundServiceType') + .split('|') + .toSet(), + {'location', 'connectedDevice'}, + reason: 'Android throws when startForeground asks for a type the ' + 'manifest does not declare for the service', + ); + expect(attribute(service, 'android:stopWithTask'), 'true', + reason: 'swiping the app away must end the session'); + expect(attribute(service, 'android:exported'), 'false'); + }); + + test("the plugin's service and receivers are removed", () { + const removed = [ + 'id.flutter.flutter_background_service.BackgroundService', + 'id.flutter.flutter_background_service.WatchdogReceiver', + 'id.flutter.flutter_background_service.BootReceiver', + ]; + final components = [...elements('service'), ...elements('receiver')]; + for (final name in removed) { + final element = components + .where((e) => attribute(e, 'android:name') == name) + .toList(); + expect(element, hasLength(1), reason: name); + expect(attribute(element.single, 'tools:node'), 'remove', + reason: '$name would merge back in from the plugin'); + } + }); + + test('background location is removed so no plugin merges it back', () { + final permission = elements('uses-permission').singleWhere((p) => + attribute(p, 'android:name') == + 'android.permission.ACCESS_BACKGROUND_LOCATION'); + expect(attribute(permission, 'tools:node'), 'remove', + reason: 'the session service keeps GPS running in the background ' + 'with while-in-use permission'); + }); + + test('neither dataSync nor the boot permission is granted', () { + final permissions = elements('uses-permission'); + String? node(String permission) => permissions + .where((p) => + attribute(p, 'android:name') == 'android.permission.$permission') + .map((p) => attribute(p, 'tools:node')) + .firstOrNull; + + expect(node('FOREGROUND_SERVICE_DATA_SYNC'), isNull, + reason: 'no service starts with dataSync any more'); + expect(node('RECEIVE_BOOT_COMPLETED'), 'remove', + reason: 'only the plugin adds it, for the boot start that is gone'); + expect(manifest, isNot(contains('dataSync'))); + }); + }); +} + +class _FakeService implements FlutterBackgroundService { + bool running = false; + int starts = 0; + void Function()? onStart; + final List invoked = []; + + @override + Future startService() async { + starts++; + running = true; + onStart?.call(); + return true; + } + + @override + Future isRunning() async => running; + + @override + void invoke(String method, [Map? arg]) { + invoked.add(method); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/test/services/bluetooth/gatt_busy_retry_test.dart b/test/services/bluetooth/gatt_busy_retry_test.dart new file mode 100644 index 00000000..5b6172fe --- /dev/null +++ b/test/services/bluetooth/gatt_busy_retry_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/bluetooth/mobile_bluetooth.dart'; + +void main() { + const busy = 'gatt.writeCharacteristic() returned 201 : ' + 'ERROR_GATT_WRITE_REQUEST_BUSY'; + Future noSleep(Duration _) async {} + + test('retries a busy write until it goes out', () async { + var calls = 0; + await writeRetryingGattBusy(() async { + calls++; + if (calls < 3) throw Exception(busy); + }, sleep: noSleep); + expect(calls, 3); + }); + + test('gives up after the last retry with the original error', () async { + var calls = 0; + await expectLater( + writeRetryingGattBusy(() async { + calls++; + throw Exception(busy); + }, sleep: noSleep), + throwsA(predicate((Object? e) => e != null && isGattWriteBusy(e))), + ); + expect(calls, kGattBusyRetryDelays.length + 1); + }); + + test('never retries another error', () async { + var calls = 0; + await expectLater( + writeRetryingGattBusy(() async { + calls++; + throw Exception('device is disconnected'); + }, sleep: noSleep), + throwsException, + ); + expect(calls, 1); + }); +} diff --git a/test/services/border_loader_test.dart b/test/services/border_loader_test.dart new file mode 100644 index 00000000..c3026c62 --- /dev/null +++ b/test/services/border_loader_test.dart @@ -0,0 +1,465 @@ +import 'dart:async'; + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:mesh_mapper/services/border_loader.dart'; + +/// The NZ group's `/border` answer is 4.8 MB and phones needed 11 to 161 s +/// for it. With a 10 s timeout and no memory of the failure, every 60 s zone +/// check started another download on top of the last (one phone pulled 41 of +/// them in 45 minutes). These tests pin the rules that stop that. +class _MemoryCache implements BorderCacheStore { + final Map entries = {}; + int hashReads = 0; + int reads = 0; + int writes = 0; + + @override + Future hashFor(String contextKey) async { + hashReads++; + return entries[contextKey]?.$1; + } + + @override + Future read(String contextKey, String borderHash) async { + reads++; + final entry = entries[contextKey]; + return entry != null && entry.$1 == borderHash ? entry.$2 : null; + } + + @override + Future write( + String contextKey, String borderHash, BorderPolygons polygons) async { + writes++; + entries[contextKey] = (borderHash, polygons); + } +} + +BorderPolygons _polygons(String code) => [ + { + 'code': code, + 'polygon': [ + [1.0, 2.0], + [3.0, 4.0], + ], + }, + ]; + +void main() { + late DateTime now; + late _MemoryCache cache; + late BorderLoader loader; + late int fetches; + + setUp(() { + now = DateTime.utc(2026, 10, 24, 12); + cache = _MemoryCache(); + loader = BorderLoader(cache: cache, now: () => now); + fetches = 0; + }); + + /// A `/border` answer; [hash] is the body's own `border_hash`, which only + /// a complete answer carries. Most tests send it equal to the /status hash. + Future Function() answer(BorderPolygons? result, + {String? hash}) => + () async { + fetches++; + return result == null ? null : BorderAnswer(result, borderHash: hash); + }; + + group('without border_hash (old server)', () { + test('loads once per context and never asks again while loaded', + () async { + final first = await loader.ensure( + contextKey: 'NZ', fetch: answer(_polygons('AKL'))); + expect(first, isNotNull); + for (var i = 0; i < 5; i++) { + now = now.add(const Duration(minutes: 1)); + expect( + await loader.ensure( + contextKey: 'NZ', fetch: answer(_polygons('AKL'))), + isNull); + } + expect(fetches, 1); + expect(cache.reads, 0); + expect(cache.writes, 0); + }); + + test('a new context loads again, and forget() allows a reload', () async { + await loader.ensure(contextKey: 'NZ', fetch: answer(_polygons('AKL'))); + await loader.ensure(contextKey: 'YOW', fetch: answer(_polygons('YOW'))); + expect(fetches, 2); + loader.forget(); + await loader.ensure(contextKey: 'YOW', fetch: answer(_polygons('YOW'))); + expect(fetches, 3); + }); + }); + + group('backoff after a failed or empty answer', () { + test('waits 5, then 15, then 30 minutes, capped at 30', () async { + final pauses = []; + for (var round = 0; round < 4; round++) { + await loader.ensure(contextKey: 'NZ', fetch: answer(null)); + pauses.add(loader.retryAt!.difference(now)); + + // Zone checks every minute before the pause ends ask nothing. + final before = fetches; + var t = now; + while (true) { + t = t.add(const Duration(minutes: 1)); + if (!t.isBefore(loader.retryAt!)) break; + now = t; + await loader.ensure(contextKey: 'NZ', fetch: answer(null)); + } + expect(fetches, before); + now = loader.retryAt!; + } + expect(pauses, const [ + Duration(minutes: 5), + Duration(minutes: 15), + Duration(minutes: 30), + Duration(minutes: 30), + ]); + expect(fetches, 4); + }); + + test('an empty polygon list counts as a failure', () async { + await loader.ensure(contextKey: 'NZ', fetch: answer(const [])); + expect(loader.retryAt, now.add(const Duration(minutes: 5))); + expect(loader.loadedKey, isNull); + }); + + test('a context change resets the backoff', () async { + await loader.ensure(contextKey: 'NZ', fetch: answer(null)); + final result = + await loader.ensure(contextKey: 'YOW', fetch: answer(_polygons('Y'))); + expect(result, isNotNull); + expect(fetches, 2); + }); + + test('a border_hash change resets the backoff', () async { + await loader.ensure( + contextKey: 'NZ', borderHash: 'a', fetch: answer(null)); + await loader.ensure( + contextKey: 'NZ', borderHash: 'b', fetch: answer(_polygons('AKL'))); + expect(fetches, 2); + }); + + test('a success clears the backoff', () async { + await loader.ensure(contextKey: 'NZ', fetch: answer(null)); + now = loader.retryAt!; + await loader.ensure(contextKey: 'NZ', fetch: answer(_polygons('AKL'))); + expect(loader.retryAt, isNull); + // A later failure in another context starts the schedule from 5 min. + await loader.ensure(contextKey: 'YOW', fetch: answer(null)); + expect(loader.retryAt, now.add(const Duration(minutes: 5))); + }); + }); + + group('one request at a time', () { + test('zone checks during a slow download start no second one', () async { + final slow = Completer(); + final first = loader.ensure( + contextKey: 'NZ', + fetch: () { + fetches++; + return slow.future; + }); + expect(loader.fetchInProgress, isTrue); + + for (var i = 0; i < 3; i++) { + now = now.add(const Duration(minutes: 1)); + expect(await loader.ensure(contextKey: 'NZ', fetch: answer(null)), + isNull); + expect(await loader.ensure(contextKey: 'YOW', fetch: answer(null)), + isNull); + } + expect(fetches, 1); + + slow.complete(BorderAnswer(_polygons('AKL'))); + expect(await first, isNotNull); + expect(loader.fetchInProgress, isFalse); + }); + + test('the guard clears when the request fails', () async { + final slow = Completer(); + final first = loader.ensure(contextKey: 'NZ', fetch: () => slow.future); + slow.complete(null); + await first; + expect(loader.fetchInProgress, isFalse); + }); + }); + + group('border_hash cache', () { + test('a hash hit uses the cache and skips /border', () async { + cache.entries['NZ'] = ('h1', _polygons('AKL')); + final result = await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(_polygons('X'))); + expect(result, _polygons('AKL')); + expect(fetches, 0); + expect(loader.loadedKey, 'NZ'); + }); + + test('a hash miss fetches and saves under the new hash', () async { + cache.entries['NZ'] = ('old', _polygons('OLD')); + final result = await loader.ensure( + contextKey: 'NZ', + borderHash: 'new', + fetch: answer(_polygons('AKL'), hash: 'new')); + expect(result, _polygons('AKL')); + expect(fetches, 1); + expect(cache.entries['NZ']!.$1, 'new'); + }); + + test('a changed hash for the loaded context fetches again', () async { + await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(_polygons('A'))); + expect( + await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(_polygons('A'))), + isNull); + final result = await loader.ensure( + contextKey: 'NZ', borderHash: 'h2', fetch: answer(_polygons('B'))); + expect(result, _polygons('B')); + expect(fetches, 2); + }); + + test('moving back to a cached context reads the cache, not /border', + () async { + await loader.ensure( + contextKey: 'NZ', + borderHash: 'n', + fetch: answer(_polygons('AKL'), hash: 'n')); + await loader.ensure( + contextKey: 'YOW', + borderHash: 'y', + fetch: answer(_polygons('YOW'), hash: 'y')); + final back = await loader.ensure( + contextKey: 'NZ', borderHash: 'n', fetch: answer(_polygons('X'))); + expect(back, _polygons('AKL')); + expect(fetches, 2); + }); + + test('a known miss is not read again during the backoff', () async { + await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(null)); + expect(cache.hashReads, 1); + for (var i = 0; i < 4; i++) { + now = now.add(const Duration(minutes: 1)); + await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(null)); + } + expect(cache.hashReads, 1); + expect(cache.reads, 0); + expect(fetches, 1); + }); + + test('a hash mismatch never reads the polygons', () async { + cache.entries['NZ'] = ('old', _polygons('OLD')); + await loader.ensure( + contextKey: 'NZ', borderHash: 'new', fetch: answer(null)); + expect(cache.hashReads, 1); + expect(cache.reads, 0); + }); + + test('an answer without a body hash is shown but never saved', () async { + final result = await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(_polygons('AKL'))); + expect(result, _polygons('AKL')); + expect(cache.writes, 0); + // Loaded in memory: the next zone checks ask nothing. + for (var i = 0; i < 3; i++) { + now = now.add(const Duration(minutes: 1)); + expect( + await loader.ensure( + contextKey: 'NZ', + borderHash: 'h1', + fetch: answer(_polygons('AKL'))), + isNull); + } + expect(fetches, 1); + }); + + test('an answer is saved under its own body hash', () async { + // The border changed between /status and /border. + await loader.ensure( + contextKey: 'NZ', + borderHash: 'h1', + fetch: answer(_polygons('AKL'), hash: 'h2')); + expect(cache.entries['NZ']!.$1, 'h2'); + // Same /status hash again: still loaded, no request. + await loader.ensure( + contextKey: 'NZ', borderHash: 'h1', fetch: answer(_polygons('X'))); + expect(fetches, 1); + // /status catches up: served from the cache. + final next = await loader.ensure( + contextKey: 'NZ', borderHash: 'h2', fetch: answer(_polygons('X'))); + expect(next, _polygons('AKL')); + expect(fetches, 1); + }); + + test('an empty status hash counts as none', () async { + await loader.ensure( + contextKey: 'NZ', borderHash: '', fetch: answer(_polygons('AKL'))); + expect(cache.hashReads, 0); + expect( + await loader.ensure( + contextKey: 'NZ', fetch: answer(_polygons('AKL'))), + isNull); + expect(fetches, 1); + }); + + test('onStale runs only before a request for another context', () async { + var stale = 0; + await loader.ensure( + contextKey: 'NZ', + borderHash: 'n', + fetch: answer(_polygons('AKL')), + onStale: () => stale++); + expect(stale, 1); + // Same context, new hash: the old borders stay until the new arrive. + await loader.ensure( + contextKey: 'NZ', + borderHash: 'n2', + fetch: answer(_polygons('AKL')), + onStale: () => stale++); + expect(stale, 1); + // Another context served from the cache: nothing to clear. + cache.entries['YOW'] = ('y', _polygons('YOW')); + await loader.ensure( + contextKey: 'YOW', + borderHash: 'y', + fetch: answer(null), + onStale: () => stale++); + expect(stale, 1); + }); + }); + + group('returning to a context', () { + test('A ok, B fails, A again shows A', () async { + var shown = >[]; + void clear() => shown = []; + + shown = (await loader.ensure( + contextKey: 'A', fetch: answer(_polygons('A')), onStale: clear))!; + expect(shown, _polygons('A')); + + expect( + await loader.ensure( + contextKey: 'B', fetch: answer(null), onStale: clear), + isNull); + expect(shown, isEmpty); + + final back = await loader.ensure( + contextKey: 'A', fetch: answer(_polygons('A')), onStale: clear); + expect(back, _polygons('A')); + expect(fetches, 3); + }); + + test('A ok, B empty, A again comes from the cache', () async { + await loader.ensure( + contextKey: 'A', + borderHash: 'a', + fetch: answer(_polygons('A'), hash: 'a'), + onStale: () {}); + await loader.ensure( + contextKey: 'B', + borderHash: 'b', + fetch: answer(const []), + onStale: () {}); + final back = await loader.ensure( + contextKey: 'A', + borderHash: 'a', + fetch: answer(_polygons('X')), + onStale: () {}); + expect(back, _polygons('A')); + expect(fetches, 2); + }); + }); + + group('answers for another place', () { + test('a rejected answer is not shown, not saved, and backs off', + () async { + final result = await loader.ensure( + contextKey: 'YOW', + borderHash: 'y', + fetch: answer(_polygons('YUL'), hash: 'y'), + accept: (p) => bordersFitZone(p, zoneCode: 'YOW')); + expect(result, isNull); + expect(cache.writes, 0); + expect(loader.loadedKey, isNull); + expect(loader.retryAt, now.add(const Duration(minutes: 5))); + }); + + test('bordersFitZone needs the zone and, in a group, only members', () { + final group = [..._polygons('AKL'), ..._polygons('WLG')]; + expect(bordersFitZone(_polygons('akl'), zoneCode: 'AKL'), isTrue); + expect(bordersFitZone(_polygons('YOW'), zoneCode: 'AKL'), isFalse); + expect( + bordersFitZone(group, + zoneCode: 'AKL', groupMembers: const ['AKL', 'WLG', 'CHC']), + isTrue); + expect( + bordersFitZone([...group, ..._polygons('YOW')], + zoneCode: 'AKL', groupMembers: const ['AKL', 'WLG']), + isFalse); + expect( + bordersFitZone(_polygons('WLG'), + zoneCode: 'AKL', groupMembers: const ['AKL', 'WLG']), + isFalse); + }); + }); + + group('HiveBorderCacheStore', () { + late Directory dir; + late int clock; + late HiveBorderCacheStore store; + + setUp(() async { + dir = await Directory.systemTemp.createTemp('border_cache_test'); + Hive.init(dir.path); + clock = 1000; + store = HiveBorderCacheStore( + now: () => DateTime.fromMillisecondsSinceEpoch(clock++)); + }); + + tearDown(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('round-trips polygons under their hash', () async { + await store.write('NZ', 'h1', _polygons('AKL')); + expect(await store.hashFor('NZ'), 'h1'); + expect(await store.read('NZ', 'h1'), _polygons('AKL')); + expect(await store.read('NZ', 'h2'), isNull); + expect(await store.hashFor('YOW'), isNull); + }); + + test('keeps the four newest contexts', () async { + for (final key in ['A', 'B', 'C', 'D', 'E']) { + await store.write(key, 'h$key', _polygons(key)); + } + expect(await store.hashFor('A'), isNull); + for (final key in ['B', 'C', 'D', 'E']) { + expect(await store.hashFor(key), 'h$key'); + } + final box = await Hive.openLazyBox(HiveBorderCacheStore.boxName); + expect(box.keys.toSet(), {'B', 'C', 'D', 'E'}); + }); + + test('a malformed saved_at is evicted first, not a stop to eviction', + () async { + for (final key in ['A', 'B', 'C', 'D']) { + await store.write(key, 'h$key', _polygons(key)); + } + final index = await Hive.openBox(HiveBorderCacheStore.indexBoxName); + await index.put('C', {'hash': 'hC', 'saved_at': 'yesterday'}); + await store.write('E', 'hE', _polygons('E')); + await store.write('F', 'hF', _polygons('F')); + expect(index.keys.toSet(), {'B', 'D', 'E', 'F'}); + }); + }); +} diff --git a/test/services/custom_api_service_test.dart b/test/services/custom_api_service_test.dart index 99db9af5..280a629b 100644 --- a/test/services/custom_api_service_test.dart +++ b/test/services/custom_api_service_test.dart @@ -86,6 +86,37 @@ void main() { }); }); + test('a SCOPES item forwards with the rest of the batch, contact and iata ' + 'added, auto_mode absent, fields otherwise unchanged', () async { + final t = build(); + t.svc.forwardPings([ + { + 'type': 'SCOPES', + 'public_key': + 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2', + 'scopes': ['ROOM1', '*'], + 'timestamp': 1757400000, + 'lat': 45.26974, + 'lon': -75.77746, + }, + {'type': 'DISC', 'lat': 45.0, 'lon': -75.0, 'auto_mode': 'passive'}, + ]); + final sent = await t.sent.timeout(const Duration(seconds: 5)); + expect(sent, hasLength(2)); + final scopesItem = sent.firstWhere((p) => p['type'] == 'SCOPES'); + expect(scopesItem, { + 'type': 'SCOPES', + 'public_key': + 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2', + 'scopes': ['ROOM1', '*'], + 'timestamp': 1757400000, + 'lat': 45.26974, + 'lon': -75.77746, + 'contact': 'D873B1F2', + 'iata': 'YOW', + }); + }); + test('the caller\'s list is not mutated', () async { final t = build(); final original = [ @@ -95,4 +126,42 @@ void main() { await t.sent.timeout(const Duration(seconds: 5)); expect(original.single['auto_mode'], 'active'); }); + + test('a bare altitude is stripped from a forwarded item, nothing else is', + () async { + final t = build(); + t.svc.forwardPings([ + { + 'type': 'TX', + 'lat': 45.0, + 'lon': -75.0, + 'altitude': 84, + 'altitude_acc': 5, + 'noisefloor': -103, + }, + ]); + final sent = await t.sent.timeout(const Duration(seconds: 5)); + expect(sent.single.containsKey('altitude'), isFalse); + expect(sent.single.containsKey('altitude_acc'), isFalse); + expect(sent.single['noisefloor'], -103); + }); + + test('the altitude trio is kept on every forwarded item', () async { + final t = build(); + t.svc.forwardPings([ + { + 'type': 'TX', + 'lat': 45.0, + 'lon': -75.0, + 'altitude': 84, + 'altitude_ref': 'msl', + 'altitude_acc': 6, + 'auto_mode': 'active', + }, + ]); + final sent = await t.sent.timeout(const Duration(seconds: 5)); + expect(sent.single['altitude'], 84); + expect(sent.single['altitude_ref'], 'msl'); + expect(sent.single['altitude_acc'], 6); + }); } diff --git a/test/services/debug_file_logger_capture_test.dart b/test/services/debug_file_logger_capture_test.dart new file mode 100644 index 00000000..7335f64c --- /dev/null +++ b/test/services/debug_file_logger_capture_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/debug_file_logger.dart'; + +/// Startup lines are held in memory until the stored preference says whether +/// a log file should exist at all. Before this the app opened a file on every +/// launch and closed it again when the preference read off, leaving one stub +/// file per launch that all surfaced the moment the user turned logging on. +void main() { + tearDown(DebugFileLogger.discardCapture); + + test('a write before capture starts is dropped', () { + DebugFileLogger.write('LOG', '[APP] too early'); + expect(DebugFileLogger.pendingLogCount, 0); + }); + + test('capture buffers lines with their level and scrubs them', () { + DebugFileLogger.beginCapture(); + DebugFileLogger.write('LOG', '[APP] MeshMapper starting...'); + DebugFileLogger.write('WARN', 'Authorization: Bearer ${'a' * 64}'); + expect(DebugFileLogger.pendingLogCount, 2); + final lines = DebugFileLogger.pendingLogsForTest; + expect(lines[0], contains('LOG: [APP] MeshMapper starting...')); + expect(lines[1], contains('WARN: Authorization: Bearer ')); + expect(lines[1], isNot(contains('a' * 64))); + }); + + test('discarding the capture empties it and later writes are dropped', () { + DebugFileLogger.beginCapture(); + DebugFileLogger.write('LOG', '[APP] one'); + DebugFileLogger.discardCapture(); + expect(DebugFileLogger.pendingLogCount, 0); + DebugFileLogger.write('LOG', '[APP] two'); + expect(DebugFileLogger.pendingLogCount, 0); + }); + + test('the capture is capped', () { + DebugFileLogger.beginCapture(); + for (var i = 0; i < 600; i++) { + DebugFileLogger.write('LOG', '[APP] line $i'); + } + expect(DebugFileLogger.pendingLogCount, DebugFileLogger.maxPendingLogs); + expect(DebugFileLogger.pendingLogsForTest.first, contains('line 0')); + }); + + test('only a stored false turns file logging off', () { + expect(DebugFileLogger.wantsFileLogging(null), isTrue); + expect(DebugFileLogger.wantsFileLogging(true), isTrue); + expect(DebugFileLogger.wantsFileLogging('stray'), isTrue); + expect(DebugFileLogger.wantsFileLogging(false), isFalse); + }); + + test('a legacy startup stub is recognised by its exact line', () { + const stub = '=== MeshMapper Debug Log Started: 2026-10-08T06:22:00 ===\n' + '=== App APP-1.4.0 | iOS 18.5 ===\n\n' + '[2026-10-08T06:22:00] LOG: [APP] MeshMapper starting...\n' + '[2026-10-08T06:22:01] LOG: [INIT] Debug logs disabled by user preference, turning off\n' + '\n=== MeshMapper Debug Log Stopped: 2026-10-08T06:22:01 ===\n'; + expect(DebugFileLogger.isStartupStubContent(stub), isTrue); + }); + + test('a real log and the new wording are not stubs', () { + const real = '=== MeshMapper Debug Log Started ===\n' + '[t] LOG: [APP] MeshMapper starting...\n' + '[t] LOG: [INIT] Debug logging enabled (APP-1.4.0)\n' + '[t] LOG: [BLE] Connected\n'; + expect(DebugFileLogger.isStartupStubContent(real), isFalse); + const reworded = '[t] LOG: [INIT] File logging stopped: preference is off\n'; + expect(DebugFileLogger.isStartupStubContent(reworded), isFalse); + }); +} diff --git a/test/services/debug_submit_service_upload_test.dart b/test/services/debug_submit_service_upload_test.dart new file mode 100644 index 00000000..1cfd95e8 --- /dev/null +++ b/test/services/debug_submit_service_upload_test.dart @@ -0,0 +1,202 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/debug_submit_service.dart'; + +/// A dropped upload answer followed by "Session Closed" means the file most +/// likely landed. The app lets upload-complete (and its hash check) decide +/// instead of failing the whole upload and never sending the user's notes. +void main() { + late Directory dir; + late File file; + + setUp(() async { + dir = await Directory.systemTemp.createTemp('debug_submit_test'); + file = File('${dir.path}/debug_log.txt'); + await file.writeAsString('line one\nline two\n'); + }); + + tearDown(() async { + await dir.delete(recursive: true); + }); + + http.Response json200(Map body) => + http.Response(json.encode(body), 200); + + final sessionBody = { + 'upload_url': 'https://meshmapper.net/debug/upload/abc', + 'session_id': 'abc', + 'expires_at': 0, + }; + + /// Builds a service whose server answers request-upload with a session, + /// each upload attempt with the next entry of [uploads] (an exception is + /// thrown, a response is returned), and upload-complete with [complete]. + ({DebugSubmitService service, List calls, List notes}) + build({ + required List uploads, + required Map complete, + }) { + final calls = []; + final notes = []; + var uploadIndex = 0; + final client = MockClient((request) async { + final path = request.url.path; + if (path.endsWith('/request-upload')) { + calls.add('request'); + return json200(sessionBody); + } + if (path.endsWith('/upload-complete')) { + calls.add('complete'); + notes.add((json.decode(request.body) as Map)['user_notes']); + return json200(complete); + } + if (path.endsWith('/upload/abc')) { + calls.add('upload'); + final next = uploads[uploadIndex++]; + if (next is Exception) throw next; + return next as http.Response; + } + throw StateError('unexpected $path'); + }); + return ( + service: DebugSubmitService( + client: client, retryDelayUnit: const Duration(milliseconds: 1)), + calls: calls, + notes: notes, + ); + } + + Future upload(DebugSubmitService service) => + service.uploadDebugFileOnly( + file: file, + deviceId: 'dev', + publicKey: 'AB' * 32, + appVersion: '1.4.2', + devicePlatform: 'ios', + userNotes: 'my notes', + ); + + final sessionClosed = + http.Response(json.encode({'message': 'Session Closed'}), 400); + + test('session closed after a dropped attempt goes on to upload-complete', + () async { + final h = build( + uploads: [http.ClientException('connection reset'), sessionClosed], + complete: {'success': true, 'hash_match': true}, + ); + + expect(await upload(h.service), isTrue); + expect(h.calls, ['request', 'upload', 'upload', 'complete']); + expect(h.notes, ['my notes']); + }); + + test('that path still fails when upload-complete does not confirm', + () async { + final h = build( + uploads: [http.ClientException('connection reset'), sessionClosed], + complete: {'success': false, 'message': 'Hash mismatch'}, + ); + + expect(await upload(h.service), isFalse); + expect(h.calls, ['request', 'upload', 'upload', 'complete']); + }); + + // A closed session takes no more uploads, so retrying it only waits out + // the backoff before failing anyway. + test('session closed with no earlier dropped attempt fails at once', + () async { + final h = build( + uploads: [sessionClosed, sessionClosed, sessionClosed], + complete: {'success': true}, + ); + + expect(await upload(h.service), isFalse); + expect(h.calls, ['request', 'upload']); + }); + + test('session closed after a refusal fails without another attempt', + () async { + final h = build( + uploads: [ + http.Response(json.encode({'message': 'Server error'}), 500), + sessionClosed, + sessionClosed, + ], + complete: {'success': true}, + ); + + expect(await upload(h.service), isFalse); + expect(h.calls, ['request', 'upload', 'upload']); + }); + + test('a plain successful upload is unchanged', () async { + final h = build( + uploads: [json200({'success': true})], + complete: {'success': true}, + ); + + expect(await upload(h.service), isTrue); + expect(h.calls, ['request', 'upload', 'complete']); + }); + + group('request-upload retries a transport error', () { + Future request(DebugSubmitService service) => + service.requestUpload( + deviceId: 'dev', + publicKey: 'AB' * 32, + fileSizeBytes: 10, + fileHash: '0' * 64, + appVersion: '1.4.2', + platform: 'ios', + ); + + test('a dropped first attempt is retried', () async { + var calls = 0; + final service = DebugSubmitService( + client: MockClient((_) async { + calls++; + if (calls == 1) throw http.ClientException('connection reset'); + return json200(sessionBody); + }), + retryDelayUnit: const Duration(milliseconds: 1), + ); + + final session = await request(service); + expect(session?.sessionId, 'abc'); + expect(calls, 2); + }); + + test('gives up after three attempts', () async { + var calls = 0; + final service = DebugSubmitService( + client: MockClient((_) async { + calls++; + throw http.ClientException('connection reset'); + }), + retryDelayUnit: const Duration(milliseconds: 1), + ); + + expect(await request(service), isNull); + expect(calls, 3); + }); + + test('a server refusal is not retried', () async { + var calls = 0; + final service = DebugSubmitService( + client: MockClient((_) async { + calls++; + return http.Response('{"message":"Bad"}', 400); + }), + retryDelayUnit: const Duration(milliseconds: 1), + ); + + expect(await request(service), isNull); + expect(calls, 1); + }); + }); +} diff --git a/test/services/fix_altitude_resolver_test.dart b/test/services/fix_altitude_resolver_test.dart new file mode 100644 index 00000000..39a4054c --- /dev/null +++ b/test/services/fix_altitude_resolver_test.dart @@ -0,0 +1,373 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/fix_altitude_resolver.dart'; + +/// The store remembers one answer per exact fix (timestamp, coordinates, +/// altitude, altitude accuracy and the mock flag) under a source generation, resolves Android fixes in the +/// background, and answers unknown for anything it has not finished. + +Position _pos({ + double lat = 45.0, + double lon = -75.0, + int timeMs = 1760000000000, + double altitude = 120.0, + double altitudeAccuracy = 6.0, + bool isMocked = false, +}) => + Position( + latitude: lat, + longitude: lon, + timestamp: DateTime.fromMillisecondsSinceEpoch(timeMs, isUtc: true), + accuracy: 5.0, + altitude: altitude, + altitudeAccuracy: altitudeAccuracy, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 0.0, + isMocked: isMocked, + ); + +NativeAltitudeAnswer _matching(Position p) => NativeAltitudeAnswer(sdk: 34, fixes: [ + NativeFixDescription( + source: 'fused', + timeMs: p.timestamp.millisecondsSinceEpoch, + lat: p.latitude, + lon: p.longitude, + hasAltitude: true, + altitude: p.altitude, + hasVerticalAccuracy: true, + verticalAccuracy: p.altitudeAccuracy, + hasMsl: false, + msl: 0.0, + hasMslAccuracy: false, + mslAccuracy: 0.0, + isMock: false, + ), + ]); + +void main() { + group('synchronous platforms', () { + test('iOS is stored and looked up at once', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + final p = _pos(); + r.track(p); + expect(r.lookup(p).reference, AltitudeReference.msl); + expect(r.lookup(p).meters, 120.0); + }); + + test('a fix never tracked is unknown', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + expect(r.lookup(_pos()).isKnown, isFalse); + }); + + test('a simulated fix is stored as unknown, no native read', () async { + var reads = 0; + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async { + reads++; + return null; + }); + final p = _pos(); + r.track(p, simulated: true); + await r.idle; + expect(r.lookup(p).isKnown, isFalse); + expect(reads, 0); + }); + + test('two fixes with the same timestamp and different coordinates ' + 'are two entries', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + final a = _pos(lat: 45.0, altitude: 100); + final b = _pos(lat: 46.0, altitude: 200); + r.track(a); + r.track(b); + expect(r.lookup(a).meters, 100); + expect(r.lookup(b).meters, 200); + expect(r.size, 2); + }); + + test('the store is capped and evicts the oldest', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios, capacity: 3); + final fixes = [for (var i = 0; i < 4; i++) _pos(timeMs: 1000 * (i + 1))]; + for (final f in fixes) { + r.track(f); + } + expect(r.size, 3); + expect(r.lookup(fixes[0]).isKnown, isFalse); + expect(r.lookup(fixes[3]).isKnown, isTrue); + }); + }); + + group('Android', () { + test('a fix is unknown until the native answer lands, then known ' + '(Review Focus 4)', () async { + final gate = Completer(); + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, readNative: () => gate.future); + r.track(p); + expect(r.lookup(p).isKnown, isFalse, reason: 'nothing waits'); + gate.complete(_matching(p)); + await r.idle; + expect(r.lookup(p).reference, AltitudeReference.ellipsoid); + }); + + test('a native read already in flight for the same fix is not repeated', + () async { + var reads = 0; + final gate = Completer(); + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () { + reads++; + return gate.future; + }); + r.track(p); + r.track(p); + expect(reads, 1); + gate.complete(_matching(p)); + await r.idle; + r.track(p); + expect(reads, 1, reason: 'a stored fix is not re-read either'); + }); + + test('a native read that throws leaves the fix unknown', () async { + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async => throw StateError('channel down')); + r.track(p); + await r.idle; + expect(r.lookup(p).isKnown, isFalse); + }); + + test('a native read that hangs is cut off by the timeout', () async { + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () => Completer().future, + nativeTimeout: const Duration(milliseconds: 20)); + r.track(p); + await r.idle; + expect(r.lookup(p).isKnown, isFalse); + }); + + test('below Android 14 the SDK is remembered and later fixes skip the read', + () async { + var reads = 0; + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async { + reads++; + return const NativeAltitudeAnswer(sdk: 33, fixes: []); + }); + final a = _pos(timeMs: 1000); + final b = _pos(timeMs: 2000); + r.track(a); + await r.idle; + r.track(b); + await r.idle; + expect(reads, 1); + expect(r.lookup(a).reference, AltitudeReference.ellipsoid); + expect(r.lookup(b).reference, AltitudeReference.ellipsoid); + }); + + test('a completion for an older generation is dropped (Review Focus 5)', + () async { + final gate = Completer(); + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, readNative: () => gate.future); + r.track(p); + r.reset(); + gate.complete(_matching(p)); + await r.idle; + expect(r.lookup(p).isKnown, isFalse); + expect(r.size, 0); + }); + + test('reset clears simulator entries so a real fix with the same key ' + 'is resolved afresh (Review Focus 5)', () async { + final p = _pos(); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async => _matching(p)); + r.track(p, simulated: true); + expect(r.lookup(p).isKnown, isFalse); + r.reset(); + r.track(p); + await r.idle; + expect(r.lookup(p).isKnown, isTrue); + expect(r.generation, 1); + }); + + test('eviction follows acceptance order even when reads finish out of ' + 'order', () async { + final gates = >{}; + var calls = 0; + final fixes = [for (var i = 0; i < 3; i++) _pos(timeMs: 1000 * (i + 1))]; + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + capacity: 2, + readNative: () { + final c = Completer(); + gates[calls++] = c; + return c.future; + }); + for (final f in fixes) { + r.track(f); // A, B, C accepted in this order + } + expect(r.size, 2, reason: 'A was evicted the moment C was accepted'); + // Complete C, then B, then A. + gates[2]!.complete(_matching(fixes[2])); + gates[1]!.complete(_matching(fixes[1])); + gates[0]!.complete(_matching(fixes[0])); + await r.idle; + expect(r.lookup(fixes[0]).isKnown, isFalse, + reason: 'a late completion never resurrects an evicted fix'); + expect(r.lookup(fixes[1]).isKnown, isTrue); + expect(r.lookup(fixes[2]).isKnown, isTrue); + expect(r.size, 2); + }); + + test('a fix evicted while its read is out and accepted again is read ' + 'once and stored once', () async { + final gates = >{}; + var calls = 0; + final fixes = [for (var i = 0; i < 3; i++) _pos(timeMs: 1000 * (i + 1))]; + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + capacity: 2, + readNative: () { + final c = Completer(); + gates[calls++] = c; + return c.future; + }); + r.track(fixes[0]); // A + r.track(fixes[1]); // B + r.track(fixes[2]); // C evicts A + r.track(fixes[0]); // A accepted again, read still out + expect(calls, 3, reason: 'A is not read a second time'); + for (var i = 0; i < 3; i++) { + gates[i]!.complete(_matching(fixes[i])); + } + await r.idle; + expect(r.lookup(fixes[0]).isKnown, isTrue, + reason: 'the pending answer lands in the re-reserved slot'); + expect(r.stats.proved + r.stats.unproved, 3, reason: 'counted once each'); + }); + + test('a malformed answer followed by a good one never poisons the SDK', + () async { + var calls = 0; + final a = _pos(timeMs: 1000); + final b = _pos(timeMs: 2000); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async => calls++ == 0 ? null : _matching(b)); + r.track(a); + await r.idle; + expect(r.lookup(a).isKnown, isFalse); + r.track(b); + await r.idle; + expect(calls, 2, reason: 'a null answer caches no SDK, so b is read'); + expect(r.lookup(b).isKnown, isTrue); + }); + + test('stats count real Android fixes only', () async { + final known = _pos(timeMs: 1000); + final unknown = _pos(timeMs: 2000); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async => _matching(known)); + r.track(known); + r.track(unknown); // its native answer describes a different fix + r.track(_pos(timeMs: 3000), simulated: true); + await r.idle; + expect(r.stats.proved, 1); + expect(r.stats.unproved, 1); + expect(r.stats.reasons, {'time_differs': 1}); + }); + }); + group('the key is the whole fix', () { + test('a mocked fix with the same time and place does not borrow a known ' + 'answer', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + final a = _pos(); + final b = _pos(isMocked: true); + r.track(a); + r.track(b); + expect(r.lookup(a).isKnown, isTrue); + expect(r.lookup(b).isKnown, isFalse); + }); + + test('a different altitude with the same time and place is its own ' + 'answer', () async { + final a = _pos(altitude: 120.0); + final b = _pos(altitude: 300.0); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () async => _matching(a)); + r.track(a); + await r.idle; + r.track(b); + await r.idle; + expect(r.lookup(a).reference, AltitudeReference.ellipsoid); + expect(r.lookup(a).meters, 120.0); + expect(r.lookup(b).isKnown, isFalse, + reason: 'the native fix proves 120 m, not 300 m'); + }); + + test('a different altitude accuracy is its own answer', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + final a = _pos(altitudeAccuracy: 6.0); + final b = _pos(altitudeAccuracy: 9.0); + r.track(a); + r.track(b); + expect(r.lookup(a).accuracy, 6.0); + expect(r.lookup(b).accuracy, 9.0); + expect(r.size, 2); + }); + + test('a pending read is never handed to a different fix with the same ' + 'time and place', () async { + final gates = >{}; + var calls = 0; + final a = _pos(altitude: 120.0); + final b = _pos(altitude: 300.0); + final r = FixAltitudeResolver( + platform: AltitudePlatform.android, + readNative: () { + final c = Completer(); + gates[calls++] = c; + return c.future; + }); + r.track(a); + r.track(b); // A's read is still out + expect(calls, 2, reason: 'B is read for itself'); + gates[0]!.complete(_matching(a)); + await Future.delayed(Duration.zero); + expect(r.lookup(a).isKnown, isTrue); + expect(r.lookup(b).isKnown, isFalse, reason: 'B never gets A\'s answer'); + gates[1]!.complete(_matching(a)); // the last fix is still A + await r.idle; + expect(r.lookup(b).isKnown, isFalse); + expect(r.lookup(a).meters, 120.0); + }); + + test('a NaN altitude fix is found again and stays unknown', () { + final r = FixAltitudeResolver(platform: AltitudePlatform.ios); + final p = _pos(altitude: double.nan, altitudeAccuracy: double.nan); + r.track(p); + r.track(p); + expect(r.size, 1, reason: 'NaN must not make every lookup a new key'); + expect(r.lookup(p).isKnown, isFalse); + }); + }); +} diff --git a/test/services/fix_altitude_test.dart b/test/services/fix_altitude_test.dart new file mode 100644 index 00000000..49c68e37 --- /dev/null +++ b/test/services/fix_altitude_test.dart @@ -0,0 +1,479 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; + +/// The one rule that decides whether an altitude may be uploaded and what +/// reference it carries. A wrong label is worse than none, so every path that +/// cannot PROVE the reference answers unknown. + +Position _pos({ + double lat = 45.0, + double lon = -75.0, + int timeMs = 1760000000000, + double altitude = 84.0, + double altitudeAccuracy = 6.0, + bool isMocked = false, +}) => + Position( + latitude: lat, + longitude: lon, + timestamp: DateTime.fromMillisecondsSinceEpoch(timeMs, isUtc: true), + accuracy: 5.0, + altitude: altitude, + altitudeAccuracy: altitudeAccuracy, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 0.0, + isMocked: isMocked, + ); + +NativeFixDescription _fix({ + int timeMs = 1760000000000, + double lat = 45.0, + double lon = -75.0, + bool hasAltitude = true, + double altitude = 120.0, + bool hasVerticalAccuracy = true, + double verticalAccuracy = 8.0, + bool hasMsl = false, + double msl = 0.0, + bool hasMslAccuracy = false, + double mslAccuracy = 0.0, + bool isMock = false, +}) => + NativeFixDescription( + source: 'fused', + timeMs: timeMs, + lat: lat, + lon: lon, + hasAltitude: hasAltitude, + altitude: altitude, + hasVerticalAccuracy: hasVerticalAccuracy, + verticalAccuracy: verticalAccuracy, + hasMsl: hasMsl, + msl: msl, + hasMslAccuracy: hasMslAccuracy, + mslAccuracy: mslAccuracy, + isMock: isMock, + ); + +NativeAltitudeAnswer _android14(List fixes) => + NativeAltitudeAnswer(sdk: 34, fixes: fixes); + +void main() { + group('FixAltitude', () { + test('unknown carries nothing', () { + const u = FixAltitude.unknown(); + expect(u.isKnown, isFalse); + expect(u.meters, isNull); + expect(u.reference, isNull); + expect(u.accuracy, isNull); + expect(u.wireReference, isNull); + }); + + test('known sanitizes its accuracy', () { + expect( + FixAltitude.known( + meters: 10, reference: AltitudeReference.msl, accuracy: 0.0) + .accuracy, + isNull); + expect( + FixAltitude.known( + meters: 10, + reference: AltitudeReference.msl, + accuracy: double.infinity) + .accuracy, + isNull); + expect( + FixAltitude.known( + meters: 10, + reference: AltitudeReference.msl, + accuracy: double.nan) + .accuracy, + isNull); + expect( + FixAltitude.known( + meters: 10, reference: AltitudeReference.msl, accuracy: 0.4) + .accuracy, + 0.4); + expect( + FixAltitude.known(meters: 10, reference: AltitudeReference.ellipsoid) + .wireReference, + 'ellipsoid'); + }); + }); + + group('reportedAltitudeOrNull', () { + test('the 0/0 pair means unknown, anything else is a reading', () { + expect(reportedAltitudeOrNull(_pos(altitude: 0, altitudeAccuracy: 0)), + isNull); + expect(reportedAltitudeOrNull(_pos(altitude: 0, altitudeAccuracy: 3)), 0); + expect(reportedAltitudeOrNull(_pos(altitude: 12, altitudeAccuracy: 0)), + 12); + }); + }); + + group('resolveFixAltitude: simulator, mock, missing', () { + test('a simulated fix is unknown on every platform', () { + for (final p in AltitudePlatform.values) { + final r = resolveFixAltitude( + platform: p, position: _pos(), simulated: true); + expect(r.altitude.isKnown, isFalse, reason: '$p'); + expect(r.reason, 'simulated'); + } + }); + + test('a mocked fix is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.ios, + position: _pos(isMocked: true), + simulated: false); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'mocked'); + }); + + test('a fix with no altitude is unknown (Review Focus 2)', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.ios, + position: _pos(altitude: 0, altitudeAccuracy: 0), + simulated: false); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'no_altitude'); + }); + + test('a NaN altitude is unknown (Review Focus 3)', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.ios, + position: _pos(altitude: double.nan), + simulated: false); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'no_altitude'); + }); + + test('an infinite accuracy is dropped but the altitude stays (Review Focus 3)', + () { + final r = resolveFixAltitude( + platform: AltitudePlatform.ios, + position: _pos(altitudeAccuracy: double.infinity), + simulated: false); + expect(r.altitude.isKnown, isTrue); + expect(r.altitude.accuracy, isNull); + }); + + test('an unknown platform is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.other, position: _pos(), simulated: false); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'other_platform'); + }); + }); + + group('resolveFixAltitude: iOS and web', () { + test('iOS is sea level with the fix accuracy', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.ios, position: _pos(), simulated: false); + expect(r.altitude.meters, 84.0); + expect(r.altitude.reference, AltitudeReference.msl); + expect(r.altitude.accuracy, 6.0); + expect(r.reason, 'ios'); + }); + + test('web is ellipsoid with no accuracy', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.web, position: _pos(), simulated: false); + expect(r.altitude.meters, 84.0); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + expect(r.altitude.accuracy, isNull); + expect(r.reason, 'web'); + }); + }); + + group('resolveFixAltitude: Android', () { + test('no native answer is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(), + simulated: false); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'no_native'); + }); + + test('below Android 14 is ellipsoid from the fix, no read needed', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(), + simulated: false, + native: const NativeAltitudeAnswer(sdk: 33, fixes: [])); + expect(r.altitude.meters, 84.0); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + expect(r.altitude.accuracy, 6.0); + expect(r.reason, 'android_legacy'); + }); + + test('Android 14 with no fixes read is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(), + simulated: false, + native: _android14(const [])); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'no_fix'); + }); + + test('Android 14 matched fix carrying sea level, plugin delivered it', + () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 84.0, altitudeAccuracy: 4.0), + simulated: false, + native: _android14([ + _fix( + altitude: 120.0, + hasMsl: true, + msl: 84.0, + hasMslAccuracy: true, + mslAccuracy: 4.0) + ])); + expect(r.altitude.meters, 84.0); + expect(r.altitude.reference, AltitudeReference.msl); + expect(r.altitude.accuracy, 4.0); + expect(r.reason, 'android_msl'); + }); + + test('Android 14 sea level without its own accuracy sends none', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 84.0, altitudeAccuracy: 8.0), + simulated: false, + native: _android14([ + _fix(altitude: 120.0, hasMsl: true, msl: 84.0) + ])); + expect(r.altitude.reference, AltitudeReference.msl); + expect(r.altitude.accuracy, isNull); + }); + + test('Android 14 matched fix without sea level, plugin delivered ellipsoid', + () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0, altitudeAccuracy: 8.0), + simulated: false, + native: _android14([_fix(altitude: 120.0)])); + expect(r.altitude.meters, 120.0); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + expect(r.altitude.accuracy, 8.0); + expect(r.reason, 'android_ellipsoid'); + }); + + test('Android 14 ellipsoid fix with no vertical accuracy sends none', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0, altitudeAccuracy: 0.0), + simulated: false, + native: _android14( + [_fix(altitude: 120.0, hasVerticalAccuracy: false)])); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + expect(r.altitude.accuracy, isNull); + }); + + test('Android 14 delivered value matching neither is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 99.0), + simulated: false, + native: _android14([_fix(altitude: 120.0, hasMsl: true, msl: 84.0)])); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'value_differs'); + }); + + test('Android 14 newer last fix is unknown (Review Focus 1)', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(timeMs: 1760000000000), + simulated: false, + native: _android14([_fix(timeMs: 1760000001000, altitude: 84.0)])); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'time_differs'); + }); + + test('Android 14 same time, different coordinate is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(lat: 45.0), + simulated: false, + native: _android14([_fix(lat: 45.0001, altitude: 84.0)])); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'coord_differs'); + }); + + test('Android 14 native fix marked mock is unknown', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0), + simulated: false, + native: _android14([_fix(altitude: 120.0, isMock: true)])); + expect(r.altitude.isKnown, isFalse); + expect(r.reason, 'native_mock'); + }); + + test('Android 14 picks the matching fix out of several manager candidates', + () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0), + simulated: false, + native: _android14([ + _fix(timeMs: 1759999990000, altitude: 50.0), + _fix(altitude: 120.0), + ])); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + }); + }); + + group('resolveFixAltitude: Android, the approved matching rule', () { + test('an exact ellipsoid match is accepted even when the fix also carries ' + 'sea level (the plugin only swaps when the fix has extras)', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0, altitudeAccuracy: 8.0), + simulated: false, + native: _android14([ + _fix(altitude: 120.0, hasMsl: true, msl: 84.0) + ])); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + expect(r.altitude.accuracy, 8.0); + expect(r.reason, 'android_ellipsoid'); + }); + + test('two candidates share time and coordinates, only the second matches ' + 'the delivered value', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0), + simulated: false, + native: _android14([ + _fix(altitude: 50.0), + _fix(altitude: 120.0), + ])); + expect(r.altitude.reference, AltitudeReference.ellipsoid); + }); + + test('a mock candidate does not hide a genuine match beside it', () { + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0), + simulated: false, + native: _android14([ + _fix(altitude: 120.0, isMock: true), + _fix(altitude: 120.0), + ])); + expect(r.altitude.isKnown, isTrue); + }); + }); + + group('NativeAltitudeAnswer.tryFromMap', () { + Map fixMap({Object? timeMs = 1760000000000}) => { + 'source': 'fused', + 'timeMs': timeMs, + 'lat': 45.0, + 'lon': -75, + 'hasAltitude': true, + 'altitude': 120, + 'hasVerticalAccuracy': true, + 'verticalAccuracy': 8.0, + 'hasMsl': true, + 'msl': 84.5, + 'hasMslAccuracy': false, + 'mslAccuracy': 0.0, + 'isMock': false, + }; + + test('parses the channel shape and tolerates int-typed doubles', () { + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [fixMap()]}); + expect(a!.sdk, 34); + expect(a.fixes.single.lon, -75.0); + expect(a.fixes.single.altitude, 120.0); + expect(a.fixes.single.msl, 84.5); + expect(a.fixes.single.hasMslAccuracy, isFalse); + }); + + test('a missing, zero, negative or non-integer sdk is no answer at all', () { + expect(NativeAltitudeAnswer.tryFromMap(const {}), isNull); + expect(NativeAltitudeAnswer.tryFromMap({'sdk': 0, 'fixes': []}), isNull); + expect(NativeAltitudeAnswer.tryFromMap({'sdk': -1, 'fixes': []}), isNull); + expect(NativeAltitudeAnswer.tryFromMap({'sdk': 34.5, 'fixes': []}), isNull); + expect(NativeAltitudeAnswer.tryFromMap('nope'), isNull); + }); + + test('a valid sdk with no fixes list is an answer with no fixes', () { + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 33}); + expect(a!.sdk, 33); + expect(a.fixes, isEmpty); + }); + + test('a malformed fix entry is skipped, the answer survives', () { + final a = NativeAltitudeAnswer.tryFromMap({ + 'sdk': 34, + 'fixes': ['garbage', {'timeMs': 'x'}, fixMap()], + }); + expect(a!.fixes, hasLength(1)); + }); + + test('a fractional timestamp is skipped, never truncated', () { + final a = NativeAltitudeAnswer.tryFromMap({ + 'sdk': 34, + 'fixes': [fixMap(timeMs: 1760000000000.5)], + }); + expect(a!.fixes, isEmpty); + }); + + test('a flag without its value is skipped', () { + final m = fixMap()..remove('msl'); + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [m]}); + expect(a!.fixes, isEmpty); + }); + + test('a missing isMock is skipped, never assumed false', () { + final m = fixMap()..remove('isMock'); + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [m]}); + expect(a!.fixes, isEmpty); + }); + test('a non-finite accuracy is dropped, the altitude is still proved', () { + final msl = fixMap() + ..['hasMslAccuracy'] = true + ..['mslAccuracy'] = double.nan; + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [msl]}); + expect(a!.fixes.single.hasMslAccuracy, isFalse); + final r = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 84.5), + simulated: false, + native: a); + expect(r.altitude.reference, AltitudeReference.msl); + expect(r.altitude.meters, 84.5); + expect(r.altitude.accuracy, isNull); + + final ell = fixMap() + ..['hasMsl'] = false + ..['verticalAccuracy'] = double.infinity; + final b = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [ell]}); + expect(b!.fixes.single.hasVerticalAccuracy, isFalse); + final r2 = resolveFixAltitude( + platform: AltitudePlatform.android, + position: _pos(altitude: 120.0), + simulated: false, + native: b); + expect(r2.altitude.reference, AltitudeReference.ellipsoid); + expect(r2.altitude.meters, 120.0); + expect(r2.altitude.accuracy, isNull); + }); + + test('a missing accuracy behind a true flag is no accuracy, not a reject', + () { + final m = fixMap()..remove('verticalAccuracy'); + final a = NativeAltitudeAnswer.tryFromMap({'sdk': 34, 'fixes': [m]}); + expect(a!.fixes.single.hasVerticalAccuracy, isFalse); + }); + }); +} diff --git a/test/services/gps_service_airborne_test.dart b/test/services/gps_service_airborne_test.dart index 4f7271f5..098db471 100644 --- a/test/services/gps_service_airborne_test.dart +++ b/test/services/gps_service_airborne_test.dart @@ -3,9 +3,9 @@ import 'package:geolocator/geolocator.dart'; import 'package:mesh_mapper/services/gps_service.dart'; /// Airborne block: a fix counts as airborne when its altitude (less the -/// GPS's own vertical error) clears 6,000 m or its ground speed clears -/// 250 km/h. Three consecutive airborne fixes latch, three consecutive -/// ground fixes clear. Unknown altitude and speed arrive as 0.0 from +/// GPS's own vertical error) clears 6,000 m with its speed unknown or at +/// least 150 km/h, or its ground speed clears 250 km/h. Three consecutive +/// airborne fixes latch, three consecutive ground fixes clear. Unknown altitude and speed arrive as 0.0 from /// geolocator and must never qualify. /// Each call is a distinct fix with its own timestamp, the way real fixes @@ -69,6 +69,51 @@ void main() { test('unknown altitude and speed never qualify', () { expect(GpsService.positionLooksAirborne(_pos()), isFalse); }); + + test('a high altitude at a known driving speed does not qualify', () { + // Denver: an iOS fix read 18,490 m in a car doing 8 km/h. + expect( + GpsService.positionLooksAirborne(_pos( + altitude: 18490, + altitudeAccuracy: 30, + speed: 8 / 3.6, + speedAccuracy: 1)), + isFalse); + }); + + test('a high altitude with a known zero speed does not qualify', () { + expect( + GpsService.positionLooksAirborne(_pos( + altitude: 12000, + altitudeAccuracy: 30, + speed: 0, + speedAccuracy: 1)), + isFalse); + }); + + test('a high altitude with unknown speed still qualifies', () { + expect( + GpsService.positionLooksAirborne( + _pos(altitude: 12000, altitudeAccuracy: 30)), + isTrue); + }); + + test('a high altitude at 150 km/h or more qualifies', () { + expect( + GpsService.positionLooksAirborne(_pos( + altitude: 12000, + altitudeAccuracy: 30, + speed: 150 / 3.6, + speedAccuracy: 1)), + isTrue); + expect( + GpsService.positionLooksAirborne(_pos( + altitude: 12000, + altitudeAccuracy: 30, + speed: 149 / 3.6, + speedAccuracy: 1)), + isFalse); + }); }); group('altitudeOrNull', () { @@ -220,6 +265,56 @@ void main() { expect(gps.isAirborne, isTrue); }); + test('three high fixes at a known driving speed do not latch', () { + for (var i = 0; i < 3; i++) { + gps.trackAirborne(_pos( + altitude: 18490, + altitudeAccuracy: 30, + speed: 8 / 3.6, + speedAccuracy: 1)); + } + expect(gps.isAirborne, isFalse); + expect(gps.airborneGate, isNull); + }); + + test('a high fix at 160 km/h latches and records the altitude gate', () { + for (var i = 0; i < 3; i++) { + gps.trackAirborne(_pos( + altitude: 12000, + altitudeAccuracy: 30, + speed: 160 / 3.6, + speedAccuracy: 1)); + } + expect(gps.isAirborne, isTrue); + expect(gps.airborneGate, AirborneGate.altitude); + expect(gps.airborneAltitude, 12000.0); + }); + + test('a high fix with unknown speed latches on the altitude gate', () { + for (var i = 0; i < 3; i++) { + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + } + expect(gps.isAirborne, isTrue); + expect(gps.airborneGate, AirborneGate.altitude); + expect(gps.airborneSpeed, isNull); + }); + + test('a known-slow high fix in between restarts the airborne streak', () { + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + gps.trackAirborne(_pos( + altitude: 12000, + altitudeAccuracy: 30, + speed: 8 / 3.6, + speedAccuracy: 1)); + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + expect(gps.isAirborne, isFalse); + + gps.trackAirborne(_pos(altitude: 12000, altitudeAccuracy: 30)); + expect(gps.isAirborne, isTrue); + }); + test('resetAirborne clears the latch and the streaks', () { for (var i = 0; i < 3; i++) { gps.trackAirborne(_pos(altitude: 9000, altitudeAccuracy: 20)); diff --git a/test/services/gps_service_fix_altitude_test.dart b/test/services/gps_service_fix_altitude_test.dart new file mode 100644 index 00000000..8b48df7b --- /dev/null +++ b/test/services/gps_service_fix_altitude_test.dart @@ -0,0 +1,69 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/fix_altitude_resolver.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; + +/// GpsService hands every accepted fix to the resolver and exposes the +/// stored answer. The simulator's fixes are tracked as simulated (unknown) +/// and switching it on or off bumps the generation. + +Position _pos({ + int timeMs = 1760000000000, + double altitude = 84.0, + double altitudeAccuracy = 6.0, +}) => + Position( + latitude: 45.0, + longitude: -75.0, + timestamp: DateTime.fromMillisecondsSinceEpoch(timeMs, isUtc: true), + accuracy: 5.0, + altitude: altitude, + altitudeAccuracy: altitudeAccuracy, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 0.0, + ); + +void main() { + test('altitudeOrNull keeps the 0/0 rule', () { + expect(GpsService.altitudeOrNull(_pos(altitude: 0.0, altitudeAccuracy: 0.0)), + isNull, reason: 'the 0/0 pair is geolocator\'s "unknown"'); + expect(GpsService.altitudeOrNull(_pos(altitude: 0.0, altitudeAccuracy: 6.0)), + 0.0, reason: 'a real reading at sea level is kept'); + expect(GpsService.altitudeOrNull(_pos(altitude: 12.0)), 12.0); + }); + + test('a fix never handed to the service is unknown', () { + final gps = GpsService( + altitudeResolver: FixAltitudeResolver(platform: AltitudePlatform.ios)); + expect(gps.fixAltitudeOf(_pos()).isKnown, isFalse); + }); + + test('simulator fixes resolve unknown and enabling the simulator resets', + () async { + final resolver = FixAltitudeResolver(platform: AltitudePlatform.ios); + final gps = GpsService(altitudeResolver: resolver); + final before = resolver.generation; + gps.enableSimulator(startLatitude: 45.0, startLongitude: -75.0); + expect(resolver.generation, before + 1); + final seed = gps.lastPosition; + expect(seed, isNotNull); + expect(resolver.size, 1, + reason: 'the seed WAS handed to the resolver (not merely never stored)'); + expect(gps.fixAltitudeOf(seed!).isKnown, isFalse, + reason: 'a simulated fix never carries a reference'); + await Future.delayed(const Duration(milliseconds: 1200)); + expect(resolver.size, greaterThan(1), + reason: 'the simulator\'s later ticks are tracked too, not only the seed'); + final after = resolver.generation; + gps.dispose(); + expect(resolver.generation, after + 1, reason: 'dispose resets'); + }); + + // disableSimulator() resets through startWatching(), whose first statements + // run synchronously before its first await. That path touches the platform + // location plugin and cannot run under flutter_test; the resolver test + // "a completion for an older generation is dropped" covers the reset itself. +} diff --git a/test/services/gps_service_location_manager_test.dart b/test/services/gps_service_location_manager_test.dart new file mode 100644 index 00000000..833c4fd9 --- /dev/null +++ b/test/services/gps_service_location_manager_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; + +/// Issue 595: with Google Location Accuracy off, Android's location plugin +/// shows Google's "Location Accuracy" dialog. Declining it failed the GPS +/// stream as "location services disabled", the dialog closing resumed the +/// app, the resume restarted GPS, and the dialog came back, so the app could +/// not get past it. A decline with device location still on now moves GPS +/// to Android's own location service, which never shows that dialog. +void main() { + bool decide({ + bool isAndroid = true, + bool alreadyUsing = false, + Object error = const LocationServiceDisabledException(), + bool deviceLocationOn = true, + }) => + shouldUseAndroidLocationManager( + isAndroid: isAndroid, + alreadyUsing: alreadyUsing, + error: error, + deviceLocationOn: deviceLocationOn, + ); + + test('a declined dialog with device location on switches', () { + expect(decide(), isTrue); + }); + + test('device location really off stays disabled', () { + expect(decide(deviceLocationOn: false), isFalse); + }); + + test('it switches once, never back and forth', () { + expect(decide(alreadyUsing: true), isFalse); + }); + + test('other stream errors do not switch', () { + expect(decide(error: const PermissionDeniedException('denied')), isFalse); + expect(decide(error: StateError('anything')), isFalse); + }); + + test('only Android has a second location service', () { + expect(decide(isAndroid: false), isFalse); + }); +} diff --git a/test/services/gps_service_stream_settings_test.dart b/test/services/gps_service_stream_settings_test.dart new file mode 100644 index 00000000..7335e1dd --- /dev/null +++ b/test/services/gps_service_stream_settings_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; + +/// Android's location plugin asks for a fix every 5 s unless told otherwise, +/// so Android pings reused the previous fix far more often than iOS (median +/// gap 5 s against 1 s). Both Android providers now ask for one a second; +/// the 10 m distance filter still decides how often a fix is delivered. +void main() { + test('Android with Google\'s provider asks for a fix every second', () { + final settings = gpsStreamSettings( + isAndroid: true, useAndroidLocationManager: false); + expect(settings, isA()); + final android = settings as AndroidSettings; + expect(android.intervalDuration, const Duration(seconds: 1)); + expect(android.forceLocationManager, isFalse); + expect(android.distanceFilter, 10); + expect(android.accuracy, LocationAccuracy.high); + expect(android.useMSLAltitude, isFalse); + }); + + test('Android\'s own location service asks for a fix every second', () { + final settings = + gpsStreamSettings(isAndroid: true, useAndroidLocationManager: true); + expect(settings, isA()); + final android = settings as AndroidSettings; + expect(android.intervalDuration, const Duration(seconds: 1)); + expect(android.forceLocationManager, isTrue); + expect(android.distanceFilter, 10); + expect(android.accuracy, LocationAccuracy.high); + expect(android.useMSLAltitude, isFalse); + }); + + test('other platforms keep the plain settings', () { + final settings = gpsStreamSettings( + isAndroid: false, useAndroidLocationManager: false); + expect(settings, isNot(isA())); + expect(settings.distanceFilter, 10); + expect(settings.accuracy, LocationAccuracy.high); + }); +} diff --git a/test/services/gps_service_zone_fix_test.dart b/test/services/gps_service_zone_fix_test.dart new file mode 100644 index 00000000..e7fd6eaf --- /dev/null +++ b/test/services/gps_service_zone_fix_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; + +/// Zone checks and the connect /auth must never send a fix the server will +/// refuse for accuracy (over 50 m). A coarse fix that lands just after a good +/// one must not stand in for it. + +final DateTime _now = DateTime(2026, 10, 6, 12); + +Position _fix({required double accuracy, required int secondsAgo}) => Position( + latitude: 45.0, + longitude: -75.0, + timestamp: _now.subtract(Duration(seconds: secondsAgo)), + accuracy: accuracy, + altitude: 0.0, + altitudeAccuracy: 0.0, + heading: 0.0, + headingAccuracy: 0.0, + speed: 0.0, + speedAccuracy: 0.0, + ); + +void main() { + group('isAccurateForZoneCheck', () { + test('50 m and under passes, over 50 m does not', () { + expect( + GpsService.isAccurateForZoneCheck(_fix(accuracy: 30, secondsAgo: 0)), + isTrue); + expect( + GpsService.isAccurateForZoneCheck(_fix(accuracy: 50, secondsAgo: 0)), + isTrue); + expect( + GpsService.isAccurateForZoneCheck( + _fix(accuracy: 64.8, secondsAgo: 0)), + isFalse); + }); + + test('age is not part of it (a stationary phone sends an old fix)', () { + expect( + GpsService.isAccurateForZoneCheck( + _fix(accuracy: 10, secondsAgo: 600)), + isTrue); + }); + }); + + group('pickZoneCheckFix', () { + test('a 738 m fix after a 20 m fix picks the 20 m one', () { + final good = _fix(accuracy: 20, secondsAgo: 5); + final coarse = _fix(accuracy: 738, secondsAgo: 1); + expect(GpsService.pickZoneCheckFix([good, coarse], _now), same(good)); + }); + + test('prefers the newest accurate fix over the most accurate one', () { + final older = _fix(accuracy: 5, secondsAgo: 30); + final newer = _fix(accuracy: 40, secondsAgo: 2); + expect(GpsService.pickZoneCheckFix([older, newer], _now), same(newer)); + expect(GpsService.pickZoneCheckFix([newer, older], _now), same(newer)); + }); + + test('ignores accurate fixes older than 60 s', () { + final stale = _fix(accuracy: 10, secondsAgo: 61); + expect(GpsService.pickZoneCheckFix([stale], _now), isNull); + }); + + test('null when every fix is coarse', () { + expect( + GpsService.pickZoneCheckFix([ + _fix(accuracy: 1300, secondsAgo: 3), + _fix(accuracy: 65, secondsAgo: 1), + ], _now), + isNull); + }); + }); + + group('bestRecentZoneCheckFix', () { + test('reads the fixes recorded by the service', () { + final gps = GpsService(); + expect(gps.bestRecentZoneCheckFix(now: _now), isNull); + final good = _fix(accuracy: 30, secondsAgo: 1); + gps.recordRecentFix(good); + gps.recordRecentFix(_fix(accuracy: 64.8, secondsAgo: 0)); + expect(gps.bestRecentZoneCheckFix(now: _now), same(good)); + }); + + test('keeps only a bounded history', () { + final gps = GpsService(); + gps.recordRecentFix(_fix(accuracy: 10, secondsAgo: 50)); + for (var i = 0; i < 40; i++) { + gps.recordRecentFix(_fix(accuracy: 500, secondsAgo: 0)); + } + // The one good fix has been pushed out by 40 coarse ones. + expect(gps.bestRecentZoneCheckFix(now: _now), isNull); + }); + }); +} diff --git a/test/services/idle_session_test.dart b/test/services/idle_session_test.dart new file mode 100644 index 00000000..019a4f9f --- /dev/null +++ b/test/services/idle_session_test.dart @@ -0,0 +1,37 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/idle_session.dart'; + +void main() { + bool idle({ + bool autoPingEnabled = false, + bool autoPingStarting = false, + bool pendingDisable = false, + bool pingSending = false, + bool pingInProgress = false, + bool repeaterAdminOpen = false, + int queuedItems = 0, + }) => + sessionIsIdle( + autoPingEnabled: autoPingEnabled, + autoPingStarting: autoPingStarting, + pendingDisable: pendingDisable, + pingSending: pingSending, + pingInProgress: pingInProgress, + repeaterAdminOpen: repeaterAdminOpen, + queuedItems: queuedItems, + ); + + test('nothing running and nothing queued is idle', () { + expect(idle(), isTrue); + }); + + test('any activity or queued item is busy', () { + expect(idle(autoPingEnabled: true), isFalse); + expect(idle(autoPingStarting: true), isFalse); + expect(idle(pendingDisable: true), isFalse); + expect(idle(pingSending: true), isFalse); + expect(idle(pingInProgress: true), isFalse); + expect(idle(repeaterAdminOpen: true), isFalse); + expect(idle(queuedItems: 1), isFalse); + }); +} diff --git a/test/services/link_decision_test.dart b/test/services/link_decision_test.dart index 93042354..423b1ea4 100644 --- a/test/services/link_decision_test.dart +++ b/test/services/link_decision_test.dart @@ -67,4 +67,26 @@ void main() { test('a lowercase pubkey is still acceptable input', () { expect(call(pubkey: goodPubkey.toLowerCase()), LinkFlowDecision.prompt); }); + + // Issue 627: two L1 Pro radios on mishmesh firmware accepted the sign + // start, then answered ERR 4, and the manual link said "Try again later" + // when only a reboot helps. + group('signFailureNeedsRadioReboot', () { + test('an ERR after the sign started asks for a reboot', () { + expect(signFailureNeedsRadioReboot('err'), isTrue); + }); + + for (final code in [ + 'unsupported', + 'busy', + 'aborted', + 'malformed_response', + 'data_too_long', + 'bad_signature_length', + ]) { + test('$code does not', () { + expect(signFailureNeedsRadioReboot(code), isFalse); + }); + } + }); } diff --git a/test/services/live_activity/live_activity_heard_test.dart b/test/services/live_activity/live_activity_heard_test.dart index 4c7059af..26b57010 100644 --- a/test/services/live_activity/live_activity_heard_test.dart +++ b/test/services/live_activity/live_activity_heard_test.dart @@ -16,7 +16,7 @@ void main() { (repeaterId: 'A1', snr: 8.5, type: OverlayPingType.tx), (repeaterId: 'B2', snr: 2.25, type: OverlayPingType.disc), ], - topTotalCount: 2, + topHeardIds: const {'A1', 'B2'}, rxSlot: (repeaterId: 'C3', snr: 9.9), topAt: t0, rxAt: t0, @@ -44,7 +44,7 @@ void main() { test('a silent ping clears the rows instead of dimming them', () { final result = buildLiveActivityHeard( top: const [(repeaterId: 'A1', snr: 8.5, type: OverlayPingType.tx)], - topTotalCount: 1, + topHeardIds: const {'A1'}, rxSlot: null, topAt: t0, rxAt: null, @@ -63,7 +63,7 @@ void main() { // The SwiftUI ForEach identifies rows by id and cannot draw one twice. final result = buildLiveActivityHeard( top: const [(repeaterId: 'a1', snr: 5, type: OverlayPingType.tx)], - topTotalCount: 1, + topHeardIds: const {'A1'}, rxSlot: (repeaterId: 'A1', snr: 9), topAt: t0, rxAt: t0, @@ -87,7 +87,7 @@ void main() { (repeaterId: 'B2', snr: 7, type: OverlayPingType.disc), (repeaterId: 'C3', snr: 6, type: OverlayPingType.disc), ], - topTotalCount: 5, + topHeardIds: const {'A1', 'B2', 'C3', 'E5', 'F6'}, rxSlot: (repeaterId: 'D4', snr: 1), topAt: t0, rxAt: t0, @@ -101,10 +101,31 @@ void main() { 'only the three the box shows, plus the RX row'); }); + test('an RX repeater the ping heard below the shown rows counts once', () { + final result = buildLiveActivityHeard( + top: const [ + (repeaterId: 'A1', snr: 8, type: OverlayPingType.disc), + (repeaterId: 'B2', snr: 7, type: OverlayPingType.disc), + (repeaterId: 'C3', snr: 6, type: OverlayPingType.disc), + ], + topHeardIds: const {'A1', 'B2', 'C3', 'D4', 'E5'}, + rxSlot: (repeaterId: 'D4', snr: 1), + topAt: t0, + rxAt: t0, + cycleStartedAt: beforeT0, + nameFor: nameFor, + ); + + expect(result.repeaters.map((r) => r.id), ['A1', 'B2', 'C3', 'D4'], + reason: 'D4 is not one of the shown ping rows, so its RX row stays'); + expect(result.totalCount, 5, + reason: 'the ping already counted D4 as its 4th repeater'); + }); + test('a fresh RX during a silent cycle shows only the RX row', () { final result = buildLiveActivityHeard( top: const [(repeaterId: 'A1', snr: 8.5, type: OverlayPingType.tx)], - topTotalCount: 1, + topHeardIds: const {'A1'}, rxSlot: (repeaterId: 'D4', snr: 1.5), topAt: t0, rxAt: t0.add(const Duration(seconds: 12)), @@ -123,7 +144,7 @@ void main() { (repeaterId: 'a1', snr: 8.5, type: OverlayPingType.tx), (repeaterId: 'b2', snr: -3, type: OverlayPingType.tx), ], - topTotalCount: 2, + topHeardIds: const {'A1', 'B2'}, rxSlot: null, topAt: t0, rxAt: null, @@ -146,7 +167,7 @@ void main() { (repeaterId: 'A1', snr: double.nan, type: OverlayPingType.tx), (repeaterId: 'B2', snr: 2, type: OverlayPingType.tx), ], - topTotalCount: 2, + topHeardIds: const {'A1', 'B2'}, rxSlot: (repeaterId: 'C3', snr: double.infinity), topAt: t0, rxAt: t0, diff --git a/test/services/meshcore/catalog_protocol_transport.dart b/test/services/meshcore/catalog_protocol_transport.dart index 64633ba5..48fda18c 100644 --- a/test/services/meshcore/catalog_protocol_transport.dart +++ b/test/services/meshcore/catalog_protocol_transport.dart @@ -59,7 +59,8 @@ class CatalogProtocolTransport extends FakeCompanionTransport { frame.writeByte(ResponseCodes.ok); case CommandCodes.getChannel: if (data[1] > 0) { - emit([ResponseCodes.err, 1]); + // ERR_CODE_NOT_FOUND: the firmware's end of the channel list. + emit([ResponseCodes.err, ErrorCodes.notFound]); return; } frame.writeByte(ResponseCodes.channelInfo); diff --git a/test/services/meshcore/channel_scan_test.dart b/test/services/meshcore/channel_scan_test.dart new file mode 100644 index 00000000..7e0fc5d5 --- /dev/null +++ b/test/services/meshcore/channel_scan_test.dart @@ -0,0 +1,449 @@ +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/buffer_utils.dart'; +import 'package:mesh_mapper/services/meshcore/channel_service.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/crypto_service.dart'; +import 'package:mesh_mapper/services/meshcore/packet_parser.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; + +import 'catalog_protocol_transport.dart'; + +/// One scripted answer to a CMD_GET_CHANNEL read. +sealed class _Answer { + const _Answer(); +} + +class _Slot extends _Answer { + final String name; + final Uint8List key; + const _Slot(this.name, this.key); +} + +class _Err extends _Answer { + final int code; + const _Err(this.code); +} + +class _Silent extends _Answer { + const _Silent(); +} + +class _WriteFails extends _Answer { + const _WriteFails(); +} + +/// The reply is held back, and from then on every reply runs one read +/// behind: each read gets the answer to the read before it. +class _Late extends _Answer { + const _Late(); +} + +/// A reply for [staleIdx] arrives first, then the real answer. +class _StaleFirst extends _Answer { + final int staleIdx; + const _StaleFirst(this.staleIdx); +} + +/// A radio whose channel table is [slots]; reads past it answer [endError]. +/// MeshCore uses NOT_FOUND, while ZephCore uses ILLEGAL_ARG. +/// [faults] lists, per slot index, answers given before the real one. +class _ChannelRadio extends CatalogProtocolTransport { + final List<_Slot> slots; + final Map> faults; + + final int? advertisedChannels; + final int endError; + final int protocolVersion; + + /// When set, CMD_SET_CHANNEL is answered with this ERR code, not OK. + final int? setChannelErr; + + _ChannelRadio(this.slots, + {Map>? faults, + this.advertisedChannels, + this.endError = ErrorCodes.notFound, + this.protocolVersion = 14, + this.setChannelErr}) + : faults = faults ?? {}; + + final List reads = []; + + /// Replies the radio still owes once a [_Late] answer starts the lag. + List>? _lagged; + + List get setChannelWrites => + writes.where((w) => w.first == CommandCodes.setChannel).toList(); + + @override + Future write(Uint8List data) async { + if (data.first == CommandCodes.deviceQuery && advertisedChannels != null) { + // Device-info layout shared by MeshCore and ZephCore. Capacity is byte 3, + // distinct from max contacts and the four-byte BLE PIN next to it. + final frame = BufferWriter(); + frame.writeBytes([ + ResponseCodes.deviceInfo, + protocolVersion, + 175, + advertisedChannels!, + 0x40, + 0xe2, + 1, + 0 + ]); + frame.writeCString('2026 Sep 27', 12); + frame.writeCString('Heltec Mesh Node T1', 40); + frame.writeCString('1.17.6-zephcore', 20); + frame.writeBytes([0, 1]); + emit(frame.toBytes()); + return; + } + if (data.first == CommandCodes.setChannel) { + writes.add(Uint8List.fromList(data)); + final err = setChannelErr; + emit(err == null ? [ResponseCodes.ok] : [ResponseCodes.err, err]); + return; + } + if (data.first != CommandCodes.getChannel) { + await super.write(data); + return; + } + final idx = data[1]; + reads.add(idx); + final queued = faults[idx]; + final _Answer answer = (queued != null && queued.isNotEmpty) + ? queued.removeAt(0) + : idx < slots.length + ? slots[idx] + : _Err(endError); + if (answer is _WriteFails) { + throw StateError('GATT write failed'); + } + writes.add(Uint8List.fromList(data)); + final lagged = _lagged; + if (answer is _Late) { + _lagged = [_frameFor(idx, idx < slots.length ? slots[idx] : null)]; + return; + } + if (lagged != null) { + lagged.add(_frameFor(idx, idx < slots.length ? slots[idx] : null)); + emit(lagged.removeAt(0)); + return; + } + switch (answer) { + case _Slot(): + emit(_frameFor(idx, answer)); + case _Err(:final code): + emit([ResponseCodes.err, code]); + case _StaleFirst(:final staleIdx): + emit(_frameFor(staleIdx, slots[staleIdx])); + emit(_frameFor(idx, slots[idx])); + case _Silent(): + case _WriteFails(): + case _Late(): + break; + } + } + + /// The radio's reply to a read of [idx]: the slot, or ERR_CODE_NOT_FOUND + /// past the end of the table. + List _frameFor(int idx, _Slot? slot) { + if (slot == null) return [ResponseCodes.err, ErrorCodes.notFound]; + final frame = BufferWriter(); + frame.writeByte(ResponseCodes.channelInfo); + frame.writeByte(idx); + frame.writeCString(slot.name, 32); + frame.writeBytes(slot.key); + return frame.toBytes(); + } +} + +void main() { + final wardrivingKey = CryptoService.deriveChannelKey('#wardriving'); + final emptyKey = Uint8List(16); + final otherKey = Uint8List.fromList(List.filled(16, 7)); + + _Slot named(String name) => _Slot(name, otherKey); + final empty = _Slot('', emptyKey); + final wardriving = _Slot('#wardriving', wardrivingKey); + + /// Runs the scan on a fake clock so the 5 s read timeout and the retry + /// delay cost no wall time. + ({ChannelInfo? result, Object? error}) scan(_ChannelRadio radio) { + ChannelInfo? result; + Object? error; + fakeAsync((async) { + final connection = MeshCoreConnection(transport: radio); + final operation = radio.advertisedChannels == null + ? ChannelService.ensureWardrivingChannel(connection) + : connection + .connect((_) async => null) + .then((_) => connection.wardrivingChannel!); + operation.then((value) => result = value, + onError: (Object e) => error = e); + async.elapse(const Duration(minutes: 2)); + connection.dispose(); + }); + radio.dispose(); + return (result: result, error: error); + } + + test('a create the radio refuses with ERR fails the setup', () { + final radio = _ChannelRadio([named('Public'), empty], + setChannelErr: ErrorCodes.illegalArg); + final out = scan(radio); + expect(out.result, isNull); + expect(out.error.toString(), contains(ChannelService.createFailedMessage)); + expect(radio.setChannelWrites, hasLength(1)); + }); + + for (final count in [8, 40, 64, 255]) { + for (final endError in [ErrorCodes.notFound, ErrorCodes.illegalArg]) { + test('$count advertised slots never probe the end (ERR $endError)', () { + final radio = _ChannelRadio( + [named('Public'), ...List.filled(count - 1, empty)], + advertisedChannels: count, + endError: endError, + protocolVersion: count == 8 ? 7 : 14, + ); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result?.channelIndex, 1); + expect(radio.reads, List.generate(count, (i) => i)); + expect(radio.setChannelWrites.single[1], 1); + }); + } + } + + test('ZephCore report creates at slot 10 after reading all 40 slots', () { + final radio = _ChannelRadio( + [ + ...List.generate(10, (i) => named('channel$i')), + ...List.filled(30, empty) + ], + advertisedChannels: 40, + endError: ErrorCodes.illegalArg, + ); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result?.channelIndex, 10); + expect(radio.reads, List.generate(40, (i) => i)); + expect(radio.setChannelWrites.single[1], 10); + }); + + for (final existing in [wardriving, _Slot('My mapping', wardrivingKey)]) { + test('reuses ${existing.name} in the last advertised slot after holes', () { + final radio = _ChannelRadio( + [named('Public'), ...List.filled(38, empty), existing], + advertisedChannels: 40, + endError: ErrorCodes.illegalArg, + ); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result?.channelIndex, 39); + expect(radio.setChannelWrites, isEmpty); + }); + } + + test('a full advertised table fails without writing or probing past it', () { + final radio = _ChannelRadio(List.filled(8, named('#other')), + advertisedChannels: 8, endError: ErrorCodes.illegalArg); + final out = scan(radio); + expect(out.error.toString(), contains('No empty channel slots')); + expect(radio.reads, List.generate(8, (i) => i)); + expect(radio.setChannelWrites, isEmpty); + }); + + for (final error in [ErrorCodes.notFound, ErrorCodes.illegalArg]) { + test('ERR $error inside advertised capacity cannot truncate the scan', () { + final radio = _ChannelRadio( + [named('Public'), empty, named('#other'), wardriving], + advertisedChannels: 4, + faults: { + 2: [_Err(error), _Err(error)] + }, + ); + final out = scan(radio); + expect(out.error.toString(), contains('Please reconnect')); + expect(radio.setChannelWrites, isEmpty); + expect(radio.reads, [0, 1, 2, 2]); + }); + } + + test('transient not-found inside capacity retries and finds existing channel', + () { + final radio = _ChannelRadio( + [named('Public'), empty, named('#other'), wardriving], + advertisedChannels: 4, + faults: { + 2: [const _Err(ErrorCodes.notFound)] + }, + ); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result?.channelIndex, 3); + expect(radio.setChannelWrites, isEmpty); + expect(radio.reads, [0, 1, 2, 2, 3]); + }); + + test('zero capacity uses the legacy not-found fallback', () { + final radio = + _ChannelRadio([named('Public'), empty], advertisedChannels: 0); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result?.channelIndex, 1); + expect(radio.reads, [0, 1, 2]); + }); + + test('a timeout at slot 3 is retried and the existing channel at 6 is found', + () { + final radio = _ChannelRadio([ + named('Public'), + empty, + named('#local'), + named('#ottawa'), + named('#test'), + named('#foo'), + wardriving, + ], faults: { + 3: [const _Silent()], + }); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 6); + expect(radio.setChannelWrites, isEmpty); + expect(radio.reads.where((i) => i == 3).length, 2); + }); + + test('a non-2 ERR at slot 3 is retried, then the channel is found', () { + final radio = _ChannelRadio([ + named('Public'), + empty, + named('#local'), + named('#ottawa'), + wardriving, + ], faults: { + 3: [const _Err(1)], + }); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 4); + expect(radio.setChannelWrites, isEmpty); + }); + + test('a write error at a slot is retried like any other failure', () { + final radio = _ChannelRadio([ + named('Public'), + empty, + wardriving + ], faults: { + 2: [const _WriteFails()], + }); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 2); + expect(radio.setChannelWrites, isEmpty); + }); + + test('a slot failing twice fails setup and creates nothing', () { + final radio = _ChannelRadio([ + named('Public'), + empty, + named('#local'), + named('#ottawa'), + wardriving, + ], faults: { + 3: [const _Silent(), const _Err(1)], + }); + final out = scan(radio); + expect(out.result, isNull); + expect(out.error.toString(), contains('Please reconnect')); + expect(out.error.toString(), isNot(contains('timed out'))); + expect(radio.setChannelWrites, isEmpty); + expect(radio.reads.where((i) => i > 3), isEmpty); + }); + + test('ERR code 2 at slot 8 with no #wardriving creates in the first empty', + () { + final radio = _ChannelRadio([ + named('Public'), + named('#a'), + empty, + named('#b'), + empty, + named('#c'), + named('#d'), + named('#e'), + ]); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 2); + expect(out.result!.name, '#wardriving'); + expect(radio.reads.last, 8); + expect(radio.setChannelWrites, hasLength(1)); + final write = radio.setChannelWrites.single; + expect(write[1], 2); + }); + + test('a differently named channel with the #wardriving key is reused', () { + final radio = _ChannelRadio([ + named('Public'), + empty, + _Slot('Wardrive', wardrivingKey), + ]); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 2); + expect(out.result!.name, 'Wardrive'); + expect(radio.setChannelWrites, isEmpty); + }); + + test('a late reply after a timeout never shifts the scan onto a used slot', + () { + // Slot 1 times out and its reply arrives late; from then on every reply + // runs one read behind. Taking replies in arrival order would record the + // empty slot 3 as slot 4 and create #wardriving over the user's channel. + final radio = _ChannelRadio([ + named('Public'), + named('#a'), + named('#b'), + empty, + named('#mine'), + ], faults: { + 1: [const _Late()], + }); + final out = scan(radio); + expect(out.error, isNull); + expect(out.result!.channelIndex, 3); + expect(radio.setChannelWrites, hasLength(1)); + expect(radio.setChannelWrites.single[1], 3); + }); + + test('a stale reply for another slot is ignored and the right one taken', () { + final radio = _ChannelRadio([ + named('Public'), + named('#a'), + empty + ], faults: { + 2: [const _StaleFirst(1)], + }); + ChannelInfo? result; + fakeAsync((async) { + final connection = MeshCoreConnection(transport: radio); + connection.getChannel(2).then((value) => result = value); + async.elapse(const Duration(seconds: 1)); + connection.dispose(); + }); + radio.dispose(); + expect(result, isNotNull); + expect(result!.channelIndex, 2); + expect(result!.name, ''); + }); + + test('the typed command error still reads as before in logs', () { + expect(const CommandErrorException(3).toString(), + 'Exception: Command error (code 3)'); + }); +} diff --git a/test/services/meshcore/connection_resilience_test.dart b/test/services/meshcore/connection_resilience_test.dart new file mode 100644 index 00000000..71f447c0 --- /dev/null +++ b/test/services/meshcore/connection_resilience_test.dart @@ -0,0 +1,122 @@ +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; + +import 'fake_companion_transport.dart'; + +/// A fake radio that answers stats requests with a noise floor reading +/// while [answerStats] is true, and whose writes fail while [failWrites] is. +class _StatsRadio extends FakeCompanionTransport { + bool answerStats = false; + int statsWrites = 0; + + @override + Future write(Uint8List data) async { + await super.write(data); + if (data.first == CommandCodes.getStats) { + statsWrites++; + if (answerStats) { + emit([ + ResponseCodes.stats, + StatsTypes.radio, + (-110) & 0xFF, + ((-110) >> 8) & 0xFF, + 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]); + } + } + } +} + +void main() { + group('noise floor polling', () { + test('backs off after 3 failures and recovers on success', () { + fakeAsync((async) { + final radio = _StatsRadio()..failWrites = true; + final connection = MeshCoreConnection(transport: radio); + connection.debugStartNoiseFloorPolling(); + + // Initial fetch plus two 5 s ticks: three failures in a row. + async.elapse(const Duration(seconds: 11)); + expect(connection.isNoiseFloorPolling, isTrue); + expect(connection.isNoiseFloorBackedOff, isTrue); + + // Backed off: nothing more within the next 25 s. + final writesAtBackoff = radio.statsWrites; + radio.failWrites = false; + radio.answerStats = true; + async.elapse(const Duration(seconds: 25)); + expect(radio.statsWrites, writesAtBackoff); + + // The 30 s tick succeeds and polling returns to 5 s. + async.elapse(const Duration(seconds: 6)); + expect(connection.isNoiseFloorBackedOff, isFalse); + expect(connection.lastNoiseFloor, -110); + final afterRecovery = radio.statsWrites; + async.elapse(const Duration(seconds: 10)); + expect(radio.statsWrites, afterRecovery + 2); + + connection.dispose(); + radio.dispose(); + }); + }); + }); + + group('setChannel', () { + Uint8List key() => Uint8List(16); + + test('completes on the radio OK', () async { + final radio = FakeCompanionTransport(); + final connection = MeshCoreConnection(transport: radio); + var done = false; + final f = connection.setChannel(3, '#wardriving', key()).then((_) { + done = true; + }); + await radio.settle(); + expect(radio.commandAt(0), CommandCodes.setChannel); + expect(done, isFalse); + radio.emit([ResponseCodes.ok]); + await f; + expect(done, isTrue); + connection.dispose(); + radio.dispose(); + }); + + test('throws CommandErrorException on ERR', () async { + final radio = FakeCompanionTransport(); + final connection = MeshCoreConnection(transport: radio); + final f = connection.setChannel(3, '#wardriving', key()); + final expectation = + expectLater(f, throwsA(isA())); + await radio.settle(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + await expectation; + connection.dispose(); + radio.dispose(); + }); + + test('a silent delete gives up after its short timeout', () { + fakeAsync((async) { + final radio = FakeCompanionTransport(); + final connection = MeshCoreConnection(transport: radio); + var done = false; + Object? error; + connection.deleteChannel(3).then((_) { + done = true; + }, onError: (Object e) { + error = e; + }); + async.elapse(const Duration(milliseconds: 1400)); + expect(done, isFalse); + async.elapse(const Duration(milliseconds: 200)); + expect(done, isTrue); + expect(error, isNull); + connection.dispose(); + radio.dispose(); + }); + }); + }); +} diff --git a/test/services/meshcore/connection_superseded_test.dart b/test/services/meshcore/connection_superseded_test.dart new file mode 100644 index 00000000..d60378f7 --- /dev/null +++ b/test/services/meshcore/connection_superseded_test.dart @@ -0,0 +1,142 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; + +import 'catalog_protocol_transport.dart'; +import 'fake_companion_transport.dart'; + +/// A connect workflow whose connection was disposed under it (an abandoned +/// reconnect, or a newer connect that took over) must leave the shared +/// transport alone. In one log the stale workflow failed seconds after the +/// user had connected again by hand, and its cleanup disconnected the new +/// link; its retried frames also went out on that new link. + +class _CountingTransport extends FakeCompanionTransport { + int disconnects = 0; + + @override + Future disconnect() async => disconnects++; +} + +class _CountingProtocolTransport extends CatalogProtocolTransport { + int disconnects = 0; + + @override + Future disconnect() async => disconnects++; +} + +void main() { + Future noModel(String _) async => throw UnimplementedError(); + + test('a disposed workflow failing does not disconnect the transport', () { + fakeAsync((async) { + final transport = _CountingTransport(); + final conn = MeshCoreConnection(transport: transport); + Object? error; + conn.connect(noModel).catchError((Object e) { + error = e; + return (deviceModel: null, deviceModelMatched: false); + }); + // Past the handshake delay: the device query is waiting for a reply. + async.elapse(const Duration(milliseconds: 600)); + expect(transport.writes, isNotEmpty); + + conn.dispose(); + async.elapse(const Duration(seconds: 6)); + + expect(error, isNotNull, reason: 'the stale workflow still fails'); + expect(transport.disconnects, 0, + reason: 'the transport belongs to whoever superseded this attempt'); + }); + }); + + test('a live workflow failing still disconnects the transport', () { + fakeAsync((async) { + final transport = _CountingTransport(); + final conn = MeshCoreConnection(transport: transport); + Object? error; + conn.connect(noModel).catchError((Object e) { + error = e; + return (deviceModel: null, deviceModelMatched: false); + }); + async.elapse(const Duration(seconds: 7)); + + expect(error, isNotNull); + expect(transport.disconnects, 1); + conn.dispose(); + }); + }); + + // An abandoned reconnect disposes its connection while the workflow sits + // in the auth step (the provider's callback awaits a GPS fix first). The + // callback then answers superseded, and the failure that follows must not + // close the link a connect the user started meanwhile is using. + group('disposed while the auth step is pending', () { + Future<({Object? error, int disconnects})> run( + {required bool disposeFirst}) async { + final transport = _CountingProtocolTransport(); + final conn = MeshCoreConnection(transport: transport); + final authStarted = Completer(); + final authAnswer = Completer?>(); + conn.onRequestAuth = () { + authStarted.complete(); + return authAnswer.future; + }; + Object? error; + final done = conn.connect((_) async => null).then((_) {}, + onError: (Object e) => error = e); + await authStarted.future; + if (disposeFirst) conn.dispose(); + authAnswer.complete({ + 'success': false, + 'reason': disposeFirst ? 'superseded' : 'outside_zone', + }); + await done; + if (!disposeFirst) conn.dispose(); + return (error: error, disconnects: transport.disconnects); + } + + test('the superseded attempt leaves the transport alone', () async { + final result = await run(disposeFirst: true); + expect(result.error.toString(), contains('AUTH_FAILED:superseded')); + expect(result.disconnects, 0); + }); + + test('a live attempt refused by auth still disconnects', () async { + final result = await run(disposeFirst: false); + expect(result.error.toString(), contains('AUTH_FAILED:outside_zone')); + expect(result.disconnects, 1); + }); + }); + + test('a disposed connection puts no frame on the transport', () { + fakeAsync((async) { + final transport = _CountingTransport(); + final conn = MeshCoreConnection(transport: transport); + conn.connect(noModel).catchError( + (Object e) => (deviceModel: null, deviceModelMatched: false)); + // Still inside the 500 ms handshake delay: nothing written yet. + async.elapse(const Duration(milliseconds: 100)); + expect(transport.writes, isEmpty); + + conn.dispose(); + async.elapse(const Duration(seconds: 7)); + + expect(transport.writes, isEmpty, + reason: 'a stale workflow must not write over a newer link'); + expect(transport.disconnects, 0); + }); + }); + + test('debug writes on a disposed connection are refused', () async { + final transport = _CountingTransport(); + final conn = MeshCoreConnection(transport: transport); + conn.dispose(); + await expectLater(conn.debugWriteRaw(Uint8List.fromList([0x16])), + throwsA(isA())); + expect(transport.writes, isEmpty); + }); +} diff --git a/test/services/meshcore/crypto_service_scope_key_test.dart b/test/services/meshcore/crypto_service_scope_key_test.dart new file mode 100644 index 00000000..a4ab87d7 --- /dev/null +++ b/test/services/meshcore/crypto_service_scope_key_test.dart @@ -0,0 +1,70 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/crypto_service.dart'; + +void main() { + group('CryptoService.deriveScopeKey', () { + test('preserves case: YOW and yow derive different keys', () { + final keyYOW = CryptoService.deriveScopeKey('YOW'); + final keyYow = CryptoService.deriveScopeKey('yow'); + + expect(keyYOW, isNotEmpty); + expect(keyYow, isNotEmpty); + expect(keyYOW.length, equals(16)); + expect(keyYow.length, equals(16)); + expect(keyYOW, isNot(keyYow)); + }); + + test('hash prefix equivalence: #yow and yow derive the same key', () { + final keyWithHash = CryptoService.deriveScopeKey('#yow'); + final keyWithoutHash = CryptoService.deriveScopeKey('yow'); + + expect(keyWithHash, equals(keyWithoutHash)); + }); + + test('known vector: #yow matches SHA256 first 16 bytes', () { + final key = CryptoService.deriveScopeKey('#yow'); + + // SHA256("#yow") = 77cb2a064167fca81a2c22cb4fd85dfb (from firmware) + final expectedKey = Uint8List.fromList([ + 0x77, 0xcb, 0x2a, 0x06, 0x41, 0x67, 0xfc, 0xa8, + 0x1a, 0x2c, 0x22, 0xcb, 0x4f, 0xd8, 0x5d, 0xfb, + ]); + + expect(key, equals(expectedKey)); + }); + + test('yow (without hash) also matches known vector', () { + final key = CryptoService.deriveScopeKey('yow'); + + // Should match the same vector as #yow + final expectedKey = Uint8List.fromList([ + 0x77, 0xcb, 0x2a, 0x06, 0x41, 0x67, 0xfc, 0xa8, + 0x1a, 0x2c, 0x22, 0xcb, 0x4f, 0xd8, 0x5d, 0xfb, + ]); + + expect(key, equals(expectedKey)); + }); + + test('uppercase YOW derives different key from lowercase yow', () { + final keyYOW = CryptoService.deriveScopeKey('YOW'); + final keyYow = CryptoService.deriveScopeKey('yow'); + + // SHA256("#YOW") should be different from SHA256("#yow") + expect(keyYOW, isNot(keyYow)); + expect(keyYOW.length, equals(16)); + expect(keyYow.length, equals(16)); + }); + + test('mixed case is preserved', () { + final keyMixed1 = CryptoService.deriveScopeKey('BrQ'); + final keyMixed2 = CryptoService.deriveScopeKey('brq'); + final keyMixed3 = CryptoService.deriveScopeKey('BRQ'); + + expect(keyMixed1, isNot(keyMixed2)); + expect(keyMixed1, isNot(keyMixed3)); + expect(keyMixed2, isNot(keyMixed3)); + }); + }); +} diff --git a/test/services/meshcore/disc_tracker_reply_time_test.dart b/test/services/meshcore/disc_tracker_reply_time_test.dart new file mode 100644 index 00000000..f8488afc --- /dev/null +++ b/test/services/meshcore/disc_tracker_reply_time_test.dart @@ -0,0 +1,154 @@ +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/disc_tracker.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; + +import 'fake_companion_transport.dart'; +import 'scope_test_support.dart'; + +/// A discovery response as the radio pushes it: [status][flags][snr][tag:4] +/// [pubkey:32]. +Uint8List _reply(List tag, int keyFill, + {int type = DiscoveryConstants.nodeTypeRepeater}) => + Uint8List.fromList([ + 0, + DiscoveryConstants.discoverRespFlag | type, + 20, + ...tag, + ...List.filled(32, keyFill), + ]); + +/// The discovery write reaches the radio at once but its acknowledged write +/// completes only 500 ms later, the way a BLE write with response does. +class _SlowAckRadio extends FakeCompanionTransport { + @override + Future write(Uint8List data) async { + writes.add(Uint8List.fromList(data)); + if (data.isNotEmpty && data.first == CommandCodes.sendControlData) { + await Future.delayed(const Duration(milliseconds: 500)); + } + } +} + +void main() { + const own = [1, 2, 3, 4]; + const foreign = [9, 9, 9, 9]; + + test('own-tag replies carry their time after the send; foreign ones none', + () { + fakeAsync((async) { + final tracker = DiscTracker(hopBytes: 1); + tracker.startTracking( + tag: Uint8List.fromList(own), sentAt: clock.now()); + async.elapse(const Duration(milliseconds: 300)); + tracker.handlePacket(_reply(own, 0x11), 5, -80); + async.elapse(const Duration(milliseconds: 900)); + tracker.handlePacket(_reply(own, 0x22), 5, -80); + tracker.handlePacket(_reply(foreign, 0x33), 5, -80); + final nodes = {for (final n in tracker.stopTracking()) n.repeaterId: n}; + expect(nodes['11']!.discoveryReplyAfter, + const Duration(milliseconds: 300)); + expect(nodes['22']!.discoveryReplyAfter, + const Duration(milliseconds: 1200)); + expect(nodes['33']!.discoveryReplyAfter, isNull, + reason: 'another phone\'s discovery: accepted, no reply time'); + }); + }); + + test('a better-SNR foreign reply keeps the own reply time', () { + fakeAsync((async) { + final tracker = DiscTracker(hopBytes: 1); + tracker.startTracking( + tag: Uint8List.fromList(own), sentAt: clock.now()); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(_reply(own, 0x11), 2, -80); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(_reply(foreign, 0x11), 9, -80); + final node = tracker.stopTracking().single; + expect(node.localSnr, 9); + expect(node.discoveryReplyAfter, const Duration(milliseconds: 400)); + }); + }); + + test('one-byte ids shared by two keys never share a reply time', () { + Uint8List reply(List tag, int second, {required bool own}) => + Uint8List.fromList([ + 0, + DiscoveryConstants.discoverRespFlag | + DiscoveryConstants.nodeTypeRepeater, + 20, + ...tag, + 0xAA, + second, + ...List.filled(30, 0x33), + ]); + fakeAsync((async) { + // Own AA01 first, then a stronger foreign AA02 replaces it. + final tracker = DiscTracker(hopBytes: 1); + tracker.startTracking( + tag: Uint8List.fromList(own), sentAt: clock.now()); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(reply(own, 0x01, own: true), 2, -80); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(reply(foreign, 0x02, own: false), 9, -80); + final node = tracker.stopTracking().single; + expect(node.pubkeyFull.substring(0, 4), 'AA02'); + expect(node.discoveryReplyAfter, isNull); + }); + fakeAsync((async) { + // Foreign AA02 first, then a weaker own AA01: no timing copied over. + final tracker = DiscTracker(hopBytes: 1); + tracker.startTracking( + tag: Uint8List.fromList(own), sentAt: clock.now()); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(reply(foreign, 0x02, own: false), 9, -80); + async.elapse(const Duration(milliseconds: 400)); + tracker.handlePacket(reply(own, 0x01, own: true), 2, -80); + final node = tracker.stopTracking().single; + expect(node.pubkeyFull.substring(0, 4), 'AA02'); + expect(node.discoveryReplyAfter, isNull); + }); + }); + + test('no sentAt: no reply times at all', () { + fakeAsync((async) { + final tracker = DiscTracker(hopBytes: 1); + tracker.startTracking(tag: Uint8List.fromList(own)); + async.elapse(const Duration(milliseconds: 300)); + tracker.handlePacket(_reply(own, 0x11), 5, -80); + expect(tracker.stopTracking().single.discoveryReplyAfter, isNull); + }); + }); + + test('a write held behind a gate is timed from after the gate', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + ({Uint8List tag, DateTime sentAt})? sent; + conn.sendDiscoveryRequest().then((s) => sent = s); + async.elapse(const Duration(seconds: 1)); + expect(radio.commands, isEmpty, reason: 'parked at the lease gate'); + final releasedAt = clock.now(); + lease.release(); + async.flushMicrotasks(); + expect(sent, isNotNull); + expect(sent!.sentAt, releasedAt); + expect(sent!.tag, radio.writes.single.sublist(3, 7)); + }); + }); + + test('a write acked 500 ms later is still timed from its submission', () { + onScopeClock(_SlowAckRadio.new, (async, radio, conn) { + final submittedAt = clock.now(); + ({Uint8List tag, DateTime sentAt})? sent; + conn.sendDiscoveryRequest().then((s) => sent = s); + async.elapse(const Duration(milliseconds: 499)); + expect(sent, isNull); + async.elapse(const Duration(milliseconds: 1)); + expect(sent, isNotNull); + expect(sent!.sentAt, submittedAt); + }); + }); +} diff --git a/test/services/meshcore/frame_log_redaction_test.dart b/test/services/meshcore/frame_log_redaction_test.dart new file mode 100644 index 00000000..ef244bf8 --- /dev/null +++ b/test/services/meshcore/frame_log_redaction_test.dart @@ -0,0 +1,35 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; + +import 'scope_test_support.dart'; + +/// Debug logs ship with bug reports, and a public key is logged by its +/// 8-hex prefix only. The per-frame dump must keep to that for the frames +/// that carry a full contact record. +void main() { + final key = Uint8List.fromList([for (var i = 0; i < 32; i++) 0x10 + i]); + String hex(Iterable bytes) => + bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '); + + for (final code in [ResponseCodes.contact, PushCodes.newAdvert]) { + test('a frame 0x${code.toRadixString(16)} logs the key prefix only', () { + final lines = captureScopeLog(); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final payload = scopeContactPayload(pubkey: key); + radio.emit([code, ...payload]); + async.flushMicrotasks(); + }); + final frameLines = + lines.where((l) => l.contains('[CONN] Frame 0x')).toList(); + expect(frameLines, hasLength(1)); + expect(frameLines.single, contains(hex([code, ...key.sublist(0, 4)]))); + final rest = hex(key.sublist(4)); + for (final line in lines) { + expect(line, isNot(contains(rest))); + expect(line, isNot(contains(hex(key.sublist(4, 8))))); + } + }); + } +} diff --git a/test/services/meshcore/ignored_frames_test.dart b/test/services/meshcore/ignored_frames_test.dart new file mode 100644 index 00000000..cd35ed5d --- /dev/null +++ b/test/services/meshcore/ignored_frames_test.dart @@ -0,0 +1,55 @@ +import 'package:flutter/foundation.dart' show debugPrint; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/utils/debug_logger_io.dart'; + +import 'fake_companion_transport.dart'; + +/// Frames the app deliberately ignores are recorded by the per-frame line +/// only. "Unhandled frame" is kept for codes the app does not know. +void main() { + late FakeCompanionTransport transport; + late MeshCoreConnection connection; + late List lines; + + setUp(() { + transport = FakeCompanionTransport(); + connection = MeshCoreConnection(transport: transport); + lines = []; + final originalDebugPrint = debugPrint; + final originalEnabled = DebugLogger.isEnabled; + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) lines.add(message); + }; + DebugLogger.setEnabled(true); + addTearDown(() { + debugPrint = originalDebugPrint; + DebugLogger.setEnabled(originalEnabled); + }); + }); + + tearDown(() { + connection.dispose(); + transport.dispose(); + }); + + for (final code in [0x80, 0x83, 0x0a, 0x11, 0x8a, 0x8f, 0x16]) { + test('code 0x${code.toRadixString(16)} is not logged as unhandled', + () async { + transport.emit([code, 0x01, 0x02, 0x03]); + await transport.settle(); + + expect(lines.any((l) => l.contains('[CONN] Frame 0x')), isTrue); + expect(lines.where((l) => l.contains('Unhandled frame')), isEmpty); + expect(lines.where((l) => l.startsWith('ERROR:')), isEmpty); + }); + } + + test('a genuinely unknown code is still logged as unhandled', () async { + transport.emit([0x7E, 0x01]); + await transport.settle(); + + expect(lines.where((l) => l.contains('Unhandled frame: code=126')), + hasLength(1)); + }); +} diff --git a/test/services/meshcore/packet_metadata_too_short_test.dart b/test/services/meshcore/packet_metadata_too_short_test.dart new file mode 100644 index 00000000..11f5bb87 --- /dev/null +++ b/test/services/meshcore/packet_metadata_too_short_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/meshcore/packet_metadata.dart'; +import 'package:mesh_mapper/services/meshcore/packet_validator.dart'; +import 'package:mesh_mapper/services/meshcore/rx_logger.dart'; +import 'package:mesh_mapper/services/meshcore/tx_tracker.dart'; +import 'package:mesh_mapper/services/meshcore/unified_rx_handler.dart'; +import 'package:mesh_mapper/utils/debug_logger_io.dart'; + +/// A truncated packet off the air is routine. It is skipped with a plain +/// log line, not reported as an error with a stack trace. +void main() { + PacketMetadata parse(List bytes) => PacketMetadata.fromRawPacket( + raw: Uint8List.fromList(bytes), + snr: 5.0, + rssi: -90, + ); + + test('a path longer than the packet throws PacketTooShortException', () { + // Flood header, pathLen says 3 one-byte hops, only one hop byte present. + expect(() => parse([0x15, 0x03, 0xAA]), + throwsA(isA())); + }); + + test('an empty or header-only packet throws PacketTooShortException', () { + expect(() => parse(const []), throwsA(isA())); + expect(() => parse([0x15]), throwsA(isA())); + // Transport flood needs 4 transport code bytes before pathLen. + expect(() => parse([0x14, 0x00, 0x00]), + throwsA(isA())); + }); + + test('a complete packet still parses', () { + final m = parse([0x15, 0x01, 0xAA, 0x01, 0x02]); + expect(m.pathHashCount, 1); + expect(m.encryptedPayload, [0x01, 0x02]); + }); + + test('the unified handler skips a short packet without an error log', + () async { + final lines = []; + final originalPrint = debugPrint; + DebugLogger.setEnabled(true); + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) lines.add(message); + }; + addTearDown(() { + debugPrint = originalPrint; + DebugLogger.setEnabled(false); + }); + + final handler = UnifiedRxHandler( + txTracker: TxTracker(), + rxLogger: RxLogger( + onRxEntry: (_) async {}, + getGpsLocation: () => + (lat: 0.0, lon: 0.0, altitude: const FixAltitude.unknown()), + ), + validator: PacketValidator(allowedChannels: const {}), + ); + handler.startListening(); + + await handler.handlePacket( + Uint8List.fromList([0x15, 0x03, 0xAA]), 5.0, -90); + + expect(lines.where((l) => l.startsWith('ERROR:')), isEmpty); + expect(lines.any((l) => l.contains('[UNIFIED RX]') && l.contains('short')), + isTrue); + }); +} diff --git a/test/services/meshcore/packet_validator_ciphertext_length_test.dart b/test/services/meshcore/packet_validator_ciphertext_length_test.dart new file mode 100644 index 00000000..9f6a9327 --- /dev/null +++ b/test/services/meshcore/packet_validator_ciphertext_length_test.dart @@ -0,0 +1,68 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/crypto_service.dart'; +import 'package:mesh_mapper/services/meshcore/packet_metadata.dart'; +import 'package:mesh_mapper/services/meshcore/packet_validator.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; + +/// AES-ECB works on whole 16-byte blocks. A GRP_TXT whose ciphertext is not +/// a block multiple is malformed and must be dropped before decryption, +/// rather than reaching the cipher and failing with "Input buffer too short". +void main() { + final key = Uint8List.fromList(List.generate(16, (i) => i + 1)); + final hash = CryptoService.computeChannelHash(key); + + PacketValidator validator() => PacketValidator(allowedChannels: { + hash: ChannelInfo(channelName: '#wardriving', key: key, hash: hash), + }); + + PacketMetadata groupText(List ciphertext) { + const header = + (PayloadType.grpTxt << PacketHeader.typeShift) | RouteType.flood; + return PacketMetadata.fromRawPacket( + raw: Uint8List.fromList([ + header, + 0x00, // no hops + hash, + 0, 0, // MAC + ...ciphertext, + ]), + snr: 5.0, + rssi: -90, + ); + } + + test('ciphertext length check accepts only whole AES blocks', () { + expect(CryptoService.isValidCiphertextLength(0), isFalse); + expect(CryptoService.isValidCiphertextLength(15), isFalse); + expect(CryptoService.isValidCiphertextLength(17), isFalse); + expect(CryptoService.isValidCiphertextLength(16), isTrue); + expect(CryptoService.isValidCiphertextLength(32), isTrue); + }); + + test('a 17-byte ciphertext is dropped before decryption', () async { + final result = + await validator().validate(groupText(List.filled(17, 0xAA))); + expect(result.valid, isFalse); + expect(result.reason, 'bad ciphertext length'); + }); + + test('an empty ciphertext is dropped before decryption', () async { + final result = await validator().validate(groupText(const [])); + expect(result.valid, isFalse); + expect(result.reason, 'bad ciphertext length'); + }); + + test('a 32-byte ciphertext decrypts and is kept', () async { + final plain = Uint8List.fromList( + [0, 0, 0, 0, 0, ...'MM:hello wardriving'.codeUnits]); // 24 bytes + final encrypted = CryptoService.encryptChannelMessage(plain, key); + expect(encrypted.length, 32); + + final result = await validator().validate(groupText(encrypted)); + expect(result.reason, isNot('bad ciphertext length')); + expect(result.valid, isTrue); + expect(result.plaintext, startsWith('MM:hello wardriving')); + }); +} diff --git a/test/services/meshcore/repeater_admin_frames_test.dart b/test/services/meshcore/repeater_admin_frames_test.dart index 54e7eb09..e2a4fca2 100644 --- a/test/services/meshcore/repeater_admin_frames_test.dart +++ b/test/services/meshcore/repeater_admin_frames_test.dart @@ -350,6 +350,63 @@ void main() { expect((await second).single.publicKeyHex, '09' * 32); }); + test('a list that streams longer than the silence window still completes', + () async { + // The radio streams about one contact per 60 ms, so a 350 entry table + // runs past any fixed total. Each frame keeps the read alive. + final future = connection.getContacts( + silenceTimeout: const Duration(milliseconds: 80), + timeout: const Duration(seconds: 5)); + await transport.settle(); + transport.emit([ResponseCodes.contactsStart, 8, 0, 0, 0]); + for (var i = 1; i <= 8; i++) { + await Future.delayed(const Duration(milliseconds: 40)); + transport.emit( + [ResponseCodes.contact, ...contactPayload(pubkey: key(i))]); + } + await Future.delayed(const Duration(milliseconds: 40)); + transport.emit([ResponseCodes.endOfContacts, 0, 0, 0, 0]); + expect((await future).length, 8); + }); + + test('a stream that goes quiet times out after the silence window', + () async { + final future = connection.getContacts( + silenceTimeout: const Duration(milliseconds: 80), + timeout: const Duration(seconds: 5)); + await transport.settle(); + transport.emit([ResponseCodes.contactsStart, 2, 0, 0, 0]); + transport.emit( + [ResponseCodes.contact, ...contactPayload(pubkey: key(1))]); + await expectLater(future, throwsA(isA())); + expect(connection.hasPendingAdminCommand, isFalse); + }); + + test('no reply at all times out after the silence window', () async { + final future = connection.getContacts( + silenceTimeout: const Duration(milliseconds: 80), + timeout: const Duration(seconds: 5)); + await expectLater(future, throwsA(isA())); + }); + + test('a stream that never ends hits the overall ceiling', () async { + final future = connection.getContacts( + silenceTimeout: const Duration(milliseconds: 80), + timeout: const Duration(milliseconds: 300)); + await transport.settle(); + transport.emit([ResponseCodes.contactsStart, 99, 0, 0, 0]); + var done = false; + unawaited(future.then((_) {}, onError: (_) {}).whenComplete(() { + done = true; + })); + for (var i = 1; i <= 20 && !done; i++) { + await Future.delayed(const Duration(milliseconds: 30)); + transport.emit( + [ResponseCodes.contact, ...contactPayload(pubkey: key(i))]); + } + await expectLater(future, throwsA(isA())); + }); + test('ERR while iterating fails with the radio code', () async { final future = connection.getContacts(); await transport.settle(); @@ -470,12 +527,14 @@ void main() { }); group('SENT', () { - test('a 10-byte SENT still completes the legacy send completer', () async { + test('a stray SENT is harmless and a channel send completes on its OK', + () async { final future = connection.sendChannelTextMessage(0, 1, 0, 'hi'); await transport.settle(); transport.emit( [ResponseCodes.sent, 1, 0xDE, 0xAD, 0xBE, 0xEF, 0x10, 0x27, 0, 0]); - await future; + transport.emit([ResponseCodes.ok]); + await future.timeout(const Duration(seconds: 1)); }); }); diff --git a/test/services/meshcore/rx_logger_altitude_test.dart b/test/services/meshcore/rx_logger_altitude_test.dart new file mode 100644 index 00000000..34cc9242 --- /dev/null +++ b/test/services/meshcore/rx_logger_altitude_test.dart @@ -0,0 +1,104 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/meshcore/packet_metadata.dart'; +import 'package:mesh_mapper/services/meshcore/packet_validator.dart'; +import 'package:mesh_mapper/services/meshcore/rx_logger.dart'; + +/// An RX row keeps the altitude, reference and accuracy of the FIRST location +/// it was heard at, exactly as it keeps that location's coordinates, even when +/// a later, stronger observation replaces the SNR. + +/// Accepts every packet. This test is about the location trio, not about +/// decryption, so the real validator (channel key, AES, printable ratio) is +/// bypassed; the logger's own pre-validator gates (flood route, a path) still +/// apply and these bytes pass them. +class _AcceptAll extends PacketValidator { + _AcceptAll() : super(allowedChannels: const {}); + + @override + Future validate(PacketMetadata metadata, + {bool skipRssiCheck = false}) async => + ValidationResult.success(); +} + +void main() { + // The flood packet from rx_logger_direct_route_test.dart: header 0x1D, + // path 7463 -> 850C (2 hops, 2 bytes each), then the payload. The last hop + // 850C is the repeater credited. + const packetBytes = [ + 0x1D, 0x42, 0x74, 0x63, 0x85, 0x0C, 0xD1, 0x88, 0x9E, 0x55, 0x36, 0xCE, // + 0xFC, 0x27, 0x39, 0x6C, 0xE4, 0xE3, 0x05, 0xCF, 0x54, 0x91, 0x1C, + 0x87, 0x78, 0x51, 0xA6, 0xE4, 0x0A, 0x95, 0xA9, 0x8E, 0x78, 0x3D, + ]; + + PacketMetadata packet(double snr) => PacketMetadata.fromRawPacket( + raw: Uint8List.fromList(packetBytes), + snr: snr, + rssi: -80, + ); + + test('the first location\'s altitude trio rides to the API entry', () async { + final entries = []; + var fixes = 0; + final logger = RxLogger( + onRxEntry: (e) async => entries.add(e), + getGpsLocation: () { + fixes++; + return fixes == 1 + ? ( + lat: 45.0, + lon: -75.0, + altitude: FixAltitude.known( + meters: 84.0, + reference: AltitudeReference.msl, + accuracy: 6.0), + ) + : (lat: 45.1, lon: -75.1, altitude: const FixAltitude.unknown()); + }, + ); + logger.startWardriving(); + final validator = _AcceptAll(); + + expect(await logger.handlePacket(packet(5.0), validator), isTrue); + expect(await logger.handlePacket(packet(9.0), validator), isTrue, + reason: 'better SNR, heard at a new fix'); + await logger.flushAllBatches(); + + expect(entries, hasLength(1)); + final e = entries.single; + expect(e.repeaterId, '850C'); + expect(e.snr, 9.0, reason: 'the better SNR wins'); + expect(e.lat, 45.0, reason: 'the FIRST location wins'); + expect(e.altitude.meters, 84.0); + expect(e.altitude.reference, AltitudeReference.msl); + expect(e.altitude.accuracy, 6.0); + }); + + test('an unknown altitude at the first fix stays unknown even when a later ' + 'fix knew it', () async { + final entries = []; + var fixes = 0; + final logger = RxLogger( + onRxEntry: (e) async => entries.add(e), + getGpsLocation: () { + fixes++; + return fixes == 1 + ? (lat: 45.0, lon: -75.0, altitude: const FixAltitude.unknown()) + : ( + lat: 45.1, + lon: -75.1, + altitude: FixAltitude.known( + meters: 84.0, reference: AltitudeReference.msl), + ); + }, + ); + logger.startWardriving(); + final validator = _AcceptAll(); + await logger.handlePacket(packet(5.0), validator); + await logger.handlePacket(packet(9.0), validator); + await logger.flushAllBatches(); + expect(entries.single.altitude.isKnown, isFalse); + }); +} diff --git a/test/services/meshcore/rx_logger_direct_route_test.dart b/test/services/meshcore/rx_logger_direct_route_test.dart new file mode 100644 index 00000000..c8275358 --- /dev/null +++ b/test/services/meshcore/rx_logger_direct_route_test.dart @@ -0,0 +1,66 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/meshcore/packet_metadata.dart'; +import 'package:mesh_mapper/services/meshcore/packet_validator.dart'; +import 'package:mesh_mapper/services/meshcore/rx_logger.dart'; + +/// A direct packet's path is the route it still has to travel, not the hops +/// it came through. A user heard a nearby radio's login request addressed via +/// 7463 then 850C at RSSI 0, and the app blamed 850C (15 km away) as a +/// possible carpeater. These bytes are that packet from the log. +void main() { + // Path 7463 -> 850C (2 hops, 2 bytes each), then the ANON_REQ payload. + const pathAndPayload = [ + 0x42, 0x74, 0x63, 0x85, 0x0C, 0xD1, 0x88, 0x9E, 0x55, 0x36, 0xCE, // + 0xFC, 0x27, 0x39, 0x6C, 0xE4, 0xE3, 0x05, 0xCF, 0x54, 0x91, 0x1C, + 0x87, 0x78, 0x51, 0xA6, 0xE4, 0x0A, 0x95, 0xA9, 0x8E, 0x78, 0x3D, + ]; + + late List drops; + late RxLogger logger; + final validator = PacketValidator(allowedChannels: const {}); + + setUp(() { + drops = []; + logger = RxLogger( + onRxEntry: (_) async {}, + getGpsLocation: () => + (lat: 53.4903, lon: 8.0317, altitude: const FixAltitude.unknown()), + onCarpeaterDrop: (id, _) => drops.add(id), + ); + logger.startWardriving(); + }); + + PacketMetadata packet(List bytes) => PacketMetadata.fromRawPacket( + raw: Uint8List.fromList(bytes), + snr: 13.0, + rssi: 0, + ); + + test('a direct packet never blames a hop on its route', () async { + // Header 0x1E: route type 2 (direct), payload type ANON_REQ. + final logged = + await logger.handlePacket(packet([0x1E, ...pathAndPayload]), validator); + expect(logged, isFalse); + expect(drops, isEmpty); + }); + + test('a transport direct packet never blames a hop on its route', () async { + // Header 0x1F: route type 3, with 4 transport code bytes before the path. + final logged = await logger.handlePacket( + packet([0x1F, 0x00, 0x00, 0x00, 0x00, ...pathAndPayload]), validator); + expect(logged, isFalse); + expect(drops, isEmpty); + }); + + test('a flood packet this strong still trips the carpeater failsafe', + () async { + // Header 0x1D: route type 1 (flood). Here the last hop really did send it. + final logged = + await logger.handlePacket(packet([0x1D, ...pathAndPayload]), validator); + expect(logged, isFalse); + expect(drops, ['850C']); + }); +} diff --git a/test/services/meshcore/scope_lease_test.dart b/test/services/meshcore/scope_lease_test.dart new file mode 100644 index 00000000..2faef880 --- /dev/null +++ b/test/services/meshcore/scope_lease_test.dart @@ -0,0 +1,1111 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/buffer_utils.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; + +import 'scope_test_support.dart'; + +/// The radio lease for scope requests: the per-command reply ledger, the +/// contact stream state, admission, the lease gate and deadline, and the +/// answer wait outside the lease. +void main() { + final key = scopeKey(0xAB); + final request = Uint8List.fromList([0x01, 0x00]); + final flood16 = Uint8List(16); + + Uint8List bytes(List b) => Uint8List.fromList(b); + + ScopeRequestOutcome? Function() ask(FakeAsync async, ScopeLease lease, + {Duration? answerWait = const Duration(seconds: 7), DateTime? notAfter}) { + ScopeRequestOutcome? outcome; + lease + .requestScopes(key, request, + answerWait: answerWait, + notAfter: notAfter ?? clock.now().add(const Duration(seconds: 30))) + .then((o) => outcome = o); + async.flushMicrotasks(); + return () => outcome; + } + + ContactRecord record(Uint8List payload) => + ContactRecord.parse(BufferReader(payload)); + + group('reply shape', () { + CommandReplyShape shape(List frame) => + MeshCoreConnection.replyShapeOf(bytes(frame)); + + test('a command earns one reply by default', () { + final s = shape([CommandCodes.setFloodScope, 0, ...flood16]); + expect(s.replies, 1); + expect(s.selfTelemetry, isFalse); + expect(s.opensContactStream, isFalse); + }); + + test('getContacts earns one initial reply and opens a stream', () { + final s = shape([CommandCodes.getContacts, 0, 0, 0, 0]); + expect(s.replies, 1); + expect(s.opensContactStream, isTrue); + }); + + test('self telemetry (4 bytes) is answered by push 0x8B', () { + final self = shape([CommandCodes.sendTelemetryReq, 0, 0, 0]); + expect(self.replies, 1); + expect(self.selfTelemetry, isTrue); + final remote = shape([CommandCodes.sendTelemetryReq, 0, 0, 0, ...key]); + expect(remote.replies, 1); + expect(remote.selfTelemetry, isFalse); + }); + + test('reboot, factory reset and CLI reboot answer nothing', () { + expect(shape([CommandCodes.reboot, ...utf8.encode('reboot')]).replies, 0); + expect(shape([CommandCodes.reboot, ...utf8.encode('rebut!')]).replies, 1); + expect( + shape([CommandCodes.factoryReset, ...utf8.encode('reset')]).replies, + 0); + expect( + shape([CommandCodes.factoryReset, ...utf8.encode('nope!')]).replies, + 1); + expect( + shape([CommandCodes.runCliCommand, ...utf8.encode('reboot')]).replies, + 0); + expect( + shape([CommandCodes.runCliCommand, ...utf8.encode('01|reboot')]) + .replies, + 0); + expect( + shape([CommandCodes.runCliCommand, ...utf8.encode('get name')]) + .replies, + 1); + }); + + test('deviceQuery writes two commands and records two replies', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.deviceQuery(4).then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + expect( + radio.commands, [CommandCodes.deviceQuery, CommandCodes.appStart]); + expect(conn.repliesOwedCount, 2); + async.elapse(const Duration(seconds: 11)); + }); + }); + }); + + group('reply ledger', () { + test('a low frame retires the oldest entry, a push retires nothing', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + conn.getBatteryVoltage(); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 2); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 1); + radio.emit([PushCodes.logRxData, 0, 0, 1, 2]); + radio.emit([PushCodes.telemetryResponse, 0, 1, 2, 3, 4, 5, 6]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 1, + reason: '0x8B is a reply only to a self-telemetry request'); + radio.emit([ResponseCodes.batteryVoltage, 0xA0, 0x0F]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 0); + }); + }); + + test('push 0x8B retires a self-telemetry entry', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes([CommandCodes.sendTelemetryReq, 0, 0, 0])); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 1); + radio.emit([PushCodes.telemetryResponse, 0, 1, 2, 3, 4, 5, 6]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 0); + }); + }); + + test('an entry expires 10 s after its write returns, never before', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + async.flushMicrotasks(); + async.elapse(const Duration(milliseconds: 9999)); + expect(conn.repliesOwedCount, 1); + async.elapse(const Duration(milliseconds: 1)); + expect(conn.repliesOwedCount, 0); + + // A write that never returns stays owed. + radio.stallCommands.add(CommandCodes.setFloodScope); + conn.setFloodScope(flood16); + async.elapse(const Duration(seconds: 60)); + expect(conn.repliesOwedCount, 1); + // Owed, but not to a scope lease: Manage does not wait for it. + expect(conn.hasScopeReplyDebt, isFalse); + }); + }); + + test('a config write owed during a contact stream is not retired by END', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes([CommandCodes.getContacts, 0, 0, 0, 0])); + conn.setFloodScope(flood16); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 2); + radio.emit([ResponseCodes.contactsStart, 1, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 1, reason: 'START retires getContacts'); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + radio.emit([ResponseCodes.endOfContacts, 0, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 1, + reason: 'streamed CONTACT and END retire nothing'); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 0); + }); + }); + }); + + group('contact stream', () { + final getContacts = [CommandCodes.getContacts, 0, 0, 0, 0]; + + test('requested, open, then none on END', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(conn.contactsStreamState, ContactsStreamState.none); + conn.debugWriteRaw(bytes(getContacts)); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.requested); + radio.emit([ResponseCodes.contactsStart, 0, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.open); + radio.emit([ResponseCodes.endOfContacts, 0, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.none); + }); + }); + + test('a throwing write is ambiguous: the stream stays requested', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + // The transport cannot say whether a throw came before or after + // sending, so even a throw before sending keeps the stream owed. + radio.failWrites = true; + conn.debugWriteRaw(bytes(getContacts)).then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.requested); + // No frame ever comes: the silence rule suspends scope discovery. + async.elapse(const Duration(seconds: 60)); + expect(conn.isScopeDiscoverySuspended, isTrue); + expect(grant(async, conn, wait: const Duration(milliseconds: 200)), + isNull); + }); + }); + + test( + 'a stream delivered before the write threw still opens and blocks ' + 'the lease', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + radio.failAfterSend = true; + Object? error; + conn.debugWriteRaw(bytes(getContacts)).then((_) {}, + onError: (Object e) { + error = e; + }); + async.flushMicrotasks(); + radio.failAfterSend = false; + expect(error, isA()); + expect(conn.contactsStreamState, ContactsStreamState.requested); + + radio.emit([ResponseCodes.contactsStart, 2, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.open); + expect(conn.repliesOwedCount, 0); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + // A lease attempt mid-stream is refused: a streamed CONTACT must + // never be taken as a lookup reply. + expect(grant(async, conn, wait: const Duration(milliseconds: 200)), + isNull); + expect(radio.writes.length, 1); + radio.emit(contactFrame(scopeContactPayload(pubkey: scopeKey(0x22)))); + radio.emit([ResponseCodes.endOfContacts, 0, 0, 0, 0]); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.none); + expect(grant(async, conn), isNotNull); + }); + }); + + test('none when the initial reply is ERR', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes(getContacts)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.badState]); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.none); + expect(conn.repliesOwedCount, 0); + }); + }); + + test('none when an APP_START is written while open', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes(getContacts)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.contactsStart, 0, 0, 0, 0]); + async.flushMicrotasks(); + conn.sendCommandAppStart(); + async.flushMicrotasks(); + expect(conn.contactsStreamState, ContactsStreamState.none); + }); + }); + + test('a stream silent for 60 s suspends scope discovery until reconnect', + () { + final lines = captureScopeLog(); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes(getContacts)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.contactsStart, 0, 0, 0, 0]); + async.elapse(const Duration(seconds: 59)); + expect(conn.isScopeDiscoverySuspended, isFalse); + async.elapse(const Duration(seconds: 1)); + expect(conn.isScopeDiscoverySuspended, isTrue); + async.elapse(const Duration(seconds: 120)); + expect(grant(async, conn), isNull); + expect(conn.contactsStreamState, ContactsStreamState.open, + reason: 'not silently cleared'); + + conn.disconnect(); + async.flushMicrotasks(); + expect(conn.isScopeDiscoverySuspended, isFalse); + }); + expect( + lines + .where((l) => + l.contains('[SCOPES]') && + l.contains('suspended until reconnect')) + .length, + 1); + // A fresh connection object starts clean. + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(grant(async, conn), isNotNull); + }); + }); + }); + + group('radio restart', () { + for (final entry in >{ + 'reboot': [CommandCodes.reboot, ...utf8.encode('reboot')], + 'factory reset': [CommandCodes.factoryReset, ...utf8.encode('reset')], + 'CLI reboot': [CommandCodes.runCliCommand, ...utf8.encode('reboot')], + }.entries) { + test('after a ${entry.key} no lease is admitted until reconnect', () { + final lines = captureScopeLog(); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes(entry.value)); + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 0); + expect(conn.isScopeDiscoverySuspended, isTrue); + expect(grant(async, conn), isNull); + async.elapse(const Duration(seconds: 30)); + conn.disconnect(); + async.flushMicrotasks(); + expect(grant(async, conn), isNull, + reason: 'only a new connection object clears it'); + }); + expect( + lines.any((l) => + l.contains('[SCOPES] Lease not admitted') && + l.contains('reboot or reset')), + isTrue); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(grant(async, conn), isNotNull); + }); + }); + } + + test('reboot() blocks the lease', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.reboot(); + async.flushMicrotasks(); + expect(grant(async, conn), isNull); + }); + }); + + test('a reboot payload that is not the magic word blocks nothing', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw( + bytes([CommandCodes.reboot, ...utf8.encode('rebut!')])); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.illegalArg]); + async.flushMicrotasks(); + expect(grant(async, conn), isNotNull); + }); + }); + }); + + group('admission', () { + test('a cancel (Stop) during the debt wait grants nothing', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + final cancel = ScopeCancelToken(); + ScopeLease? lease; + var done = false; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), cancel: cancel) + .then((l) { + lease = l; + done = true; + }); + async.elapse(const Duration(milliseconds: 200)); + expect(done, isFalse); + cancel.cancel(); + async.flushMicrotasks(); + expect(done, isTrue); + expect(lease, isNull); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(seconds: 1)); + expect(conn.isScopeLeaseActive, isFalse); + + // A replacement runner is admitted normally. + expect(grant(async, conn), isNotNull); + }); + }); + + test('a hard stop during the poll drain grants nothing', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.getNoiseFloor().then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + final cancel = ScopeCancelToken(); + ScopeLease? lease; + var done = false; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), cancel: cancel) + .then((l) { + lease = l; + done = true; + }); + async.elapse(const Duration(milliseconds: 100)); + cancel.cancel(); + async.flushMicrotasks(); + expect(done, isTrue); + expect(lease, isNull); + expect(conn.isScopeLeaseActive, isFalse); + }); + }); + + test('a disconnect during admission grants nothing', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + ScopeLease? lease; + var done = false; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), + cancel: ScopeCancelToken()) + .then((l) { + lease = l; + done = true; + }); + async.elapse(const Duration(milliseconds: 100)); + conn.disconnect(); + async.elapse(const Duration(milliseconds: 100)); + expect(done, isTrue); + expect(lease, isNull); + }); + }); + + test('a lease handed to an already cancelled runner is released at once', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final cancel = ScopeCancelToken(); + final lease = grant(async, conn, cancel: cancel)!; + conn.setFloodScope(flood16); + async.flushMicrotasks(); + expect(radio.writes, isEmpty, reason: 'parked at the lease gate'); + cancel.cancel(); + async.flushMicrotasks(); + expect(lease.active, isFalse); + expect(radio.commands, [CommandCodes.setFloodScope]); + }); + }); + + test('refused while a sign is in progress', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.sign(Uint8List(32)).then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + expect(grant(async, conn, wait: const Duration(milliseconds: 200)), + isNull); + async.elapse(const Duration(seconds: 6)); + }); + }); + + test('refused while a contact stream is open', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.debugWriteRaw(bytes([CommandCodes.getContacts, 0, 0, 0, 0])); + async.flushMicrotasks(); + radio.emit([ResponseCodes.contactsStart, 0, 0, 0, 0]); + async.flushMicrotasks(); + expect(grant(async, conn, wait: const Duration(milliseconds: 200)), + isNull); + }); + }); + + test('waits out an owed config OK, then grants', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + // A session recovery's setFloodScope written just before. + conn.setFloodScope(flood16); + ScopeLease? lease; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), + cancel: ScopeCancelToken()) + .then((l) => lease = l); + async.elapse(const Duration(milliseconds: 500)); + expect(lease, isNull); + expect(conn.isScopeLeaseActive, isFalse); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(milliseconds: 100)); + expect(lease, isNotNull); + expect(lease!.active, isTrue); + }); + }); + + test('refused while the admin slot is owned', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.login(key, 'pw').then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.hasPendingAdminCommand, isTrue); + expect(grant(async, conn, wait: const Duration(milliseconds: 200)), + isNull); + async.elapse(const Duration(seconds: 30)); + }); + }); + + test('a poll in flight is drained first', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.getNoiseFloor().then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + ScopeLease? lease; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), + cancel: ScopeCancelToken()) + .then((l) => lease = l); + async.elapse(const Duration(milliseconds: 300)); + expect(lease, isNull); + radio.emit([ + ResponseCodes.stats, + StatsTypes.radio, + 0x90, + 0xFF, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + async.elapse(const Duration(milliseconds: 100)); + expect(lease, isNotNull); + }); + }); + }); + + group('while held', () { + test('a config write waits at the gate and goes out after release', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + conn.setFloodScope(flood16); + async.elapse(const Duration(seconds: 1)); + expect(radio.writes, isEmpty); + expect(conn.repliesOwedCount, 0, + reason: 'no config write is on the wire while the lease holds'); + lease.release(); + async.flushMicrotasks(); + expect(radio.commands, [CommandCodes.setFloodScope]); + }); + }); + + test('pollers skip while the lease is held and run during the answer wait', + () { + onScopeClock(PollingScopeRadio.new, (async, radio, conn) { + conn.connect((_) async => null); + async.elapse(const Duration(seconds: 5)); + final before = radio.count(CommandCodes.getStats); + final lease = grant(async, conn)!; + final outcome = ask(async, lease); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.elapse(const Duration(seconds: 1)); + expect(lease.active, isTrue); + expect(radio.count(CommandCodes.getStats), before, + reason: 'the 5 s poll tick fell inside the lease'); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isTrue); + async.elapse(const Duration(seconds: 5)); + expect(radio.count(CommandCodes.getStats), before + 1); + expect(conn.isScopeListenActive, isTrue); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome(), isA()); + }); + }); + }); + + group('lease deadline', () { + /// Starts an ask with a TX queued behind the lease; returns the outcome + /// getter, the lease and when it was granted. + ({ + ScopeRequestOutcome? Function() outcome, + ScopeLease lease, + DateTime granted + }) start(FakeAsync async, ScopeRadio radio, MeshCoreConnection conn) { + final lease = grant(async, conn)!; + final granted = clock.now(); + final outcome = ask(async, lease); + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) {}); + async.flushMicrotasks(); + return (outcome: outcome, lease: lease, granted: granted); + } + + void expectReleasedAtFourSeconds(FakeAsync async, ScopeRadio radio, + MeshCoreConnection conn, ScopeLease lease, DateTime granted) { + final left = + granted.add(const Duration(seconds: 4)).difference(clock.now()); + async.elapse(left - const Duration(milliseconds: 1)); + expect(lease.active, isTrue); + expect(radio.commands.contains(CommandCodes.sendChannelTxtMsg), isFalse); + async.elapse(const Duration(milliseconds: 1)); + expect(lease.active, isFalse); + expect(radio.commands.last, CommandCodes.sendChannelTxtMsg, + reason: 'the queued TX goes out once the lease releases'); + } + + test('a missing borrow OK ends the lease at 4 s', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final s = start(async, radio, conn); + final payload = scopeContactPayload(pubkey: key); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.addUpdateContact); + expectReleasedAtFourSeconds(async, radio, conn, s.lease, s.granted); + expect((s.outcome()! as ScopeLocalFailure).why, 'hold_cap'); + expect(s.outcome()!.restoreOwed, isTrue); + expect(s.lease.unrestored.single.publicKey, key); + }); + }); + + test('a missing SENT ends the lease at 4 s', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final s = start(async, radio, conn); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.sendAnonReq); + expectReleasedAtFourSeconds(async, radio, conn, s.lease, s.granted); + expect((s.outcome()! as ScopeLocalFailure).why, 'hold_cap'); + expect(s.lease.unrestored, hasLength(1)); + expect(conn.hasPendingAdminCommand, isFalse); + }); + }); + + test('a missing restore OK ends the lease at 4 s and still listens', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final s = start(async, radio, conn); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.addUpdateContact); + expectReleasedAtFourSeconds(async, radio, conn, s.lease, s.granted); + expect(conn.isScopeListenActive, isTrue); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(s.outcome(), isA()); + expect(s.outcome()!.restoreOwed, isTrue); + expect(s.lease.unrestored, hasLength(1)); + }); + }); + + test('a stalled write ends the lease at 4 s without awaiting it', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + radio.stallCommands.add(CommandCodes.addUpdateContact); + final s = start(async, radio, conn); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + expectReleasedAtFourSeconds(async, radio, conn, s.lease, s.granted); + expect((s.outcome()! as ScopeLocalFailure).why, 'hold_cap'); + expect(s.lease.unrestored, hasLength(1)); + expect(conn.hasScopeReplyDebt, isTrue, + reason: 'the stalled write stays owed'); + }); + }); + }); + + group('background traffic', () { + test('a TX written during the lease goes out right after release', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) {}); + async.elapse(const Duration(milliseconds: 500)); + expect(radio.writes, isEmpty); + lease.release(); + async.flushMicrotasks(); + expect(radio.commands, [CommandCodes.sendChannelTxtMsg]); + }); + }); + + test( + 'TX and discovery go out during the answer wait; their OKs are not the answer', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final outcome = ask(async, grant(async, conn)!); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + var txDone = false; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) => txDone = true); + conn.sendDiscoveryRequest(); + async.flushMicrotasks(); + expect(radio.commands.sublist(2), + [CommandCodes.sendChannelTxtMsg, CommandCodes.sendControlData]); + radio.emit([ResponseCodes.ok]); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(txDone, isTrue); + expect(outcome(), isNull); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome(), isA()); + }); + }); + + test( + 'login and binary requests are refused while the listen holds the slot', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ask(async, grant(async, conn)!); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.hasPendingAdminCommand, isTrue); + Object? loginError; + Object? binaryError; + conn.login(key, 'pw').then((_) {}, onError: (Object e) { + loginError = e; + }); + conn.sendBinaryRequest(key, bytes([5, 0, 0])).then((_) {}, + onError: (Object e) { + binaryError = e; + }); + async.flushMicrotasks(); + expect(loginError, isA()); + expect(binaryError, isA()); + async.elapse(const Duration(seconds: 8)); + }); + }); + + void expectWait(Duration? answerWait, int est, Duration expected, + {Duration? notAfterIn}) { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + Duration? reported; + ScopeRequestOutcome? outcome; + grant(async, conn)! + .requestScopes(key, request, + answerWait: answerWait, + notAfter: + clock.now().add(notAfterIn ?? const Duration(seconds: 60)), + onSent: (w) => reported = w) + .then((o) => outcome = o); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame(est: est)); + async.flushMicrotasks(); + if (notAfterIn == null) expect(reported, expected); + async.elapse(expected - const Duration(milliseconds: 1)); + expect(outcome, isNull); + async.elapse(const Duration(milliseconds: 1)); + expect(outcome, isA()); + }); + } + + test('the answer wait is the given answerWait', () { + expectWait(const Duration(seconds: 3), 1500, const Duration(seconds: 3)); + }); + + test('without answerWait it is est_timeout plus 1 s', () { + expectWait(null, 1500, const Duration(milliseconds: 2500)); + }); + + test('the answer wait never exceeds 7 s', () { + expectWait(const Duration(seconds: 10), 1500, const Duration(seconds: 7)); + expectWait(null, 9000, const Duration(seconds: 7)); + }); + + test('the answer wait is cut at notAfter', () { + expectWait(const Duration(seconds: 7), 1500, const Duration(seconds: 1), + notAfterIn: const Duration(seconds: 1)); + }); + }); + + group('late replies', () { + test( + 'a borrow OK after the deadline is retired before the restore is written', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final first = grant(async, conn)!; + final payload = scopeContactPayload(pubkey: key); + final outcome = ask(async, first); + radio.emit(contactFrame(payload)); + async.elapse(const Duration(seconds: 4)); + expect(outcome(), isA()); + final owed = first.unrestored.single; + + ScopeLease? second; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), + cancel: ScopeCancelToken()) + .then((l) => second = l); + async.elapse(const Duration(milliseconds: 500)); + expect(second, isNull, reason: 'the borrow OK is still owed'); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(milliseconds: 100)); + expect(second, isNotNull); + final writesBefore = radio.writes.length; + bool? restored; + second!.restore(owed).then((r) => restored = r); + async.flushMicrotasks(); + expect(radio.writes.length, writesBefore + 1); + expect(radio.writes.last, [CommandCodes.addUpdateContact, ...payload]); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(restored, isTrue); + expect(second!.unrestored, isEmpty); + }); + }); + + test('after a SENT timeout a late ERR is retired before the restore', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final first = grant(async, conn)!; + ask(async, first); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(seconds: 4)); + expect(first.active, isFalse); + expect(conn.hasScopeReplyDebt, isTrue); + + ScopeLease? second; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 3), + cancel: ScopeCancelToken()) + .then((l) => second = l); + async.elapse(const Duration(milliseconds: 500)); + expect(second, isNull); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.elapse(const Duration(milliseconds: 100)); + expect(second, isNotNull); + second!.restore(first.unrestored.single); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.addUpdateContact); + }); + }); + }); + + group('reply expiry', () { + /// A first request whose lookup is never answered: the lease ends at + /// 4 s and the lookup's owed reply expires unanswered at 10 s. + void expireAnUnansweredLookup( + FakeAsync async, ScopeRadio radio, MeshCoreConnection conn) { + final first = grant(async, conn)!; + ask(async, first); + expect(radio.commands.last, CommandCodes.getContactByKey); + async.elapse(const Duration(seconds: 4)); + expect(first.active, isFalse); + expect(conn.hasScopeReplyDebt, isTrue); + async.elapse(const Duration(seconds: 7)); + expect(conn.hasScopeReplyDebt, isFalse, + reason: 'the lookup reply expired unanswered'); + } + + int anonRequests(ScopeRadio radio) => + radio.commands.where((c) => c == CommandCodes.sendAnonReq).length; + + test( + 'an old lookup ERR_NOT_FOUND after its debt expired never sends to a ' + 'saved flood-route contact', () { + final lines = captureScopeLog(); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expireAnUnansweredLookup(async, radio, conn); + expect(conn.isScopeDiscoverySuspended, isTrue); + + final second = grant(async, conn); + if (second != null) { + ask(async, second); + // The old lookup's late ERR_NOT_FOUND, then the new lookup's real + // CONTACT (a saved contact with no route), then its SENT. + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(contactFrame(scopeContactPayload( + pubkey: key, outPathLen: 0xFF, outPath: const []))); + radio.emit(sentFrame(flood: true)); + async.elapse(const Duration(seconds: 5)); + } + expect(anonRequests(radio), 0, + reason: 'command 57 must never be written'); + expect(second, isNull); + async.elapse(const Duration(minutes: 2)); + expect(grant(async, conn), isNull, + reason: 'suspended for the rest of the connection'); + }); + expect( + lines + .where((l) => + l.contains('[SCOPES]') && l.contains('out of step')) + .length, + 1); + // A new connection object starts in step. + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(grant(async, conn), isNotNull); + }); + }); + + test( + 'a stale zero-hop CONTACT after the debt expired is never taken as ' + 'the new lookup answer', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expireAnUnansweredLookup(async, radio, conn); + + final second = grant(async, conn); + if (second != null) { + ask(async, second); + // The old lookup's CONTACT (zero hop at the time), though the + // radio's route is now 0xFF: the lease would skip the borrow. + radio.emit(contactFrame( + scopeContactPayload(pubkey: key, outPathLen: 0, outPath: const []))); + async.flushMicrotasks(); + radio.emit(contactFrame(scopeContactPayload( + pubkey: key, outPathLen: 0xFF, outPath: const []))); + radio.emit(sentFrame(flood: true)); + async.elapse(const Duration(seconds: 5)); + } + expect(anonRequests(radio), 0, + reason: 'command 57 must never be written'); + expect(second, isNull); + }); + }); + + test('a lease waiting out the debt is refused once it expires', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + async.flushMicrotasks(); + ScopeLease? lease; + var done = false; + conn + .acquireScopeLease( + admissionWait: const Duration(seconds: 15), + cancel: ScopeCancelToken()) + .then((l) { + lease = l; + done = true; + }); + async.elapse(const Duration(seconds: 11)); + expect(done, isTrue); + expect(lease, isNull); + }); + }); + + test('a debt answered in time leaves scope work running', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.setFloodScope(flood16); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 9)); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(seconds: 30)); + expect(conn.isScopeDiscoverySuspended, isFalse); + expect(grant(async, conn), isNotNull); + }); + }); + }); + + group('cancellation', () { + test('a cancel before the borrow write puts no further byte on the air', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final cancel = ScopeCancelToken(); + final outcome = ask(async, grant(async, conn, cancel: cancel)!); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + cancel.cancel(); + async.elapse(const Duration(seconds: 10)); + expect(radio.commands, [CommandCodes.getContactByKey]); + expect(outcome(), isA()); + }); + }); + + test('a cancel during a stalled borrow writes nothing more', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + radio.stallCommands.add(CommandCodes.addUpdateContact); + final cancel = ScopeCancelToken(); + final lease = grant(async, conn, cancel: cancel)!; + final outcome = ask(async, lease); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + cancel.cancel(); + async.elapse(const Duration(seconds: 10)); + expect(radio.commands, + [CommandCodes.getContactByKey, CommandCodes.addUpdateContact]); + expect(outcome(), isA()); + expect(lease.active, isFalse); + expect(lease.unrestored, hasLength(1)); + }); + }); + + test( + 'a cancel after the borrow leaves the record; the next lease restores it first', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final payload = scopeContactPayload(pubkey: key); + final cancel = ScopeCancelToken(); + final first = grant(async, conn, cancel: cancel)!; + final outcome = ask(async, first); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.sendAnonReq); + cancel.cancel(); + async.flushMicrotasks(); + expect(outcome(), isA()); + expect(outcome()!.restoreOwed, isTrue); + final owed = first.unrestored.single; + expect(owed.toFrame(CommandCodes.addUpdateContact), + [CommandCodes.addUpdateContact, ...payload]); + + // The late SENT is retired, then the next lease restores first. + radio.emit(sentFrame()); + async.flushMicrotasks(); + final second = grant(async, conn)!; + second.restore(owed); + async.flushMicrotasks(); + expect(radio.writes.last, [CommandCodes.addUpdateContact, ...payload]); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(second.unrestored, isEmpty); + expect(record(payload).publicKey, key); + }); + }); + + test('a disconnect aborts the request and drops everything', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + final outcome = ask(async, lease); + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + conn.disconnect(); + async.flushMicrotasks(); + expect(outcome(), isA()); + expect(lease.active, isFalse); + expect(lease.unrestored, isEmpty); + expect(conn.isScopeLeaseActive, isFalse); + expect(conn.hasScopeReplyDebt, isFalse); + expect(conn.hasPendingAdminCommand, isFalse); + }); + }); + + test('a disconnect during the answer wait is ScopeAborted', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final outcome = ask(async, grant(async, conn)!); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isTrue); + conn.disconnect(); + async.flushMicrotasks(); + expect(outcome(), isA()); + expect(conn.isScopeListenActive, isFalse); + }); + }); + }); + + group('contact table full', () { + test('a new connection object starts with the flag clear', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ask(async, grant(async, conn)!); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(conn.scopeCannotAskNonContacts, isTrue); + }); + // A fresh connection object (a reconnect) starts clean, even though + // the previous connection's flag was set. + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(conn.scopeCannotAskNonContacts, isFalse); + }); + }); + }); + + group('release', () { + test( + 'a reply owed at release is retired on arrival and dispatched as before', + () { + final lines = captureScopeLog(); + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + lease.restore(record(scopeContactPayload(pubkey: key))); + async.elapse(const Duration(seconds: 4)); + expect(lease.active, isFalse); + expect(conn.hasScopeReplyDebt, isTrue); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(conn.hasScopeReplyDebt, isFalse); + }); + expect( + lines.any((l) => l.contains('[CONN] Received OK response')), isTrue); + }); + + test('queued writes go out in their original order', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + conn.setFloodScope(flood16); + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) {}); + conn.sendDiscoveryRequest(); + conn.getBatteryVoltage(); + async.flushMicrotasks(); + expect(radio.writes, isEmpty); + lease.release(); + async.flushMicrotasks(); + expect(radio.commands, [ + CommandCodes.setFloodScope, + CommandCodes.sendChannelTxtMsg, + CommandCodes.sendControlData, + CommandCodes.getBatteryVoltage, + ]); + async.elapse(const Duration(seconds: 11)); + }); + }); + }); +} diff --git a/test/services/meshcore/scope_radio_busy_test.dart b/test/services/meshcore/scope_radio_busy_test.dart new file mode 100644 index 00000000..23c92035 --- /dev/null +++ b/test/services/meshcore/scope_radio_busy_test.dart @@ -0,0 +1,105 @@ +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/buffer_utils.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; + +import 'scope_test_support.dart'; + +/// Manage waits while scope discovery owns the radio: a lease, or a reply +/// still owed for a command that lease wrote. The flag has to reach the +/// provider when it flips back, or the button stays disabled until some +/// unrelated control change, and ordinary traffic (the pollers, a flood +/// scope write) must neither set it nor fire the notification. +void main() { + final key = scopeKey(0xAB); + final flood16 = Uint8List(16); + + ContactRecord record(Uint8List payload) => + ContactRecord.parse(BufferReader(payload)); + + ({List seen}) watch(MeshCoreConnection conn) { + final seen = []; + conn.onScopeRadioBusyChanged = () => seen.add(conn.isScopeRadioBusy); + return (seen: seen); + } + + /// A lease whose restore write is still owed at the 4 s release. + ScopeLease releasedWithDebt(FakeAsync async, ScopeRadio radio, + MeshCoreConnection conn) { + final lease = grant(async, conn)!; + lease.restore(record(scopeContactPayload(pubkey: key))); + async.elapse(const Duration(seconds: 4)); + expect(lease.active, isFalse); + return lease; + } + + test('reply debt from ordinary traffic is not scope debt, and never ' + 'notifies', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final w = watch(conn); + for (var i = 0; i < 20; i++) { + conn.setFloodScope(flood16); + conn.getBatteryVoltage(); + } + async.flushMicrotasks(); + expect(conn.repliesOwedCount, 40); + expect(conn.hasScopeReplyDebt, isFalse); + expect(conn.isScopeRadioBusy, isFalse); + async.elapse(const Duration(seconds: 11)); + expect(w.seen, isEmpty); + }); + }); + + test('busy while the lease is held, still busy on release with a reply ' + 'owed, and notified once when that reply lands', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final w = watch(conn); + releasedWithDebt(async, radio, conn); + expect(conn.hasScopeReplyDebt, isTrue); + expect(conn.isScopeRadioBusy, isTrue); + expect(w.seen, [true], reason: 'one change: idle to busy at the grant'); + + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(conn.isScopeRadioBusy, isFalse); + expect(w.seen, [true, false]); + }); + }); + + test('scope debt expiring notifies once', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final w = watch(conn); + releasedWithDebt(async, radio, conn); + expect(w.seen, [true]); + async.elapse(const Duration(seconds: 7)); + expect(conn.hasScopeReplyDebt, isFalse); + expect(w.seen, [true, false]); + }); + }); + + test('a lease released with nothing owed notifies both flips', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final w = watch(conn); + final lease = grant(async, conn)!; + lease.release(); + async.flushMicrotasks(); + expect(conn.isScopeRadioBusy, isFalse); + expect(w.seen, [true, false]); + }); + }); + + test('disconnect clears scope debt and notifies', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final w = watch(conn); + releasedWithDebt(async, radio, conn); + conn.disconnect(); + async.flushMicrotasks(); + expect(conn.isScopeRadioBusy, isFalse); + expect(w.seen.last, isFalse); + }); + }); +} diff --git a/test/services/meshcore/scope_request_frames_test.dart b/test/services/meshcore/scope_request_frames_test.dart new file mode 100644 index 00000000..ea8bae23 --- /dev/null +++ b/test/services/meshcore/scope_request_frames_test.dart @@ -0,0 +1,456 @@ +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; + +import 'scope_test_support.dart'; + +/// Byte vectors for the scope request, from examples/companion_radio/MyMesh.cpp +/// (CMD_GET_CONTACT_BY_KEY, CMD_ADD_UPDATE_CONTACT, CMD_SEND_ANON_REQ and +/// writeContactRespFrame). +void main() { + final key = scopeKey(0xAB); + final request = Uint8List.fromList([0x01, 0x00]); + + /// Starts a request on a fresh lease; [out] receives the outcome. + void ask(FakeAsync async, MeshCoreConnection conn, + void Function(ScopeRequestOutcome) out, + {Duration? answerWait = const Duration(seconds: 7), + DateTime? notAfter, + void Function(Duration)? onSent}) { + final lease = grant(async, conn)!; + lease + .requestScopes(key, request, + answerWait: answerWait, + notAfter: notAfter ?? clock.now().add(const Duration(seconds: 30)), + onSent: onSent) + .then(out); + async.flushMicrotasks(); + } + + test('lookup, borrow, send and restore go out byte for byte', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + // A name with invalid UTF-8 and junk after its NUL must survive. + final raw = rawNameBytes([0x48, 0xFF, 0xC3, 0x69], after: [0x5A, 0x5A]); + final payload = + scopeContactPayload(pubkey: key, rawName: raw, lastMod: 0x01020304); + ScopeRequestOutcome? outcome; + Duration? sentWait; + ask(async, conn, (o) => outcome = o, onSent: (w) => sentWait = w); + + expect(radio.writes.last, [CommandCodes.getContactByKey, ...key]); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + + // The borrow is the record as read with ONLY out_path_len changed. + final borrow = radio.writes.last; + expect(borrow[0], CommandCodes.addUpdateContact); + expect(borrow.length, 1 + ContactRecord.payloadLength); + final diffs = [ + for (var i = 0; i < payload.length; i++) + if (borrow[i + 1] != payload[i]) i + ]; + expect(diffs, [34], reason: 'only out_path_len (offset 34) may differ'); + expect(borrow[35], 0); + + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(radio.writes.last, [CommandCodes.sendAnonReq, ...key, 0x01, 0x00]); + + radio.emit(sentFrame(est: 1500)); + async.flushMicrotasks(); + expect(sentWait, const Duration(seconds: 7)); + // The restore is the lookup payload, byte for byte. + expect(radio.writes.last, [CommandCodes.addUpdateContact, ...payload]); + expect(conn.isScopeLeaseActive, isTrue, + reason: 'held until the restore OK'); + + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(conn.isScopeLeaseActive, isFalse); + expect(conn.isScopeListenActive, isTrue); + + radio.emit(answerPush(body: [1, 0, 0, 0, 0x41, 0x2C, 0x42])); + async.flushMicrotasks(); + expect(outcome, isA()); + final answered = outcome! as ScopeAnswered; + expect(answered.body, [1, 0, 0, 0, 0x41, 0x2C, 0x42]); + expect(answered.restoreOwed, isFalse); + expect(answered.borrowedFrom?.publicKey, key); + expect(conn.isScopeListenActive, isFalse); + expect(conn.hasPendingAdminCommand, isFalse); + }); + }); + + test('an answer that lands during a slow restore is kept', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final payload = scopeContactPayload(pubkey: key); + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o, + answerWait: const Duration(seconds: 1)); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + final sentAt = clock.now(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(radio.writes.last, [CommandCodes.addUpdateContact, ...payload]); + // The answer arrives 0.2 s after SENT, inside its 1 s wait ... + async.elapse(const Duration(milliseconds: 200)); + radio.emit(answerPush(body: [0, 0, 0, 0, 0x41])); + async.flushMicrotasks(); + // ... and the restore OK only at 2 s, after the answer wait ran out. + async.elapse(const Duration(milliseconds: 1800)); + expect(outcome, isNull); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(outcome, isA()); + final answered = outcome! as ScopeAnswered; + expect(answered.body, [0, 0, 0, 0, 0x41]); + expect( + answered.receivedAt, sentAt.add(const Duration(milliseconds: 200))); + expect(answered.restoreOwed, isFalse); + expect(conn.isScopeListenActive, isFalse); + }); + }); + + test('a contact the radio does not know (ERR 2) goes straight to the send', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(radio.commands, + [CommandCodes.getContactByKey, CommandCodes.sendAnonReq]); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.isScopeLeaseActive, isFalse, reason: 'nothing to restore'); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome, isA()); + expect(outcome!.borrowedFrom, isNull); + expect(outcome!.restoreOwed, isFalse); + }); + }); + + test('an already zero-hop contact is not borrowed', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit(contactFrame( + scopeContactPayload(pubkey: key, outPathLen: 0x80, outPath: []))); + async.flushMicrotasks(); + expect(radio.commands, + [CommandCodes.getContactByKey, CommandCodes.sendAnonReq]); + radio.emit(sentFrame()); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome, isA()); + expect(outcome!.borrowedFrom, isNull); + }); + }); + + test('a CONTACT for another key is reply_owed, not accepted', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit(contactFrame(scopeContactPayload(pubkey: scopeKey(0x11)))); + async.flushMicrotasks(); + expect(outcome, isA()); + expect((outcome! as ScopeLocalFailure).why, 'reply_owed'); + expect(radio.commands, [CommandCodes.getContactByKey]); + expect(conn.isScopeLeaseActive, isFalse); + }); + }); + + test('SENT and the answer in the same transport chunk still answer', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + final start = clock.now(); + radio.emit(sentFrame(tag: [7, 7, 7, 7])); + radio.emit(answerPush(tag: [7, 7, 7, 7], body: [0, 0, 0, 0])); + async.flushMicrotasks(); + expect(outcome, isA()); + expect((outcome! as ScopeAnswered).receivedAt, start); + }); + }); + + test('an answer for another tag is ignored and the wait ends as no answer', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame(tag: [1, 1, 1, 1])); + radio.emit(answerPush(tag: [2, 2, 2, 2])); + async.elapse(const Duration(milliseconds: 6999)); + expect(outcome, isNull); + async.elapse(const Duration(milliseconds: 1)); + expect(outcome, isA()); + // The tag is cleared: a late answer is ignored. + radio.emit(answerPush(tag: [1, 1, 1, 1])); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isFalse); + }); + }); + + test('a flooded send is ScopeFlooded at once', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + var sentCalled = false; + ask(async, conn, (o) => outcome = o, onSent: (_) => sentCalled = true); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame(flood: true)); + async.flushMicrotasks(); + expect(outcome, isA()); + expect(sentCalled, isFalse); + expect(conn.hasPendingAdminCommand, isFalse); + }); + }); + + test('a malformed SENT is malformed_sent and the borrow is restored', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final payload = scopeContactPayload(pubkey: key); + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.sent, 0, 1, 2]); + async.flushMicrotasks(); + expect(radio.writes.last, [CommandCodes.addUpdateContact, ...payload]); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(outcome, isA()); + expect((outcome! as ScopeLocalFailure).why, 'malformed_sent'); + expect(outcome!.restoreOwed, isFalse); + }); + }); + + test('a throwing write is write_failed', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final lease = grant(async, conn)!; + radio.failWrites = true; + ScopeRequestOutcome? outcome; + lease + .requestScopes(key, request, + answerWait: null, + notAfter: clock.now().add(const Duration(seconds: 30))) + .then((o) => outcome = o); + async.flushMicrotasks(); + expect(outcome, isA()); + expect((outcome! as ScopeLocalFailure).why, 'write_failed'); + expect(lease.active, isFalse); + }); + }); + + test('an ERR other than 2 is ScopeRadioError', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + // The ambiguous ERR 3 on a non-contact send is confirmed with one more + // lookup before the outcome lands; answer it not-found here so this + // generic test does not hang on an unanswered exchange. + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(outcome, isA()); + expect((outcome! as ScopeRadioError).code, ErrorCodes.tableFull); + }); + }); + + group('a full contact table', () { + test('a table-full send to a non-contact, confirmed still absent, sets ' + 'the connection flag and marks the outcome', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + expect(conn.scopeCannotAskNonContacts, isFalse); + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + // The confirming re-lookup: still not a contact, so the anon + // contact really could not be allocated. + expect(radio.commands.last, CommandCodes.getContactByKey); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(outcome, isA()); + final err = outcome! as ScopeRadioError; + expect(err.code, ErrorCodes.tableFull); + expect(err.nonContactTableFull, isTrue); + expect(conn.scopeCannotAskNonContacts, isTrue); + expect(radio.commands, [ + CommandCodes.getContactByKey, + CommandCodes.sendAnonReq, + CommandCodes.getContactByKey, + ]); + }); + }); + + test('a table-full send to a non-contact, but the re-lookup now finds ' + 'it, never sets the flag (the packet pool was full, not the table)', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.getContactByKey); + // The confirming re-lookup: the anon contact WAS allocated after + // all, so `addContact` succeeded and `sendAnonReq` itself failed + // for an unrelated (transient) reason. + radio.emit(contactFrame(scopeContactPayload(pubkey: key))); + async.flushMicrotasks(); + expect(outcome, isA()); + final err = outcome! as ScopeRadioError; + expect(err.code, ErrorCodes.tableFull); + expect(err.nonContactTableFull, isFalse); + expect(conn.scopeCannotAskNonContacts, isFalse); + }); + }); + + test('a table-full send to a SAVED contact never sets the flag', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + final payload = scopeContactPayload(pubkey: key); + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + // The ERR still owes the borrow's restore before the outcome lands. + expect(radio.commands.last, CommandCodes.addUpdateContact); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(outcome, isA()); + final err = outcome! as ScopeRadioError; + expect(err.code, ErrorCodes.tableFull); + expect(err.nonContactTableFull, isFalse); + expect(conn.scopeCannotAskNonContacts, isFalse); + }); + }); + + test( + 'once the flag is set, a fresh non-contact lookup ends the ask ' + 'without a send', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ask(async, conn, (_) {}); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(conn.scopeCannotAskNonContacts, isTrue); + + final before = radio.commands.length; + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(outcome, isA()); + expect(radio.commands.sublist(before), [CommandCodes.getContactByKey], + reason: 'the lookup happens, but nothing is sent'); + expect(conn.isScopeLeaseActive, isFalse); + }); + }); + + test('once the flag is set, a saved contact is still asked normally', + () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ask(async, conn, (_) {}); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.tableFull]); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(conn.scopeCannotAskNonContacts, isTrue); + + final payload = scopeContactPayload(pubkey: key); + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit(contactFrame(payload)); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.addUpdateContact, + reason: 'the borrow still happens for a saved contact'); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(radio.commands, contains(CommandCodes.sendAnonReq)); + // The restore (the original route written back) before the lease + // releases into the answer wait. + expect(radio.commands.last, CommandCodes.addUpdateContact); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome, isA()); + }); + }); + }); + + group('stray replies during the answer wait', () { + for (final stray in >>{ + 'a TX ERR': [ + [ResponseCodes.err, ErrorCodes.notFound] + ], + 'a discovery ERR': [ + [ResponseCodes.err, ErrorCodes.tableFull] + ], + 'a trace SENT': [ + sentFrame(tag: [5, 5, 5, 5]) + ], + 'a config OK and ERR': [ + [ResponseCodes.ok], + [ResponseCodes.err, ErrorCodes.illegalArg] + ], + 'poll replies (stats ERR, battery)': [ + [ResponseCodes.err, 1], + [ResponseCodes.batteryVoltage, 0xA0, 0x0F] + ], + }.entries) { + test('${stray.key} never fails the waiter', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + ScopeRequestOutcome? outcome; + ask(async, conn, (o) => outcome = o); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isTrue); + for (final frame in stray.value) { + radio.emit(frame); + } + async.elapse(const Duration(seconds: 1)); + expect(outcome, isNull); + expect(conn.isScopeListenActive, isTrue); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(outcome, isA()); + }); + }); + } + }); +} diff --git a/test/services/meshcore/scope_test_support.dart b/test/services/meshcore/scope_test_support.dart new file mode 100644 index 00000000..17081bed --- /dev/null +++ b/test/services/meshcore/scope_test_support.dart @@ -0,0 +1,176 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/foundation.dart' show debugPrint; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/buffer_utils.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; +import 'package:mesh_mapper/utils/debug_logger_io.dart'; + +import 'catalog_protocol_transport.dart'; +import 'fake_companion_transport.dart'; + +/// A fake radio whose writes can be made to stall (the transport never +/// returns), for the lease deadline and cancellation cases. +class ScopeRadio extends FakeCompanionTransport { + /// Commands whose write is recorded and then never returns. + final Set stallCommands = {}; + + /// Set true to record the frame (it reached the radio) and then throw, + /// the ambiguous-delivery case. + bool failAfterSend = false; + + @override + Future write(Uint8List data) async { + if (failWrites) throw StateError('fake transport link is down'); + writes.add(Uint8List.fromList(data)); + if (failAfterSend) throw StateError('fake transport lost the ack'); + if (data.isNotEmpty && stallCommands.contains(data.first)) { + await Completer().future; + } + } + + /// Command bytes of every write, oldest first. + List get commands => [for (final w in writes) w.isEmpty ? -1 : w[0]]; +} + +/// The real connect handshake plus live pollers; scope, TX and config +/// commands are only recorded, so the test answers them by hand. +class PollingScopeRadio extends CatalogProtocolTransport { + static const Set _manual = { + CommandCodes.getContactByKey, + CommandCodes.addUpdateContact, + CommandCodes.sendAnonReq, + CommandCodes.sendChannelTxtMsg, + CommandCodes.sendControlData, + CommandCodes.setFloodScope, + CommandCodes.sendLogin, + CommandCodes.sendBinaryReq, + }; + + @override + Future write(Uint8List data) async { + if (data.isNotEmpty && _manual.contains(data.first)) { + writes.add(Uint8List.fromList(data)); + return; + } + await super.write(data); + } + + int count(int command) => writes.where((w) => w.first == command).length; +} + +Uint8List scopeKey(int fill) => Uint8List.fromList(List.filled(32, fill)); + +/// The 32 raw name bytes: [name] then a NUL then [after] (junk the firmware +/// may leave past the terminator). +Uint8List rawNameBytes(List name, {List after = const []}) { + final raw = Uint8List(32); + raw.setRange(0, name.length, name); + raw.setRange(name.length + 1, name.length + 1 + after.length, after); + return raw; +} + +/// A RESP_CODE_CONTACT payload (147 bytes after the code byte). +Uint8List scopeContactPayload({ + required Uint8List pubkey, + int type = 2, + int flags = 0, + int outPathLen = 0x02, + List outPath = const [0x4E, 0x7A], + Uint8List? rawName, + int lastAdvert = 1700000000, + int latMicro = 45269740, + int lonMicro = -75777460, + int lastMod = 1700000100, +}) { + final w = BufferWriter(); + w.writeBytes(pubkey); + w.writeByte(type); + w.writeByte(flags); + w.writeByte(outPathLen); + final path = Uint8List(64)..setRange(0, outPath.length, outPath); + // Leftover bytes past the live route, as the firmware keeps them. + path[60] = 0xEE; + w.writeBytes(path); + w.writeBytes(rawName ?? rawNameBytes('Hilltop'.codeUnits)); + w.writeUInt32LE(lastAdvert); + w.writeUInt32LE(latMicro.toUnsigned(32)); + w.writeUInt32LE(lonMicro.toUnsigned(32)); + w.writeUInt32LE(lastMod); + return w.toBytes(); +} + +List contactFrame(Uint8List payload) => + [ResponseCodes.contact, ...payload]; + +/// RESP_CODE_SENT: [6][flood][tag:4][est_timeout_ms:u32 LE]. +List sentFrame( + {bool flood = false, + List tag = const [1, 2, 3, 4], + int est = 2000}) => + [ + ResponseCodes.sent, + flood ? 1 : 0, + ...tag, + est & 0xFF, + (est >> 8) & 0xFF, + (est >> 16) & 0xFF, + (est >> 24) & 0xFF, + ]; + +/// PUSH_CODE_BINARY_RESPONSE: [0x8C][reserved][tag:4][body]. +List answerPush( + {List tag = const [1, 2, 3, 4], + List body = const [9, 9, 9, 9, 0x41]}) => + [PushCodes.binaryResponse, 0, ...tag, ...body]; + +/// Runs [body] on a controlled clock with a connection built inside it. +void onScopeClock(T Function() makeRadio, + void Function(FakeAsync async, T radio, MeshCoreConnection conn) body) { + fakeAsync((async) { + final radio = makeRadio(); + final conn = MeshCoreConnection(transport: radio); + body(async, radio, conn); + conn.dispose(); + radio.dispose(); + async.flushMicrotasks(); + }); +} + +/// Acquires a lease on a quiet radio and returns it (null when refused). +ScopeLease? grant(FakeAsync async, MeshCoreConnection conn, + {ScopeCancelToken? cancel, Duration wait = const Duration(seconds: 3)}) { + ScopeLease? lease; + var done = false; + conn + .acquireScopeLease( + admissionWait: wait, cancel: cancel ?? ScopeCancelToken()) + .then((l) { + lease = l; + done = true; + }); + async.flushMicrotasks(); + if (!done) async.elapse(wait + const Duration(milliseconds: 50)); + expect(done, isTrue, reason: 'admission should have settled'); + return lease; +} + +/// Captures every debug log line for the rest of the test. +List captureScopeLog() { + final lines = []; + final originalDebugPrint = debugPrint; + final originalEnabled = DebugLogger.isEnabled; + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) lines.add(message); + }; + DebugLogger.setEnabled(true); + addTearDown(() { + debugPrint = originalDebugPrint; + DebugLogger.setEnabled(originalEnabled); + }); + return lines; +} diff --git a/test/services/meshcore/sign_flow_test.dart b/test/services/meshcore/sign_flow_test.dart index 0e1cc79c..2b442e2c 100644 --- a/test/services/meshcore/sign_flow_test.dart +++ b/test/services/meshcore/sign_flow_test.dart @@ -1,13 +1,17 @@ import 'dart:async'; import 'dart:typed_data'; +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart' show debugPrint; import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/link_decision.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; import 'package:mesh_mapper/utils/debug_logger_io.dart'; import 'fake_companion_transport.dart'; +import 'scope_test_support.dart'; /// CMD_SIGN framing contract (mirrors the portal's meshcore.js, which is what /// today's 1,475 live companion links were made with): @@ -436,4 +440,64 @@ void main() { expect(transport.commandAt(0), CommandCodes.getBatteryVoltage); }); }); + + group('sign and the scope lease', () { + Uint8List nonce() => Uint8List.fromList(List.generate(32, (i) => i)); + + /// Puts [conn] in the answer wait of a scope request. + void listen(FakeAsync async, ScopeRadio radio, MeshCoreConnection conn) { + final lease = grant(async, conn)!; + lease.requestScopes(scopeKey(0xAB), Uint8List.fromList([1, 0]), + answerWait: const Duration(seconds: 7), + notAfter: clock.now().add(const Duration(seconds: 30))); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + } + + test('a sign started during the lease waits for the listen to end', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + listen(async, radio, conn); + expect(conn.isScopeLeaseActive, isTrue); + conn.sign(nonce()).then((_) {}, onError: (_) {}); + async.flushMicrotasks(); + radio.emit(sentFrame()); + async.elapse(const Duration(seconds: 1)); + expect(conn.isScopeListenActive, isTrue); + expect(radio.commands.contains(CommandCodes.signStart), isFalse, + reason: 'no sign while the scope listen holds the slot'); + radio.emit(answerPush()); + async.flushMicrotasks(); + expect(radio.commands.last, CommandCodes.signStart); + async.elapse(const Duration(seconds: 6)); + }); + }); + + test('a sign waiting past its limit fails busy', () { + onScopeClock(ScopeRadio.new, (async, radio, conn) { + conn.signScopeWait = const Duration(seconds: 2); + listen(async, radio, conn); + radio.emit(sentFrame()); + async.flushMicrotasks(); + Object? error; + conn.sign(nonce()).then((_) {}, onError: (Object e) { + error = e; + }); + async.elapse(const Duration(milliseconds: 1999)); + expect(error, isNull); + async.elapse(const Duration(milliseconds: 1)); + expect(error, + isA().having((e) => e.code, 'code', 'busy')); + expect(radio.commands.contains(CommandCodes.signStart), isFalse); + async.elapse(const Duration(seconds: 8)); + }); + }); + + test('the link flow backs off on busy and never takes a strike', () { + expect(signFailureAction('busy'), SignFailureAction.backoff); + expect(signFailureAction('unsupported'), SignFailureAction.strike); + expect(signFailureAction('err'), SignFailureAction.silent); + expect(signFailureAction('aborted'), SignFailureAction.silent); + }); + }); } diff --git a/test/services/meshcore/tx_reply_test.dart b/test/services/meshcore/tx_reply_test.dart new file mode 100644 index 00000000..b1d8a01f --- /dev/null +++ b/test/services/meshcore/tx_reply_test.dart @@ -0,0 +1,276 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/foundation.dart' show debugPrint; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/utils/debug_logger_io.dart'; + +import 'catalog_protocol_transport.dart'; +import 'fake_companion_transport.dart'; + +/// Runs the real connect handshake, then answers a channel message the way +/// the firmware does: a bare OK, here 5 ms after the write. +class _OkAfterTxTransport extends CatalogProtocolTransport { + @override + Future write(Uint8List data) async { + if (data.isNotEmpty && data.first == CommandCodes.sendChannelTxtMsg) { + writes.add(Uint8List.fromList(data)); + Timer(const Duration(milliseconds: 5), () => emit([ResponseCodes.ok])); + return; + } + await super.write(data); + } +} + +/// The companion firmware answers CMD_SEND_CHANNEL_TXT_MSG and +/// CMD_SEND_CONTROL_DATA (discovery) with a bare OK or ERR, never with +/// RESP_CODE_SENT (examples/companion_radio/MyMesh.cpp). A TX send therefore +/// has to wait for its own OK, and both sends have to claim their reply so it +/// cannot complete some other command's OK waiter. +void main() { + late FakeCompanionTransport transport; + late MeshCoreConnection connection; + + setUp(() { + transport = FakeCompanionTransport(); + connection = MeshCoreConnection(transport: transport); + }); + + tearDown(() { + connection.dispose(); + transport.dispose(); + }); + + Uint8List key(int fill) => Uint8List.fromList(List.filled(32, fill)); + + ContactRecord contact() => ContactRecord.newRepeater( + publicKey: key(9), name: 'R', lat: 1, lon: 2, nowSecs: 5); + + Future sendTx() => connection.sendChannelTextMessage(0, 1, 0, 'MM:x'); + + /// Resolves true once [future] completes, false while it is still pending. + Future isDone(Future future) async { + var done = false; + unawaited(future.then((_) => done = true, onError: (_) => done = true)); + await transport.settle(); + await transport.settle(); + return done; + } + + List captureLog() { + final lines = []; + final originalDebugPrint = debugPrint; + final originalEnabled = DebugLogger.isEnabled; + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) lines.add(message); + }; + DebugLogger.setEnabled(true); + addTearDown(() { + debugPrint = originalDebugPrint; + DebugLogger.setEnabled(originalEnabled); + }); + return lines; + } + + /// Runs [body] on a controlled clock with a connection built inside it, so + /// every timer (the reply budget included) is fake and nothing is timed on + /// the wall clock. + void onFakeClock( + FakeCompanionTransport Function() makeTransport, + void Function(FakeAsync async, FakeCompanionTransport transport, + MeshCoreConnection connection) + body) { + fakeAsync((async) { + final fakeTransport = makeTransport(); + final fakeConnection = MeshCoreConnection(transport: fakeTransport); + body(async, fakeTransport, fakeConnection); + fakeConnection.dispose(); + fakeTransport.dispose(); + async.flushMicrotasks(); + }); + } + + test('sendPing on a connected radio returns 5 ms after its OK is sent', + () { + final lines = captureLog(); + onFakeClock(_OkAfterTxTransport.new, (async, radio, conn) { + var connected = false; + conn.connect((_) async => null).then((_) => connected = true); + // connect() lets the link settle for 500 ms before its first query. + async.elapse(const Duration(seconds: 1)); + expect(connected, isTrue); + expect(conn.wardrivingChannel?.name, '#wardriving'); + + var done = false; + conn.sendPing('MM:YVNPAr5OIw').then((_) => done = true); + async.flushMicrotasks(); + expect(radio.writes.last.first, CommandCodes.sendChannelTxtMsg); + + // The radio replies OK 5 ms after the write. + async.elapse(const Duration(milliseconds: 4)); + expect(done, isFalse); + async.elapse(const Duration(milliseconds: 6)); + expect(done, isTrue, reason: 'sendPing must finish within 10 ms'); + }); + expect(lines.any((l) => l.contains('[CONN] OK claimed by TX send')), + isTrue); + }); + + test('a TX returns as soon as its own OK arrives, not after 3 s', () { + onFakeClock(FakeCompanionTransport.new, (async, radio, conn) { + var done = false; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) => done = true); + async.flushMicrotasks(); + expect(radio.commandAt(0), CommandCodes.sendChannelTxtMsg); + Timer(const Duration(milliseconds: 5), + () => radio.emit([ResponseCodes.ok])); + async.elapse(const Duration(milliseconds: 10)); + expect(done, isTrue); + }); + }); + + test('a TX ERR returns at once and is logged as a warning', () { + final lines = captureLog(); + onFakeClock(FakeCompanionTransport.new, (async, radio, conn) { + var done = false; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) => done = true); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + expect(done, isTrue); + }); + expect( + lines.any((l) => + l.contains('[CONN]') && + l.contains('TX send rejected by radio') && + l.contains('error code ${ErrorCodes.notFound}')), + isTrue); + }); + + test('a TX with no reply returns after 3 s and releases its claim', () { + onFakeClock(FakeCompanionTransport.new, (async, radio, conn) { + var done = false; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) => done = true); + async.elapse(const Duration(milliseconds: 2999)); + expect(done, isFalse); + async.elapse(const Duration(milliseconds: 1)); + expect(done, isTrue); + + // The expired claim must not swallow the next command's OK. + var added = false; + conn.addContact(contact()).then((_) => added = true); + async.flushMicrotasks(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(added, isTrue); + }); + }); + + test('a TX OK goes to the TX and the admin OK to the admin', () async { + final tx = sendTx(); + await transport.settle(); + final add = connection.addContact(contact()); + await transport.settle(); + expect(transport.commandAt(1), CommandCodes.addUpdateContact); + + transport.emit([ResponseCodes.ok]); + expect(await isDone(tx), isTrue); + expect(await isDone(add), isFalse); + + transport.emit([ResponseCodes.ok]); + expect(await isDone(add), isTrue); + }); + + test('a discovery OK never completes an admin waiter', () async { + await connection.sendDiscoveryRequest(); + final add = connection.addContact(contact()); + await transport.settle(); + + transport.emit([ResponseCodes.ok]); + expect(await isDone(add), isFalse); + + transport.emit([ResponseCodes.ok]); + expect(await isDone(add), isTrue); + }); + + test('a discovery ERR never fails an admin waiter', () async { + await connection.sendDiscoveryRequest(); + final add = connection.addContact(contact()); + await transport.settle(); + + transport.emit([ResponseCodes.err, ErrorCodes.tableFull]); + expect(await isDone(add), isFalse); + + transport.emit([ResponseCodes.ok]); + await add; + }); + + test('a discovery OK never completes a sign chunk', () async { + await connection.sendDiscoveryRequest(); + final sign = connection + .sign(Uint8List.fromList(List.generate(32, (i) => i + 1))); + await transport.settle(); + + // The radio answers in command order: the discovery OK first. + transport.emit([ResponseCodes.ok]); + transport.emit([ResponseCodes.signStart, 0, 128, 0, 0, 0]); + await transport.settle(); + expect(transport.commandAt(2), CommandCodes.signData); + + // The chunk is still waiting for its own OK. + await transport.settle(); + expect(transport.writes.length, 3); + + transport.emit([ResponseCodes.ok]); + await transport.settle(); + expect(transport.commandAt(3), CommandCodes.signFinish); + transport.emit([ResponseCodes.signature, ...List.filled(64, 0xAB)]); + expect((await sign).length, 64); + }); + + test('replies are claimed oldest first across TX and discovery', () async { + final lines = captureLog(); + await connection.sendDiscoveryRequest(); + final tx = sendTx(); + await transport.settle(); + + transport.emit([ResponseCodes.ok]); + expect(await isDone(tx), isFalse); + + transport.emit([ResponseCodes.err, ErrorCodes.notFound]); + expect(await isDone(tx), isTrue); + expect(lines.any((l) => l.contains('TX send rejected by radio')), isTrue); + }); + + test('an unanswered discovery claim expires and stops claiming', () async { + connection.ownReplyTimeout = const Duration(milliseconds: 20); + await connection.sendDiscoveryRequest(); + await Future.delayed(const Duration(milliseconds: 60)); + + final add = connection.addContact(contact()); + await transport.settle(); + transport.emit([ResponseCodes.ok]); + expect(await isDone(add), isTrue); + }); + + test('a failed TX write leaves no claim behind', () async { + transport.failWrites = true; + await expectLater(sendTx(), throwsA(isA())); + transport.failWrites = false; + + final add = connection.addContact(contact()); + await transport.settle(); + transport.emit([ResponseCodes.ok]); + expect(await isDone(add), isTrue); + }); + + test('dispose releases a TX still waiting for its reply', () async { + final tx = sendTx(); + await transport.settle(); + connection.dispose(); + expect(await isDone(tx), isTrue); + }); +} diff --git a/test/services/noise_floor_session_store_test.dart b/test/services/noise_floor_session_store_test.dart new file mode 100644 index 00000000..6258c5fd --- /dev/null +++ b/test/services/noise_floor_session_store_test.dart @@ -0,0 +1,217 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:mesh_mapper/models/noise_floor_session.dart'; +import 'package:mesh_mapper/services/noise_floor_session_store.dart'; + +/// The History tab's recording session lived only in memory until the mode +/// stopped, so an app killed mid-drive lost the whole entry (graph, ping +/// markers, view on map). It is now checkpointed while it runs, and a +/// checkpoint left open by a kill is closed at the next launch. +void main() { + late Directory directory; + const boxName = 'noise_floor_sessions'; + + // Registered once: Hive.resetAdapters() also drops Hive's own DateTime + // adapter, which these models need. + setUpAll(() { + Hive.registerAdapter(NoiseFloorSampleAdapter()); + Hive.registerAdapter(PingEventTypeAdapter()); + Hive.registerAdapter(MarkerRepeaterInfoAdapter()); + Hive.registerAdapter(PingEventMarkerAdapter()); + Hive.registerAdapter(NoiseFloorSessionAdapter()); + }); + + setUp(() async { + directory = await Directory.systemTemp.createTemp('nf-sessions-'); + Hive.init(directory.path); + }); + + tearDown(() async { + await Hive.close(); + await directory.delete(recursive: true); + }); + + final t0 = DateTime(2026, 11, 8, 9); + + NoiseFloorSession session(String id, DateTime start, + {DateTime? end, int samples = 0}) => + NoiseFloorSession( + id: id, + startTime: start, + endTime: end, + mode: 'passive', + samples: [ + for (var i = 0; i < samples; i++) + NoiseFloorSample( + timestamp: start.add(Duration(seconds: 5 * i)), + noiseFloor: -110), + ], + ); + + Future> open() => + Hive.openBox(boxName); + + /// What a kill does: the process goes away without ending the session. + Future> killAndRelaunch() async { + await Hive.close(); + return open(); + } + + group('checkpoint, kill, relaunch', () { + test('the session comes back closed at its last sample', () async { + var box = await open(); + final live = session('live', t0, samples: 3); + live.markers.add(PingEventMarker( + timestamp: t0.add(const Duration(seconds: 7)), + type: PingEventType.discSuccess, + noiseFloor: -108, + latitude: 45, + longitude: -75)); + final checkpoint = NoiseFloorCheckpoint(); + expect(await checkpoint.write(box, live), isTrue); + live.samples.add(NoiseFloorSample( + timestamp: t0.add(const Duration(minutes: 4)), noiseFloor: -105)); + expect(await checkpoint.write(box, live), isTrue); + + box = await killAndRelaunch(); + final stored = await loadStoredNoiseFloorSessions(box); + + expect(stored, hasLength(1)); + expect(stored.single.id, 'live'); + expect(stored.single.isActive, isFalse); + expect(stored.single.endTime, t0.add(const Duration(minutes: 4))); + expect(stored.single.samples, hasLength(4)); + expect(stored.single.markers.single.latitude, 45); + + // The close is written back, so a later launch reads it closed too. + box = await killAndRelaunch(); + expect(box.get('live')!.endTime, t0.add(const Duration(minutes: 4))); + }); + + test('a marker later than the last sample sets the end', () { + final s = session('s', t0, samples: 2) + ..markers.add(PingEventMarker( + timestamp: t0.add(const Duration(minutes: 1)), + type: PingEventType.txFail, + noiseFloor: -100)); + expect(interruptedNoiseFloorSessionEnd(s), + t0.add(const Duration(minutes: 1))); + }); + + test('a session with nothing recorded ends at its start', () { + expect(interruptedNoiseFloorSessionEnd(session('s', t0)), t0); + }); + + test('closed sessions load unchanged, newest first', () async { + final box = await open(); + await box.put('old', session('old', t0, end: t0, samples: 1)); + await box.put( + 'new', + session('new', t0.add(const Duration(hours: 1)), + end: t0.add(const Duration(hours: 2)), samples: 1)); + final stored = await loadStoredNoiseFloorSessions(box); + expect(stored.map((s) => s.id), ['new', 'old']); + expect(stored.first.endTime, t0.add(const Duration(hours: 2))); + }); + + test('a recovered session past the cap drops the oldest', () async { + var box = await open(); + for (var i = 0; i < maxStoredNoiseFloorSessions; i++) { + final start = t0.add(Duration(hours: i)); + await box.put('s$i', session('s$i', start, end: start, samples: 1)); + } + await NoiseFloorCheckpoint().write( + box, session('live', t0.add(const Duration(days: 1)), samples: 2)); + + box = await killAndRelaunch(); + final stored = await loadStoredNoiseFloorSessions(box); + + expect(stored, hasLength(maxStoredNoiseFloorSessions)); + expect(stored.first.id, 'live'); + expect(stored.map((s) => s.id), isNot(contains('s0'))); + expect(box.length, maxStoredNoiseFloorSessions); + expect(box.containsKey('s0'), isFalse); + }); + }); + + group('checkpoint writes', () { + test('nothing new since the last write skips it', () async { + final box = await open(); + final live = session('live', t0, samples: 2); + final checkpoint = NoiseFloorCheckpoint(); + expect(await checkpoint.write(box, live), isTrue); + expect(await checkpoint.write(box, live), isFalse); + live.markers.add(PingEventMarker( + timestamp: t0, type: PingEventType.rx, noiseFloor: -110)); + expect(await checkpoint.write(box, live), isTrue); + }); + + test('an ended session is never checkpointed', () async { + final box = await open(); + final ended = session('done', t0, end: t0, samples: 2); + expect(await NoiseFloorCheckpoint().write(box, ended), isFalse); + expect(box.isEmpty, isTrue); + }); + + test('no box writes nothing', () async { + expect(await NoiseFloorCheckpoint().write(null, session('s', t0)), + isFalse); + }); + }); + + group('ending a session', () { + test('a session never checkpointed is stored as before', () async { + final box = await open(); + final stored = []; + final live = session('live', t0, samples: 2) + ..endTime = t0.add(const Duration(minutes: 1)); + await saveEndedNoiseFloorSession(box, stored, live); + expect(stored.map((s) => s.id), ['live']); + expect(box.get('live')!.endTime, t0.add(const Duration(minutes: 1))); + }); + + test('a checkpointed session is stored once, not twice', () async { + final box = await open(); + final stored = []; + final live = session('live', t0, samples: 2); + await NoiseFloorCheckpoint().write(box, live); + live.endTime = t0.add(const Duration(minutes: 1)); + await saveEndedNoiseFloorSession(box, stored, live); + expect(stored, hasLength(1)); + expect(box.length, 1); + expect(box.get('live')!.endTime, t0.add(const Duration(minutes: 1))); + }); + + test('the cap of 10 holds with a checkpoint in the box', () async { + final box = await open(); + final stored = []; + for (var i = maxStoredNoiseFloorSessions - 1; i >= 0; i--) { + final start = t0.add(Duration(hours: i)); + final s = session('s$i', start, end: start, samples: 1); + await box.put(s.id, s); + stored.add(s); + } + final live = session('live', t0.add(const Duration(days: 1))); + await NoiseFloorCheckpoint().write(box, live); + expect(box.length, maxStoredNoiseFloorSessions + 1); + + live.endTime = live.startTime.add(const Duration(minutes: 5)); + await saveEndedNoiseFloorSession(box, stored, live); + + expect(stored, hasLength(maxStoredNoiseFloorSessions)); + expect(stored.first.id, 'live'); + expect(stored.map((s) => s.id), isNot(contains('s0'))); + expect(box.length, maxStoredNoiseFloorSessions); + expect(box.containsKey('s0'), isFalse); + }); + + test('with no box the list still updates', () async { + final stored = []; + final live = session('live', t0)..endTime = t0; + await saveEndedNoiseFloorSession(null, stored, live); + expect(stored.single.id, 'live'); + }); + }); +} diff --git a/test/services/offline_session_export_test.dart b/test/services/offline_session_export_test.dart new file mode 100644 index 00000000..e6db6e0d --- /dev/null +++ b/test/services/offline_session_export_test.dart @@ -0,0 +1,110 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:mesh_mapper/services/offline_session_export.dart'; +import 'package:mesh_mapper/services/offline_session_service.dart'; + +/// Export all offline sessions (#560): one JSON file per stored session, the +/// same name and pretty JSON the single-session export writes, and nothing +/// about the stored sessions changes afterwards. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory dir; + + setUp(() async { + dir = await Directory.systemTemp.createTemp('offline_export_test'); + }); + + tearDown(() async { + if (await dir.exists()) await dir.delete(recursive: true); + }); + + OfflineSession session(String filename, {int pings = 2}) => OfflineSession( + filename: filename, + createdAt: DateTime(2026, 11, 9, 12), + pingCount: pings, + data: { + 'offline': true, + 'ping_count': pings, + 'pings': List.generate(pings, (i) => {'type': 'TX', 'seq': i}), + }, + ); + + test('the JSON is the pretty JSON the single-session export writes', () { + final data = session('2026-11-09.json').data; + expect(offlineSessionJson(data), + const JsonEncoder.withIndent(' ').convert(data)); + }); + + test('no sessions gives no files', () async { + final files = await writeOfflineSessionExports(const [], dir); + expect(files, isEmpty); + }); + + test('one session gives one file named after it', () async { + final s = session('2026-11-09.json'); + final files = await writeOfflineSessionExports([s], dir); + + expect(files, hasLength(1)); + expect(files.single.path, '${dir.path}/2026-11-09.json'); + expect(await files.single.readAsString(), offlineSessionJson(s.data)); + }); + + test('every session gets its own file, in list order', () async { + final sessions = [ + session('2026-11-09-2.json', pings: 3), + session('2026-11-09.json', pings: 1), + session('2026-11-08.json', pings: 500), + ]; + final files = await writeOfflineSessionExports(sessions, dir); + + expect(files.map((f) => f.uri.pathSegments.last).toList(), + ['2026-11-09-2.json', '2026-11-09.json', '2026-11-08.json']); + for (var i = 0; i < sessions.length; i++) { + expect(await files[i].readAsString(), offlineSessionJson(sessions[i].data)); + } + }); + + test('a repeated filename is not overwritten', () async { + // A delete can make the service hand out a name that is still in use. + final a = session('2026-11-09-3.json', pings: 1); + final b = session('2026-11-09-3.json', pings: 4); + final files = await writeOfflineSessionExports([a, b], dir); + + expect(files.map((f) => f.uri.pathSegments.last).toList(), + ['2026-11-09-3.json', '2026-11-09-3 (2).json']); + expect(await files[0].readAsString(), offlineSessionJson(a.data)); + expect(await files[1].readAsString(), offlineSessionJson(b.data)); + }); + + test('exporting keeps every session, none marked uploaded', () async { + SharedPreferences.setMockInitialValues({}); + final service = OfflineSessionService(); + await service.init(); + await service.saveSession([ + {'type': 'TX', 'seq': 0} + ], deviceName: 'A'); + await service.saveSession([ + {'type': 'TX', 'seq': 1}, + {'type': 'RX', 'seq': 2}, + ], deviceName: 'B'); + final before = service.sessions.map((s) => jsonEncode(s.toJson())).toList(); + + final files = await writeOfflineSessionExports(service.sessions, dir); + + expect(files, hasLength(2)); + expect(service.sessionCount, 2); + expect(service.sessions.every((s) => !s.uploaded), isTrue); + expect(service.sessions.map((s) => jsonEncode(s.toJson())).toList(), before); + + // And the stored copy is untouched too. + final reloaded = OfflineSessionService(); + await reloaded.init(); + expect(reloaded.sessions.map((s) => jsonEncode(s.toJson())).toList(), + before); + }); +} diff --git a/test/services/offline_session_service_test.dart b/test/services/offline_session_service_test.dart index 23187872..cefa4359 100644 --- a/test/services/offline_session_service_test.dart +++ b/test/services/offline_session_service_test.dart @@ -1,6 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/offline_session_service.dart'; /// Regression tests for the offline-session lifecycle duplicate bug. @@ -73,6 +74,31 @@ void main() { reason: 'finalize breaks tracking so the next save is a new session'); }); + test( + 'replacePings rewrites the whole list and persists it, unlike removeProcessedPings which only drops a prefix', + () async { + SharedPreferences.setMockInitialValues({}); + final service = OfflineSessionService(); + await service.init(); + + final rows = [ + {'type': 'DISC', 'seq': 0}, + {'type': 'SCOPES', 'seq': 1}, + {'type': 'RX', 'seq': 2}, + {'type': 'SCOPES', 'seq': 3}, + ]; + await service.updateCurrentSession(rows, deviceName: 'Test'); + final filename = service.sessions.single.filename; + + final withoutScopes = rows.where((r) => r['type'] != 'SCOPES').toList(); + await service.replacePings(filename, withoutScopes); + + final reloaded = service.getSession(filename)!; + expect(reloaded.pingCount, 2); + expect(reloaded.data['pings'], withoutScopes); + expect(reloaded.data['ping_count'], 2); + }); + test( 'final save with empty queue still finalizes, so next session does not append to the old one', () async { @@ -99,5 +125,47 @@ void main() { expect(service.sessions.first.pingCount, 2, reason: 'second session holds only its own 2 pings'); }); + + test('an offline session keeps the altitude trio through save and reload', + () async { + SharedPreferences.setMockInitialValues({}); + final service = OfflineSessionService(); + await service.init(); + await service.updateCurrentSession([ + { + 'type': 'RX', + 'lat': 45.0, + 'lon': -75.0, + 'altitude': 84, + 'altitude_ref': 'ellipsoid', + 'altitude_acc': 9, + } + ], deviceName: 'Test'); + service.finalizeCurrentSession(); + + final reloaded = OfflineSessionService(); + await reloaded.init(); + final pings = + (reloaded.sessions.first.data['pings'] as List).cast(); + expect(pings.single['altitude'], 84); + expect(pings.single['altitude_ref'], 'ellipsoid'); + expect(pings.single['altitude_acc'], 9); + + final uploaded = >[]; + await runOfflineChunkedUpload( + pings.map((p) => Map.from(p)).toList(), + scopeDiscoveryOffered: true, + batchSize: 50, + persistRows: (_) async {}, + uploadChunk: (chunk, _, __) async { + uploaded.addAll(chunk); + return true; + }, + forwardChunk: (_, __) {}, + ); + expect(uploaded.single['altitude'], 84); + expect(uploaded.single['altitude_ref'], 'ellipsoid'); + expect(uploaded.single['altitude_acc'], 9); + }); }); } diff --git a/test/services/permission_disclosure_service_test.dart b/test/services/permission_disclosure_service_test.dart new file mode 100644 index 00000000..e0fa5904 --- /dev/null +++ b/test/services/permission_disclosure_service_test.dart @@ -0,0 +1,199 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/location_consent.dart'; +import 'package:mesh_mapper/services/permission_disclosure_service.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + group('PermissionDisclosureService.deniedWithoutDialog', () { + test('an instant denial means no dialog was shown', () { + expect( + PermissionDisclosureService.deniedWithoutDialog( + const Duration(milliseconds: 150)), + isTrue, + ); + }); + + test('a denial that took human time came from a dialog', () { + expect( + PermissionDisclosureService.deniedWithoutDialog( + const Duration(seconds: 2)), + isFalse, + ); + }); + + test('the threshold itself counts as a dialog answer', () { + expect( + PermissionDisclosureService.deniedWithoutDialog( + PermissionDisclosureService.silentDenialThreshold), + isFalse, + ); + }); + }); + + // Background location is used only while a radio is connected, so neither + // lead may claim use "even when the app is closed or not in use". + group('disclosure wording says background use follows the connection', () { + test('the location lead is the approved copy', () { + expect( + PermissionDisclosureService.locationDisclosureLead, + 'MeshMapper collects and uses location data while the app is open, ' + 'to show you on the map and check which region you are in. While it ' + 'is connected to your radio, it also uses location to keep the radio ' + 'signed in and, while a wardriving mode runs, to tag your pings and ' + 'map coverage, including with the screen off or another app open. ' + 'When you disconnect and leave the app, MeshMapper stops using your ' + 'location.', + ); + }); + + test('the background lead is the approved copy', () { + expect( + PermissionDisclosureService.backgroundDisclosureLead, + 'MeshMapper collects location data in the background only while your ' + 'radio is connected, to keep tagging pings and mapping coverage ' + 'during a wardriving mode. When you disconnect, it stops.', + ); + }); + + for (final (name, lead) in [ + ('location', PermissionDisclosureService.locationDisclosureLead), + ('background', PermissionDisclosureService.backgroundDisclosureLead), + ]) { + test('$name lead no longer claims use while the app is closed', () { + expect( + lead, isNot(contains('even when the app is closed or not in use'))); + }); + } + }); + + group('LocationConsent.needsDisclosure', () { + test('until agreed, it shows even with no prompt next', () { + expect( + LocationConsent.needsDisclosure(agreed: false, aboutToRequest: false), + isTrue); + }); + + test('once agreed, it shows again before every system prompt', () { + expect( + LocationConsent.needsDisclosure(agreed: true, aboutToRequest: true), + isTrue); + }); + + test('once agreed and granted, it stays away', () { + expect( + LocationConsent.needsDisclosure(agreed: true, aboutToRequest: false), + isFalse); + }); + }); + + Future openAndTap( + WidgetTester tester, + Future Function(BuildContext) show, + String lead, + String button, + ) async { + bool? result; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async => result = await show(context), + child: const Text('open'), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text(lead), findsOneWidget); + for (final point in PermissionDisclosureService.sharingPoints) { + expect(find.text(point), findsOneWidget); + } + await tester.tap(find.text(button)); + await tester.pumpAndSettle(); + return result; + } + + group('PermissionDisclosureService.showLocationDisclosure', () { + setUp(() => SharedPreferences.setMockInitialValues({})); + tearDown(() => debugDefaultTargetPlatformOverride = null); + + Future tap(WidgetTester tester, String button) => openAndTap( + tester, + PermissionDisclosureService.showLocationDisclosure, + PermissionDisclosureService.locationDisclosureLead, + button); + + testWidgets('Agree allows the system prompt and is remembered', + (tester) async { + expect(await tap(tester, 'Agree'), isTrue); + expect(await LocationConsent.hasAgreed(), isTrue); + }); + + testWidgets('Not Now skips the system prompt and is not remembered', + (tester) async { + expect(await tap(tester, 'Not Now'), isFalse); + expect( + await LocationConsent.hasAgreed(), isFalse); + }); + + // The binding checks foundation overrides before tearDown runs, so each + // test puts the platform back itself. + Future openDialog( + WidgetTester tester, TargetPlatform platform) async { + debugDefaultTargetPlatformOverride = platform; + try { + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () => + PermissionDisclosureService.showLocationDisclosure(context), + child: const Text('open'), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + } finally { + debugDefaultTargetPlatformOverride = null; + } + } + + testWidgets('on Android it mentions the connected-radio notification', + (tester) async { + await openDialog(tester, TargetPlatform.android); + expect(find.text(PermissionDisclosureService.androidNotificationPoint), + findsOneWidget); + }); + + testWidgets('on iOS it leaves the notification line out', (tester) async { + await openDialog(tester, TargetPlatform.iOS); + expect(find.text(PermissionDisclosureService.locationDisclosureLead), + findsOneWidget); + expect(find.text(PermissionDisclosureService.androidNotificationPoint), + findsNothing); + }); + + test('Continue on the old dialog still counts as agreeing', () async { + SharedPreferences.setMockInitialValues( + {'location_disclosure_shown': true}); + expect(await LocationConsent.hasAgreed(), isTrue); + }); + }); + + group('PermissionDisclosureService.showBackgroundLocationDisclosure', () { + Future tap(WidgetTester tester, String button) => openAndTap( + tester, + PermissionDisclosureService.showBackgroundLocationDisclosure, + PermissionDisclosureService.backgroundDisclosureLead, + button); + + testWidgets('Agree allows the Always prompt', (tester) async { + expect(await tap(tester, 'Agree'), isTrue); + }); + + testWidgets('Not Now skips it', (tester) async { + expect(await tap(tester, 'Not Now'), isFalse); + }); + }); +} diff --git a/test/services/ping_service_activity_anchor_test.dart b/test/services/ping_service_activity_anchor_test.dart index 5307420c..8f0d39cf 100644 --- a/test/services/ping_service_activity_anchor_test.dart +++ b/test/services/ping_service_activity_anchor_test.dart @@ -8,6 +8,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -19,6 +20,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// activity anchor (and must NOT touch the TX skip anchor). class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; final List activityMarks = []; final List pingMarks = []; @@ -84,7 +88,8 @@ class _FakeConnection implements MeshCoreConnection { Stream get traceDataStream => const Stream.empty(); @override - Future sendDiscoveryRequest() => Future.value(Uint8List(4)); + Future<({Uint8List tag, DateTime sentAt})> sendDiscoveryRequest() => + Future.value((tag: Uint8List(4), sentAt: DateTime.now())); @override Future sendTracePath(Uint8List repeaterIdBytes, diff --git a/test/services/ping_service_airborne_test.dart b/test/services/ping_service_airborne_test.dart index dabcade2..24eec5da 100644 --- a/test/services/ping_service_airborne_test.dart +++ b/test/services/ping_service_airborne_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -17,6 +18,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// mode can send in the seconds between detection and the transport closing. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; bool airborne = false; int freshCalls = 0; @@ -101,7 +105,8 @@ class _FakeConnection implements MeshCoreConnection { dynamic noSuchMethod(Invocation invocation) { if (invocation.memberName == #sendDiscoveryRequest) { discoveryTransmits++; - return Future.value(Uint8List.fromList([1, 2, 3, 4])); + return Future.value( + (tag: Uint8List.fromList([1, 2, 3, 4]), sentAt: DateTime.now())); } if (invocation.memberName == #sendTracePath) { traceTransmits++; diff --git a/test/services/ping_service_discovery_guard_test.dart b/test/services/ping_service_discovery_guard_test.dart index 322d33a2..c53fc52b 100644 --- a/test/services/ping_service_discovery_guard_test.dart +++ b/test/services/ping_service_discovery_guard_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -23,6 +24,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// clear it out from under the manual ping. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; int freshCalls = 0; @@ -103,7 +107,8 @@ class _FakeConnection implements MeshCoreConnection { dynamic noSuchMethod(Invocation invocation) { if (invocation.memberName == #sendDiscoveryRequest) { discoveryTransmits++; - return Future.value(Uint8List.fromList([1, 2, 3, 4])); + return Future.value( + (tag: Uint8List.fromList([1, 2, 3, 4]), sentAt: DateTime.now())); } if (invocation.memberName == #sendPing) { return sendPingGate?.future ?? Future.value(); @@ -173,7 +178,7 @@ PingService _build( rxWindowTimer: RxWindowTimer(), discoveryWindowTimer: discoveryWindow, deviceId: 'TEST', - )..checkRecentCoverage = (lat, lon) => RecentCoverage.clear; + )..checkRecentCoverage = (lat, lon, kind) => RecentCoverage.clear; if (withSession) { service.getSessionId = () => 'YYZ-20260914-0001'; service.getNextPingCounter = () => 1; @@ -388,7 +393,7 @@ void main() { // easiest to stand one up on. final ping = _build(gps, conn, discoveryWindow) ..checkRecentCoverage = - (lat, lon) => throw StateError('coverage lookup failed'); + (lat, lon, kind) => throw StateError('coverage lookup failed'); // Park the opening discovery on its fresh fix, then stop Passive: the // latch turns the stop into a parked disable waiting on this attempt. diff --git a/test/services/ping_service_dispose_test.dart b/test/services/ping_service_dispose_test.dart new file mode 100644 index 00000000..c2dac49a --- /dev/null +++ b/test/services/ping_service_dispose_test.dart @@ -0,0 +1,297 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/models/device_model.dart'; +import 'package:mesh_mapper/models/log_entry.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/ping_service.dart'; +import 'package:mesh_mapper/services/recent_coverage_service.dart'; +import 'package:mesh_mapper/services/wakelock_service.dart'; + +/// A disposed PingService must stay silent. +/// +/// Both radio-drop paths in the provider dispose the service without a force +/// disable first. A send parked on its fresh fix (or on the BLE write) then +/// resumed into a service whose mode flags still said on, and its skip or +/// failure path re-armed a timer that kept pinging after the radio was gone. + +class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + + Position? position; + int freshCalls = 0; + bool canPingHere = true; + Completer? freshPositionGate; + + @override + GpsStatus get status => GpsStatus.locked; + + @override + Position? get lastPosition => position; + + @override + bool get isAirborne => false; + + @override + bool isAccuracyAcceptableForPing(Position position) => true; + + @override + bool canPingAtPosition(Position position) => canPingHere; + + @override + double get configuredMinDistance => 25.0; + + @override + void markActivityPosition(Position position) {} + + @override + void markPingPosition(Position position) {} + + @override + Future getFreshPosition( + {Duration timeout = const Duration(seconds: 3)}) async { + freshCalls++; + final gate = freshPositionGate; + if (gate != null) await gate.future; + return position; + } + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('GpsService.${invocation.memberName}'); +} + +class _FakeConnection implements MeshCoreConnection { + /// Held by the test to park a discovery on its BLE write. + Completer? discoveryGate; + + /// When set, the parked (or immediate) discovery write throws. + bool failDiscovery = false; + int discoveryAttempts = 0; + int pingTransmits = 0; + + @override + ConnectionStep get currentStep => ConnectionStep.connected; + + @override + DeviceModel? get deviceModel => null; + + @override + int? get lastNoiseFloor => null; + + @override + int? get wardrivingChannelIndex => null; + + @override + Uint8List? get wardrivingChannelKey => null; + + @override + int? get wardrivingChannelHash => null; + + @override + Stream<({Uint8List raw, double snr, int rssi})> get controlDataStream => + const Stream.empty(); + + @override + Stream get traceDataStream => const Stream.empty(); + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #sendDiscoveryRequest) { + discoveryAttempts++; + Future<({Uint8List tag, DateTime sentAt})> send() async { + final gate = discoveryGate; + if (gate != null) await gate.future; + if (failDiscovery) throw StateError('GATT write failed'); + return (tag: Uint8List.fromList([1, 2, 3, 4]), sentAt: DateTime.now()); + } + + return send(); + } + if (invocation.memberName == #sendPing) { + pingTransmits++; + return Future.value(); + } + throw UnimplementedError('MeshCoreConnection.${invocation.memberName}'); + } +} + +class _FakeApiQueue implements ApiQueueService { + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName.toString().contains('enqueue')) { + return Future.value(); + } + throw UnimplementedError('ApiQueueService.${invocation.memberName}'); + } +} + +class _FakeWakelock implements WakelockService { + @override + bool get isEnabled => false; + + @override + Future enable() async {} + + @override + Future disable() async {} + + @override + Future dispose() async {} +} + +Position _pos({double lat = 45.0, double lon = -75.0}) => Position( + latitude: lat, + longitude: lon, + timestamp: DateTime.now(), + accuracy: 5.0, + altitude: 0.0, + altitudeAccuracy: 1.0, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 1.0, + ); + +PingService _build(_FakeGps gps, _FakeConnection conn, + DiscoveryWindowTimer discoveryWindow) { + final service = PingService( + gpsService: gps, + connection: conn, + apiQueue: _FakeApiQueue(), + wakelockService: _FakeWakelock(), + cooldownTimer: CooldownTimer(), + manualPingCooldownTimer: ManualPingCooldownTimer(), + rxWindowTimer: RxWindowTimer(), + discoveryWindowTimer: discoveryWindow, + deviceId: 'TEST', + )..checkRecentCoverage = (lat, lon, kind) => RecentCoverage.clear; + service.getSessionId = () => 'YYZ-20260914-0001'; + service.getNextPingCounter = () => 1; + return service; +} + +void main() { + testWidgets('dispose during an Active fresh fix arms no timer', + (tester) async { + final gps = _FakeGps() + ..position = _pos() + // The resumed ping fails validation, which is the skip path that + // re-arms the lane. + ..canPingHere = false + ..freshPositionGate = Completer(); + final conn = _FakeConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final ping = _build(gps, conn, discoveryWindow); + var scheduledAfterDispose = 0; + var disposed = false; + ping.onAutoPingScheduled = (_, __) { + if (disposed) scheduledAfterDispose++; + }; + + unawaited(ping.enableAutoPing()); + await tester.pump(); + expect(gps.freshCalls, 1, reason: 'the opening ping awaits its fix'); + + ping.dispose(); + disposed = true; + gps.freshPositionGate!.complete(); + gps.freshPositionGate = null; + gps.canPingHere = true; + await tester.pump(); + await tester.pump(const Duration(minutes: 2)); + + expect(scheduledAfterDispose, 0, reason: 'no timer re-armed after dispose'); + expect(gps.freshCalls, 1, reason: 'no further auto ping attempted'); + expect(conn.pingTransmits, 0, reason: 'nothing went on the air'); + expect(ping.autoPingEnabled, isFalse); + discoveryWindow.stop(); + }); + + testWidgets('dispose during a Hybrid fresh fix sends nothing', + (tester) async { + final gps = _FakeGps() + ..position = _pos() + ..freshPositionGate = Completer(); + final conn = _FakeConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final ping = _build(gps, conn, discoveryWindow); + + unawaited(ping.enableAutoPing(hybridMode: true)); + await tester.pump(); + expect(gps.freshCalls, 1); + + ping.dispose(); + gps.freshPositionGate!.complete(); + gps.freshPositionGate = null; + await tester.pump(); + await tester.pump(const Duration(minutes: 2)); + + expect(conn.discoveryAttempts, 0); + expect(conn.pingTransmits, 0); + expect(gps.freshCalls, 1); + discoveryWindow.stop(); + }); + + testWidgets('a discovery write failing after dispose does not reschedule', + (tester) async { + final gps = _FakeGps()..position = _pos(); + final conn = _FakeConnection() + ..discoveryGate = Completer() + ..failDiscovery = true; + final discoveryWindow = DiscoveryWindowTimer(); + final ping = _build(gps, conn, discoveryWindow); + var scheduledAfterDispose = 0; + var disposed = false; + ping.onAutoPingScheduled = (_, __) { + if (disposed) scheduledAfterDispose++; + }; + + unawaited(ping.enableAutoPing(passiveMode: true)); + await tester.pump(); + expect(conn.discoveryAttempts, 1, reason: 'parked on the BLE write'); + + ping.dispose(); + disposed = true; + conn.discoveryGate!.complete(); + conn.discoveryGate = null; + await tester.pump(); + await tester.pump(const Duration(minutes: 2)); + + expect(scheduledAfterDispose, 0); + expect(conn.discoveryAttempts, 1, reason: 'no retry after dispose'); + discoveryWindow.stop(); + }); + + testWidgets('a failed discovery write withdraws its log entry', + (tester) async { + final gps = _FakeGps()..position = _pos(); + final conn = _FakeConnection()..failDiscovery = true; + final discoveryWindow = DiscoveryWindowTimer(); + final ping = _build(gps, conn, discoveryWindow); + final published = []; + final withdrawn = []; + ping.onDiscPing = published.add; + ping.onDiscPingAborted = withdrawn.add; + + await ping.enableAutoPing(passiveMode: true); + await tester.pump(); + + expect(conn.discoveryAttempts, 1); + expect(published, hasLength(1)); + expect(withdrawn, hasLength(1)); + expect(identical(withdrawn.single, published.single), isTrue, + reason: 'the entry published before the write is the one withdrawn'); + + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + }); +} diff --git a/test/services/ping_service_held_tx_test.dart b/test/services/ping_service_held_tx_test.dart new file mode 100644 index 00000000..b65c9730 --- /dev/null +++ b/test/services/ping_service_held_tx_test.dart @@ -0,0 +1,252 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/models/device_model.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/ping_service.dart'; +import 'package:mesh_mapper/services/recent_coverage_service.dart'; +import 'package:mesh_mapper/services/wakelock_service.dart'; + +/// A TX that comes due while a replacement session is being installed (an +/// expiry recovery, or a group handoff) bows out at the recovery hold. The +/// bow-out re-arms the lane at a full interval so it cannot die, which used to +/// push that ping a whole interval back; now the release pulls the held leg in +/// to about a second, and in Hybrid it is the TX leg that runs, not the +/// discovery the flag had already flipped to. + +class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + + Position? position; + + @override + GpsStatus get status => GpsStatus.locked; + + @override + Position? get lastPosition => position; + + @override + bool get isAirborne => false; + + @override + bool isAccuracyAcceptableForPing(Position position) => true; + + @override + bool canPingAtPosition(Position position) => true; + + @override + double get configuredMinDistance => 25.0; + + @override + void markPingPosition(Position position) {} + + @override + void markActivityPosition(Position position) {} + + @override + Future getFreshPosition( + {Duration timeout = const Duration(seconds: 3)}) async => + position; + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('GpsService.${invocation.memberName}'); +} + +class _FakeConnection implements MeshCoreConnection { + int txTransmits = 0; + int discoveryTransmits = 0; + + @override + ConnectionStep get currentStep => ConnectionStep.connected; + + @override + DeviceModel? get deviceModel => null; + + @override + int? get lastNoiseFloor => null; + + @override + int? get wardrivingChannelIndex => null; + + @override + Uint8List? get wardrivingChannelKey => null; + + @override + int? get wardrivingChannelHash => null; + + @override + Stream<({Uint8List raw, double snr, int rssi})> get controlDataStream => + const Stream.empty(); + + @override + Stream get traceDataStream => const Stream.empty(); + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #sendPing) { + txTransmits++; + return Future.value(); + } + if (invocation.memberName == #sendDiscoveryRequest) { + discoveryTransmits++; + return Future.value( + (tag: Uint8List.fromList([1, 2, 3, 4]), sentAt: DateTime.now())); + } + throw UnimplementedError('MeshCoreConnection.${invocation.memberName}'); + } +} + +class _FakeApiQueue implements ApiQueueService { + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName.toString().contains('enqueue')) { + return Future.value(); + } + throw UnimplementedError('ApiQueueService.${invocation.memberName}'); + } +} + +class _FakeWakelock implements WakelockService { + @override + bool get isEnabled => false; + + @override + Future enable() async {} + + @override + Future disable() async {} + + @override + Future dispose() async {} +} + +Position _pos({double lat = 45.0}) => Position( + latitude: lat, + longitude: -75.0, + timestamp: DateTime.now(), + accuracy: 5.0, + altitude: 0.0, + altitudeAccuracy: 1.0, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 1.0, + ); + +PingService _build( + _FakeGps gps, _FakeConnection conn, List scheduled) { + final service = PingService( + gpsService: gps, + connection: conn, + apiQueue: _FakeApiQueue(), + wakelockService: _FakeWakelock(), + cooldownTimer: CooldownTimer(), + manualPingCooldownTimer: ManualPingCooldownTimer(), + rxWindowTimer: RxWindowTimer(), + discoveryWindowTimer: DiscoveryWindowTimer(), + deviceId: 'TEST', + )..checkRecentCoverage = (lat, lon, kind) => RecentCoverage.clear; + service.getSessionId = () => 'YOW-20261012-0001'; + service.getNextPingCounter = () => 1; + service.onAutoPingScheduled = (intervalMs, skipReason) => + scheduled.add(intervalMs); + return service; +} + +void main() { + testWidgets('an Active TX held by the recovery goes out a second after it', + (tester) async { + final gps = _FakeGps()..position = _pos(); + final conn = _FakeConnection(); + final scheduled = []; + final ping = _build(gps, conn, scheduled); + + ping.setSessionRecoveryInProgress(true); + await ping.enableAutoPing(); + await tester.pump(); + expect(conn.txTransmits, 0, reason: 'the hold refused the opening ping'); + expect(scheduled.last, greaterThan(10000), + reason: 'the bow-out re-armed a full interval as the backstop'); + + ping.setSessionRecoveryInProgress(false); + expect(scheduled.last, PingService.heldTxReleaseDelay.inMilliseconds, + reason: 'the release pulled the held TX in'); + await tester.pump(const Duration(milliseconds: 900)); + expect(conn.txTransmits, 0); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(); + expect(conn.txTransmits, 1, reason: 'about a second, not an interval'); + + // The lane then runs on its ordinary interval. + await tester.pump(const Duration(seconds: 40)); + await tester.pump(); + expect(conn.txTransmits, 2); + + ping.dispose(); + }); + + testWidgets('a release with nothing held re-arms nothing', (tester) async { + final gps = _FakeGps()..position = _pos(); + final conn = _FakeConnection(); + final scheduled = []; + final ping = _build(gps, conn, scheduled); + + await ping.enableAutoPing(); + await tester.pump(); + expect(conn.txTransmits, 1); + final before = scheduled.length; + + ping.setSessionRecoveryInProgress(true); + ping.setSessionRecoveryInProgress(false); + expect(scheduled.length, before, + reason: 'no TX bowed out, so the schedule is untouched'); + + ping.dispose(); + }); + + testWidgets('in Hybrid the held TX leg is the one that runs', (tester) async { + final gps = _FakeGps()..position = _pos(); + final conn = _FakeConnection(); + final scheduled = []; + final ping = _build(gps, conn, scheduled); + + // Hybrid opens with a discovery; its TX leg comes due an interval later. + await ping.enableAutoPing(hybridMode: true); + await tester.pump(); + expect(conn.discoveryTransmits, 1); + expect(conn.txTransmits, 0); + + // The swap starts before the TX leg; the leg bows out at the hold. + ping.setSessionRecoveryInProgress(true); + await tester.pump(const Duration(seconds: 40)); + await tester.pump(); + expect(conn.txTransmits, 0, reason: 'the hold refused the TX leg'); + expect(conn.discoveryTransmits, 1); + + ping.setSessionRecoveryInProgress(false); + expect(scheduled.last, PingService.heldTxReleaseDelay.inMilliseconds); + await tester.pump(const Duration(milliseconds: 1100)); + await tester.pump(); + expect(conn.txTransmits, 1, reason: 'the TX leg ran, a second later'); + expect(conn.discoveryTransmits, 1, + reason: 'the alternation did not skip to discovery'); + + // And the alternation continues: discovery next. The discovery lane has + // its own 25 m rule against the last discovery, so the phone moves. + gps.position = _pos(lat: 45.01); + await tester.pump(const Duration(seconds: 40)); + await tester.pump(); + expect(conn.discoveryTransmits, 2); + + ping.dispose(); + }); +} diff --git a/test/services/ping_service_passive_restart_test.dart b/test/services/ping_service_passive_restart_test.dart index 0a3d2696..f5967dd7 100644 --- a/test/services/ping_service_passive_restart_test.dart +++ b/test/services/ping_service_passive_restart_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -27,6 +28,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// a new session always opens with a discovery. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; @override @@ -99,8 +103,9 @@ class _FakeConnection implements MeshCoreConnection { dynamic noSuchMethod(Invocation invocation) { if (invocation.memberName == #sendDiscoveryRequest) { discoveryTransmits++; - return discoveryGate?.future ?? - Future.value(Uint8List.fromList([1, 2, 3, 4])); + return (discoveryGate?.future ?? + Future.value(Uint8List.fromList([1, 2, 3, 4]))) + .then((tag) => (tag: tag, sentAt: DateTime.now())); } throw UnimplementedError('MeshCoreConnection.${invocation.memberName}'); } @@ -159,7 +164,7 @@ PingService _build( rxWindowTimer: RxWindowTimer(), discoveryWindowTimer: discoveryWindow, deviceId: 'TEST', - )..checkRecentCoverage = (lat, lon) => RecentCoverage.clear; + )..checkRecentCoverage = (lat, lon, kind) => RecentCoverage.clear; void main() { testWidgets('a user stop keeps the 25 m anchor, so a restart in place is held', diff --git a/test/services/ping_service_pending_disable_test.dart b/test/services/ping_service_pending_disable_test.dart index f7c4dc13..b96114bf 100644 --- a/test/services/ping_service_pending_disable_test.dart +++ b/test/services/ping_service_pending_disable_test.dart @@ -8,6 +8,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -23,6 +24,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// ping's window drained it 41s later. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; bool tooClose = false; Completer? freshPositionGate; @@ -99,15 +103,17 @@ class _FakeConnection implements MeshCoreConnection { Stream get traceDataStream => const Stream.empty(); @override - Future sendPing(String message) async { + Future sendPing(String message, {void Function()? onWire}) async { + onWire?.call(); txTransmits++; if (sendPingThrows) throw Exception('BLE write failed'); } @override - Future sendDiscoveryRequest() { + Future<({Uint8List tag, DateTime sentAt})> sendDiscoveryRequest() { discoveryTransmits++; - return discoveryGate?.future ?? Future.value(Uint8List(4)); + return (discoveryGate?.future ?? Future.value(Uint8List(4))) + .then((tag) => (tag: tag, sentAt: DateTime.now())); } @override diff --git a/test/services/ping_service_recovery_test.dart b/test/services/ping_service_recovery_test.dart index ddeac75b..188c3ba5 100644 --- a/test/services/ping_service_recovery_test.dart +++ b/test/services/ping_service_recovery_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -22,6 +23,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// flags still read enabled. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; int freshCalls = 0; @@ -164,7 +168,7 @@ PingService _build( rxWindowTimer: RxWindowTimer(), discoveryWindowTimer: DiscoveryWindowTimer(), deviceId: 'TEST', - )..checkRecentCoverage = (lat, lon) => coverage.answer; + )..checkRecentCoverage = (lat, lon, kind) => coverage.answer; service.getSessionId = () => 'YYZ-20260916-0001'; service.getNextPingCounter = () => 1; service.onAutoPingScheduled = (intervalMs, skipReason) => diff --git a/test/services/ping_service_scope_runner_test.dart b/test/services/ping_service_scope_runner_test.dart new file mode 100644 index 00000000..8fc4247e --- /dev/null +++ b/test/services/ping_service_scope_runner_test.dart @@ -0,0 +1,906 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/models/device_model.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; +import 'package:mesh_mapper/services/ping_service.dart'; +import 'package:mesh_mapper/services/recent_coverage_service.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_discovery_rules.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_runner.dart'; +import 'package:mesh_mapper/services/wakelock_service.dart'; + +import 'meshcore/scope_test_support.dart' as lease_support; + +/// The scope runner rides alongside the discovery schedule and must never +/// move it: these tests run the real PingService on a fake radio and compare +/// every scheduled moment with and without a runner. + +class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + + double _lat = 45.0; + bool tooClose = false; + + Position get _next { + // Each fresh fix is 100 m further north, so the 25 m rule never holds a + // discovery back. + _lat += 0.0009; + return _pos(_lat, -75.0); + } + + Position? _last; + + @override + GpsStatus get status => GpsStatus.locked; + + @override + Position? get lastPosition => _last ??= _pos(_lat, -75.0); + + @override + Future getFreshPosition( + {Duration timeout = const Duration(seconds: 3)}) async { + _last = _next; + return _last; + } + + @override + bool isAccuracyAcceptableForPing(Position position) => true; + + @override + bool get isAirborne => false; + + @override + bool canPingAtPosition(Position position) => !tooClose; + + @override + double get configuredMinDistance => 25.0; + + @override + void markPingPosition(Position position) {} + + @override + void markActivityPosition(Position position) {} + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('GpsService.${invocation.memberName}'); +} + +/// Answers every discovery with [replies] (own tag unless told otherwise), +/// 300 ms after the send. +class _FakeConnection implements MeshCoreConnection { + final StreamController<({Uint8List raw, double snr, int rssi})> control = + StreamController.broadcast(sync: true); + final List events = []; + final DateTime t0; + List<({int keyFill, int type, bool own, int rssi})> replies = [ + (keyFill: 0x11, type: DiscoveryConstants.nodeTypeRepeater, own: true, rssi: -70), + (keyFill: 0x22, type: DiscoveryConstants.nodeTypeRepeater, own: true, rssi: -80), + ]; + Duration replyDelay = const Duration(milliseconds: 300); + + /// Runs at the moment a discovery reaches the radio. + void Function()? onDiscoveryWrite; + + _FakeConnection(this.t0); + + int get _ms => clock.now().difference(t0).inMilliseconds; + + @override + ConnectionStep get currentStep => ConnectionStep.connected; + + @override + DeviceModel? get deviceModel => null; + + @override + int? get lastNoiseFloor => null; + + @override + int? get wardrivingChannelIndex => null; + + @override + Uint8List? get wardrivingChannelKey => null; + + @override + int? get wardrivingChannelHash => null; + + @override + Stream<({Uint8List raw, double snr, int rssi})> get controlDataStream => + control.stream; + + @override + Stream get traceDataStream => const Stream.empty(); + + @override + Future sendPing(String message, {void Function()? onWire}) async { + onWire?.call(); + events.add('tx@$_ms'); + } + + @override + Future<({Uint8List tag, DateTime sentAt})> sendDiscoveryRequest() async { + onDiscoveryWrite?.call(); + events.add('disc@$_ms'); + const own = [1, 2, 3, 4]; + for (final r in replies) { + Timer(replyDelay, () { + control.add(( + raw: Uint8List.fromList([ + 0, + DiscoveryConstants.discoverRespFlag | r.type, + 20, + ...(r.own ? own : const [9, 9, 9, 9]), + ...List.filled(32, r.keyFill), + ]), + snr: 5.0, + rssi: r.rssi, + )); + }); + } + return (tag: Uint8List.fromList(own), sentAt: clock.now()); + } + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('MeshCoreConnection.${invocation.memberName}'); +} + +class _FakeApiQueue implements ApiQueueService { + /// When set, every DISC write parks on it. + Completer? discGate; + int discWrites = 0; + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #enqueueDisc) { + discWrites++; + return discGate?.future ?? Future.value(); + } + if (invocation.memberName.toString().contains('enqueue')) { + return Future.value(); + } + throw UnimplementedError('ApiQueueService.${invocation.memberName}'); + } +} + +class _FakeWakelock implements WakelockService { + @override + bool get isEnabled => false; + + @override + Future enable() async {} + + @override + Future disable() async {} + + @override + Future dispose() async {} +} + +Position _pos(double lat, double lon) => Position( + latitude: lat, + longitude: lon, + timestamp: DateTime(2026), + accuracy: 5.0, + altitude: 0.0, + altitudeAccuracy: 1.0, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 1.0, + ); + +/// A radio the test drives: a lease is held until [endLeasePhase] (or, in +/// auto mode, for [autoLease]), then the answer wait runs until the wait +/// ends or the test answers. Records what the runner asked and fails on +/// overlap. +class _ControlledRadio implements ScopeRadio { + final List<({String key, Duration? answerWait, DateTime at})> asks = []; + final List overlaps = []; + bool leaseHeld = false; + bool inWait = false; + + /// Null holds each lease until [endLeasePhase]. + Duration? autoLease = const Duration(milliseconds: 100); + + /// When set, the answer wait ends only when the test completes this, and + /// it returns that outcome even after a cancel: an answer that arrives + /// after the runner was stopped. + Completer? lateAnswer; + Completer? _leasePhase; + + void endLeasePhase() => _leasePhase?.complete(); + + @override + Future acquire( + {required Duration admissionWait, + required ScopeCancelToken cancel}) async { + if (leaseHeld || inWait) overlaps.add('overlap'); + if (cancel.isCancelled) return null; + leaseHeld = true; + return _Lease(this, cancel); + } +} + +class _Lease implements ScopeLeaseHandle { + final _ControlledRadio radio; + final ScopeCancelToken cancel; + _Lease(this.radio, this.cancel); + + @override + List get unrestored => const []; + + @override + Future release() async => radio.leaseHeld = false; + + @override + Future restore(ContactRecord original) async => true; + + Future _until(Future f) { + final done = Completer(); + f.then((_) { + if (!done.isCompleted) done.complete(true); + }); + cancel.whenCancelled.then((_) { + if (!done.isCompleted) done.complete(false); + }); + return done.future; + } + + @override + Future requestScopes(Uint8List pubkey, Uint8List request, + {required Duration? answerWait, + required DateTime notAfter, + void Function(Duration wait)? onSent}) async { + final key = pubkey + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join() + .toUpperCase(); + radio.asks.add((key: key, answerWait: answerWait, at: clock.now())); + final auto = radio.autoLease; + final phase = radio._leasePhase = Completer(); + final leaseDone = auto == null + ? phase.future + : Future.delayed(auto); + if (!await _until(leaseDone)) { + radio.leaseHeld = false; + return const ScopeAborted(); + } + radio.leaseHeld = false; + radio.inWait = true; + final late = radio.lateAnswer; + if (late != null) { + final outcome = await late.future; + radio.inWait = false; + return outcome; + } + var wait = answerWait ?? const Duration(seconds: 3); + final end = clock.now().add(wait); + if (notAfter.isBefore(end)) wait = notAfter.difference(clock.now()); + final ran = await _until(Future.delayed(wait)); + radio.inWait = false; + return ran ? const ScopeNoAnswer() : const ScopeAborted(); + } +} + +class _Scenario { + final FakeAsync async; + final DateTime t0; + final _FakeGps gps = _FakeGps(); + late final _FakeConnection conn = _FakeConnection(t0); + final _FakeApiQueue queue = _FakeApiQueue(); + final _ControlledRadio radio = _ControlledRadio(); + final List badge = []; + final List<({DateTime hardStop, DateTime at, DateTime? earliest})> built = []; + final List runners = []; + final List tokens = []; + final List logged = []; + int enqueued = 0; + + /// What Smart Pinging answers for every fix (see [smartPing]). + RecentCoverage coverage = RecentCoverage.clear; + + /// Runs after every schedule the service announces. + void Function(int ms, String? reason)? onScheduled; + late final PingService ping; + + _Scenario(this.async, + {bool withRunner = true, int intervalMs = 30000, bool smartPing = false}) + : t0 = clock.now() { + ping = PingService( + gpsService: gps, + connection: conn, + apiQueue: queue, + wakelockService: _FakeWakelock(), + cooldownTimer: CooldownTimer(), + manualPingCooldownTimer: ManualPingCooldownTimer(), + rxWindowTimer: RxWindowTimer(), + discoveryWindowTimer: DiscoveryWindowTimer(), + deviceId: 'TEST', + ) + ..getSessionId = (() => 'OTT-20260926-0001') + ..getNextPingCounter = (() => 1) + ..onAutoPingScheduled = (ms, reason) { + conn.events.add('sched$ms@${clock.now().difference(t0).inMilliseconds}'); + onScheduled?.call(ms, reason); + }; + if (smartPing) ping.checkRecentCoverage = (_, __, ___) => coverage; + ping.setAutoPingInterval(intervalMs); + if (withRunner) { + ping.scopeRunnerFactory = ({required hardStop, required cancel}) { + built.add(( + hardStop: hardStop, + at: clock.now(), + earliest: ping.earliestNextDiscoveryAt + )); + tokens.add(cancel); + final runner = ScopeRunner( + radio: radio, + cancel: cancel, + hardStop: hardStop, + refreshDays: () => 14, + deviceKey: () => 'DEVICEKEY', + serverInfo: (_) => (onList: false, checkedAt: null), + cache: ScopeQueryCache.fromJson(null), + budget: ScopeHourlyBudget(save: (_) async {}), + enqueue: (_, __) async { + enqueued++; + return true; + }, + nowSec: () => clock.now().millisecondsSinceEpoch ~/ 1000, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: badge.add, + onLogged: logged.add, + pendingRestores: [], + ); + runners.add(runner); + return runner; + }; + } + } + + int ms() => clock.now().difference(t0).inMilliseconds; +} + +List _timeline( + {required bool withRunner, + bool hybrid = false, + int intervalMs = 30000, + bool txSkipped = false, + Duration? holdLease}) { + late List events; + fakeAsync((async) { + final s = _Scenario(async, withRunner: withRunner, intervalMs: intervalMs); + s.gps.tooClose = txSkipped; + s.radio.autoLease = holdLease ?? const Duration(milliseconds: 100); + if (hybrid) { + s.ping.enableAutoPing(hybridMode: true); + } else { + s.ping.enableAutoPing(passiveMode: true); + } + async.elapse(const Duration(seconds: 125)); + if (withRunner) { + expect(s.radio.asks, isNotEmpty, reason: 'the runner really ran'); + expect(s.radio.overlaps, isEmpty); + } + events = List.of(s.conn.events); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + s.ping.dispose(); + async.elapse(const Duration(seconds: 60)); + }, initialTime: DateTime(2026, 9, 26, 10)); + return events; +} + +void main() { + group('scope count', () { + test('counts each answer and resets with the other stats', () { + fakeAsync((async) { + final s = _Scenario(async, withRunner: false); + final seen = []; + s.ping.onStatsUpdated = (stats) => seen.add(stats.scopeCount); + s.ping.recordScopeAnswer(); + s.ping.recordScopeAnswer(); + expect(seen, [1, 2]); + expect(s.ping.stats.scopeCount, 2); + s.ping.resetStats(); + expect(seen.last, 0); + s.ping.dispose(); + }, initialTime: DateTime(2026, 9, 26, 10)); + }); + }); + + group('the schedule never moves', () { + test('Passive: identical with no runner, and with a busy runner', () { + final today = _timeline(withRunner: false); + expect(today.where((e) => e.startsWith('disc@')), + ['disc@0', 'disc@37000', 'disc@74000', 'disc@111000']); + expect(_timeline(withRunner: true), today); + // A runner that holds every lease for 3 s changes nothing either. + expect( + _timeline(withRunner: true, holdLease: const Duration(seconds: 3)), + today); + }); + + test('Hybrid: identical with and without a runner, TX sent or skipped', + () { + for (final interval in [15000, 30000]) { + for (final skipped in [false, true]) { + final today = _timeline( + withRunner: false, + hybrid: true, + intervalMs: interval, + txSkipped: skipped); + expect(today.where((e) => e.startsWith('disc@')).length, + greaterThan(2), reason: today.join(' ')); + expect( + _timeline( + withRunner: true, + hybrid: true, + intervalMs: interval, + txSkipped: skipped), + today, + reason: 'interval $interval, TX skipped $skipped'); + } + } + }); + + test('a factory that returns null asks nothing and changes nothing', () { + late List events; + fakeAsync((async) { + final s = _Scenario(async, withRunner: false); + var calls = 0; + s.ping.scopeRunnerFactory = ({required hardStop, required cancel}) { + calls++; + return null; + }; + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 125)); + expect(calls, greaterThan(0)); + expect(s.ping.isScopeRunnerActive, isFalse); + events = List.of(s.conn.events); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + s.ping.dispose(); + }, initialTime: DateTime(2026, 9, 26, 10)); + expect(events, _timeline(withRunner: false)); + }); + }); + + group('hard stop', () { + test('Passive: the next discovery is 30 s out, and so is the hard stop', + () { + fakeAsync((async) { + final s = _Scenario(async); + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 8)); + final b = s.built.single; + expect(b.earliest, b.at.add(const Duration(seconds: 30))); + expect(b.hardStop, b.at.add(const Duration(seconds: 30))); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + }); + + void hybridAt15(bool txSkipped) { + fakeAsync((async) { + final s = _Scenario(async, intervalMs: 15000); + s.gps.tooClose = txSkipped; + s.ping.enableAutoPing(hybridMode: true); + async.elapse(const Duration(seconds: 120)); + expect(s.built.length, greaterThan(2)); + final discs = [ + for (final e in s.conn.events) + if (e.startsWith('disc@')) int.parse(e.substring(5)), + ]; + for (final b in s.built) { + // The TX leg waits 10 s, the discovery leg 8 s after it. + expect(b.earliest, b.at.add(const Duration(seconds: 18))); + expect(b.hardStop, b.earliest); + final atMs = b.at.difference(s.t0).inMilliseconds; + final hardMs = b.hardStop.difference(s.t0).inMilliseconds; + final next = discs.firstWhere((d) => d > atMs, orElse: () => -1); + if (next < 0) continue; + expect(next, greaterThanOrEqualTo(hardMs), + reason: 'no discovery before the hard stop'); + if (txSkipped) expect(next, hardMs, reason: 'exactly at it'); + } + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + } + + test('Hybrid at 15 s with the TX leg sent', () => hybridAt15(false)); + test('Hybrid at 15 s with the TX leg skipped', () => hybridAt15(true)); + + test('the next discovery send cancels a runner mid-wait', () { + fakeAsync((async) { + final s = _Scenario(async); + // One candidate whose wait outlasts the sweep would never be asked + // (the hard stop refuses it), so hold the lease past the next send + // instead. + s.radio.autoLease = null; + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 8)); + expect(s.radio.leaseHeld, isTrue); + final token = s.tokens.single; + async.elapse(const Duration(seconds: 28)); + expect(token.isCancelled, isFalse); + async.elapse(const Duration(seconds: 1)); // the 37 s discovery + expect(s.conn.events.where((e) => e.startsWith('disc@')).length, 2); + expect(token.isCancelled, isTrue); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + }); + }); + + group('candidates', () { + test('repeaters only, strongest first, own replies carry their time', () { + fakeAsync((async) { + final s = _Scenario(async); + s.conn.replies = [ + (keyFill: 0x11, type: DiscoveryConstants.nodeTypeRoom, own: true, rssi: -50), + (keyFill: 0x22, type: DiscoveryConstants.nodeTypeRepeater, own: false, rssi: -60), + (keyFill: 0x33, type: DiscoveryConstants.nodeTypeRepeater, own: true, rssi: -70), + ]; + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 20)); + expect(s.radio.asks.map((a) => a.key.substring(0, 2)), ['22', '33']); + expect(s.radio.asks[0].answerWait, isNull, + reason: 'another phone\'s discovery: no reply time'); + expect(s.radio.asks[1].answerWait, + const Duration(milliseconds: 2300)); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + }); + + test('DISC items not written within 2 s: nothing asked', () { + fakeAsync((async) { + final s = _Scenario(async); + s.queue.discGate = Completer(); + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 20)); + expect(s.queue.discWrites, 2); + expect(s.radio.asks, isEmpty); + expect(s.ping.isScopeRunnerActive, isFalse); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + }); + }); + + group('cancellation', () { + test('Stop with a Hybrid TX in flight while the runner holds a lease', () { + fakeAsync((async) { + final s = _Scenario(async); + s.radio.autoLease = null; // held until the test says + s.ping.enableAutoPing(hybridMode: true); + async.elapse(const Duration(milliseconds: 32500)); // TX at 32 s + expect(s.radio.leaseHeld, isTrue); + expect(s.conn.events, contains('tx@32000')); + expect(s.ping.pingInProgress, isTrue, reason: 'TX RX window open'); + final token = s.tokens.single; + final accepted = s.ping.disableAutoPing(); + // Before the future is even awaited: already cancelled. + expect(token.isCancelled, isTrue); + expect(s.badge.last, isFalse); + expect(s.ping.pendingDisable, isTrue, reason: 'the stop is parked'); + async.flushMicrotasks(); + expect(s.radio.leaseHeld, isFalse); + var ok = false; + accepted.then((v) => ok = v); + async.elapse(const Duration(seconds: 6)); + expect(ok, isTrue); + expect(s.ping.pendingDisable, isFalse, reason: 'the TX drained'); + expect(s.ping.autoPingEnabled, isFalse); + }); + }); + + test('Stop with a Hybrid TX in flight while the runner waits for an answer', + () { + fakeAsync((async) { + final s = _Scenario(async); + s.conn.replies = [ + (keyFill: 0x11, type: DiscoveryConstants.nodeTypeRepeater, own: true, rssi: -70), + ]; + // A 5 s discovery reply gives a 7 s answer wait; a 23 s lease puts + // that wait across the TX leg at 32 s. + s.conn.replyDelay = const Duration(seconds: 5); + s.radio.autoLease = const Duration(seconds: 23); + s.ping.enableAutoPing(hybridMode: true); + async.elapse(const Duration(milliseconds: 30500)); + expect(s.radio.inWait, isTrue); + async.elapse(const Duration(milliseconds: 2000)); // TX at 32 s + expect(s.conn.events, contains('tx@32000')); + expect(s.ping.pingInProgress, isTrue); + expect(s.radio.inWait, isTrue); + final token = s.tokens.single; + s.ping.disableAutoPing(); + expect(token.isCancelled, isTrue); + expect(s.badge.last, isFalse); + expect(s.ping.pendingDisable, isTrue); + async.flushMicrotasks(); + expect(s.radio.inWait, isFalse); + async.elapse(const Duration(seconds: 6)); + expect(s.ping.pendingDisable, isFalse); + expect(s.ping.autoPingEnabled, isFalse); + }); + }); + + void stopsAtOnce(String name, void Function(_Scenario s) stop) { + test('$name stops the runner at once', () { + fakeAsync((async) { + final s = _Scenario(async); + s.radio.autoLease = null; + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 8)); + expect(s.radio.leaseHeld, isTrue); + expect(s.ping.isScopeRunnerActive, isTrue); + final asked = s.radio.asks.length; + stop(s); + expect(s.tokens.single.isCancelled, isTrue); + expect(s.badge.last, isFalse); + expect(s.ping.isScopeRunnerActive, isFalse); + async.flushMicrotasks(); + expect(s.radio.leaseHeld, isFalse); + async.elapse(const Duration(seconds: 30)); + expect(s.radio.asks.length, asked, reason: 'nothing more asked'); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }); + }); + } + + stopsAtOnce('Stop', (s) => s.ping.disableAutoPing()); + stopsAtOnce('force disable', (s) => s.ping.forceDisableAutoPing()); + // The provider's events reach PingService through this (see + // scope_lifecycle_test.dart for the events themselves). + stopsAtOnce('cancelScopeRunner', + (s) => s.ping.cancelScopeRunner('offline switch')); + stopsAtOnce('dispose', (s) => s.ping.dispose()); + }); + + // Smart Pinging holds a discovery back in a square that is already mapped + // and banks it; the bank is released on the first fix in a clear square. + // A runner's hard stop is the earliest the next discovery can go out, so + // a banked discovery and a live runner meet only at the deferral instant, + // before the runner's own hard-stop timer fires at that same moment. The + // release below is made from exactly there (a microtask after the + // deferral), the one moment the two can overlap. + group('alongside Smart Pinging', () { + /// Passive with Smart Pinging wired. The first discovery goes out clear + /// and starts R1 at 7 s (hard stop 37 s); the 37 s attempt finds the + /// square covered and banks. With [release], the bank is let go into a + /// clear square from the deferral instant. + ({_Scenario s, List log, List atWrite}) + passiveDeferredAt37(FakeAsync async, + {required bool release, + Duration? autoLease, + Completer? lateAnswer}) { + final log = lease_support.captureScopeLog(); + final s = _Scenario(async, smartPing: true); + s.radio.autoLease = autoLease; + s.radio.lateAnswer = lateAnswer; + final atWrite = []; + s.conn.onDiscoveryWrite = () { + if (s.tokens.isEmpty) return; // the first discovery, before R1 + atWrite.add('${s.ms()}:cancelled=${s.tokens.first.isCancelled}' + ':lease=${s.radio.leaseHeld}:asks=${s.radio.asks.length}'); + }; + s.onScheduled = (ms, reason) { + if (reason != PingService.skipReasonRecentlyCovered) return; + atWrite.add('deferred@${s.ms()}:cancelled=${s.tokens.first.isCancelled}'); + if (!release) return; + scheduleMicrotask(() { + s.coverage = RecentCoverage.clear; + final released = s.ping.maybeSendBankedPing(_pos(46.0, -75.0)); + atWrite.add('released=$released'); + }); + }; + s.ping.enableAutoPing(passiveMode: true); + async.elapse(const Duration(seconds: 8)); + expect(s.built, hasLength(1)); + expect(s.built.single.hardStop, s.t0.add(const Duration(seconds: 37))); + s.coverage = RecentCoverage.covered; + async.elapse(const Duration(milliseconds: 28999)); // 36.999 s + return (s: s, log: log, atWrite: atWrite); + } + + test('a banked discovery released while the runner waits for an answer ' + 'cancels it before the write, and its late answer is ignored', () { + fakeAsync((async) { + final late = Completer(); + final t = passiveDeferredAt37(async, + release: true, + autoLease: const Duration(milliseconds: 100), + lateAnswer: late); + final s = t.s; + expect(s.radio.inWait, isTrue, reason: 'R1 is waiting for an answer'); + expect(s.ping.isScopeRunnerActive, isTrue); + async.elapse(const Duration(milliseconds: 1)); // 37 s + expect(t.atWrite, [ + 'deferred@37000:cancelled=false', + 'released=true', + startsWith('37000:cancelled=true'), + ]); + expect( + t.log.where((l) => l.contains('Runner stopped: next discovery')), + hasLength(1)); + expect(t.log.where((l) => l.contains('Runner stopped: hard stop')), + isEmpty); + // The answer lands after the cancel: the runner drops it. + final loggedBefore = s.logged.length; + late.complete(ScopeAnswered( + Uint8List.fromList([0, 0, 0, 0, 0x41]), clock.now())); + s.radio.lateAnswer = null; + async.flushMicrotasks(); + expect(s.enqueued, 0); + expect(s.logged.length, loggedBefore); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }, initialTime: DateTime(2026, 9, 26, 10)); + }); + + test('the same release while the runner holds the lease: the discovery ' + 'goes out once the lease is gone, and R1 writes nothing more', () { + fakeAsync((async) { + final t = passiveDeferredAt37(async, release: true); + final s = t.s; + expect(s.radio.leaseHeld, isTrue, reason: 'R1 holds the radio'); + final asksBefore = s.radio.asks.length; + async.elapse(const Duration(milliseconds: 1)); // 37 s + expect(t.atWrite, [ + 'deferred@37000:cancelled=false', + 'released=true', + '37000:cancelled=true:lease=false:asks=$asksBefore', + ]); + // R2 only starts once the released discovery's window closes at + // 44 s; nothing is asked between the cancel and that. + async.elapse(const Duration(milliseconds: 6900)); + expect(s.built, hasLength(1)); + expect(s.radio.asks.length, asksBefore); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }, initialTime: DateTime(2026, 9, 26, 10)); + }); + + test('a deferred discovery does not cancel the runner, which ends at its ' + 'own hard stop, and starts no new runner', () { + fakeAsync((async) { + // R1 holds the radio through the deferral. + final t = passiveDeferredAt37(async, release: false); + final s = t.s; + expect(s.radio.leaseHeld, isTrue); + async.elapse(const Duration(milliseconds: 1)); // 37 s + expect(t.atWrite, ['deferred@37000:cancelled=false']); + expect(s.tokens.single.isCancelled, isTrue); + expect(s.ping.isScopeRunnerActive, isFalse); + expect(t.log.where((l) => l.contains('Runner stopped: hard stop')), + hasLength(1)); + expect( + t.log.where((l) => l.contains('Runner stopped: next discovery')), + isEmpty); + // Still covered: the 67 s attempt defers too. No window, no runner. + async.elapse(const Duration(seconds: 33)); + expect(s.conn.events.where((e) => e.startsWith('disc@')), ['disc@0']); + expect(s.built, hasLength(1)); + expect(s.ping.bankedPing, BankedPingType.discovery); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }, initialTime: DateTime(2026, 9, 26, 10)); + }); + + // The fakes above cannot show the radio's own lease gate, so this runs + // the same order the release takes (cancel the runner, then write the + // discovery) on a real connection, with the discovery already queued + // behind a held lease. + test('on a real connection, a discovery queued behind a lease goes out ' + 'as soon as the cancel releases it, and no scope frame follows', () { + lease_support.onScopeClock(lease_support.ScopeRadio.new, (async, radio, conn) { + final cancel = ScopeCancelToken(); + final lease = lease_support.grant(async, conn, cancel: cancel)!; + final granted = clock.now(); + var sent = false; + conn.sendDiscoveryRequest().then((_) => sent = true); + async.flushMicrotasks(); + expect(radio.commands, isNot(contains(CommandCodes.sendControlData)), + reason: 'queued at the lease gate'); + async.elapse(const Duration(seconds: 1)); + expect(radio.commands, isNot(contains(CommandCodes.sendControlData))); + + final before = radio.commands.length; + cancel.cancel(); + async.flushMicrotasks(); + expect(lease.active, isFalse); + expect(radio.commands.skip(before), [CommandCodes.sendControlData]); + expect(clock.now().difference(granted), + lessThan(const Duration(seconds: 4))); + + // The cancelled lease writes nothing more. + ScopeRequestOutcome? outcome; + lease + .requestScopes(lease_support.scopeKey(0xAB), Uint8List.fromList([1, 0]), + answerWait: const Duration(seconds: 3), + notAfter: clock.now().add(const Duration(seconds: 30))) + .then((o) => outcome = o); + radio.emit([ResponseCodes.ok]); + async.elapse(const Duration(seconds: 5)); + expect(outcome, isNotNull); + expect(radio.commands.skip(before), [CommandCodes.sendControlData]); + expect(sent, isTrue); + }); + }); + + test('Hybrid with the TX leg deferred: the hard stop still lands before ' + 'the next discovery goes out', () { + for (final interval in [15000, 30000]) { + fakeAsync((async) { + final log = lease_support.captureScopeLog(); + final s = _Scenario(async, intervalMs: interval, smartPing: true); + s.radio.autoLease = null; // R1 would hold the radio indefinitely + final atWrite = []; + var txDeferred = 0; + s.onScheduled = (ms, reason) { + if (reason == PingService.skipReasonRecentlyCovered) { + txDeferred++; + // Only the TX leg is covered: the discovery leg goes out. The + // banked TX would take a clear discovery leg, so it is held + // inside its own 25 m rule to keep that leg a discovery. + s.coverage = RecentCoverage.clear; + s.gps.tooClose = true; + } + }; + s.conn.onDiscoveryWrite = () { + if (s.tokens.isEmpty) return; + atWrite.add('${s.ms()}:cancelled=${s.tokens.first.isCancelled}' + ':lease=${s.radio.leaseHeld}'); + }; + s.ping.enableAutoPing(hybridMode: true); + // Until R1 is built, then cover the TX leg that follows. + while (s.built.isEmpty) { + async.elapse(const Duration(milliseconds: 100)); + } + s.coverage = RecentCoverage.covered; + final hardStop = s.built.single.hardStop; + final earliest = s.built.single.earliest!; + expect(hardStop.isAfter(earliest), isFalse, + reason: 'interval $interval'); + async.elapse(earliest.difference(clock.now()) + + const Duration(seconds: 1)); + expect(txDeferred, 1, reason: 'interval $interval'); + expect(s.conn.events.where((e) => e.startsWith('tx@')), isEmpty); + final earliestMs = earliest.difference(s.t0).inMilliseconds; + // The TX leg deferred with no RX window, so the discovery leg goes + // out exactly at the earliest the runner was built against, and + // the runner is already stopped when it does. + expect(atWrite, ['$earliestMs:cancelled=true:lease=false'], + reason: 'interval $interval'); + expect(log.where((l) => l.contains('Runner stopped: hard stop')), + hasLength(1)); + expect( + log.where((l) => l.contains('Runner stopped: next discovery')), + isEmpty, + reason: 'the hard stop, not the send, ended R1'); + s.ping.forceDisableAutoPing(); + async.flushMicrotasks(); + }, initialTime: DateTime(2026, 9, 26, 10)); + } + }); + }); +} diff --git a/test/services/ping_service_smart_ping_test.dart b/test/services/ping_service_smart_ping_test.dart index a050dcc7..e8543a75 100644 --- a/test/services/ping_service_smart_ping_test.dart +++ b/test/services/ping_service_smart_ping_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -17,6 +18,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// covered. Manual pings and the auto-mode start check never look. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; bool tooClose = false; bool airborne = false; @@ -94,7 +98,8 @@ class _FakeConnection implements MeshCoreConnection { // A released banked discovery reaches the real send path, unlike the // deferral tests where validation returns first. if (invocation.memberName == #sendDiscoveryRequest) { - return Future.value(Uint8List.fromList([1, 2, 3, 4])); + return Future.value( + (tag: Uint8List.fromList([1, 2, 3, 4]), sentAt: DateTime.now())); } throw UnimplementedError('MeshCoreConnection.${invocation.memberName}'); } @@ -137,10 +142,47 @@ Position _pos({double lat = 45.0, double lon = -75.0}) => Position( speedAccuracy: 1.0, ); -/// A coverage answer the test can change after the service is built. +/// A GPS fake whose TX send completes, for tests that let a TX go out. +class _SendingGps extends _FakeGps { + @override + void markPingPosition(Position position) {} +} + +/// A radio that counts what went on the air, and lets a TX send complete. +class _CountingConnection extends _FakeConnection { + int txTransmits = 0; + int discoveryTransmits = 0; + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #sendPing) { + txTransmits++; + return Future.value(); + } + if (invocation.memberName == #sendDiscoveryRequest) { + discoveryTransmits++; + } + return super.noSuchMethod(invocation); + } +} + +/// A coverage answer the test can change after the service is built. [tx] +/// and [discovery] override [answer] for one kind of ping, and [asked] +/// records which kind each lookup was for. class _Coverage { RecentCoverage answer; - _Coverage(this.answer); + RecentCoverage? tx; + RecentCoverage? discovery; + final List asked = []; + _Coverage(this.answer, {this.tx, this.discovery}); + + RecentCoverage answerFor(BankedPingType kind) { + asked.add(kind); + return switch (kind) { + BankedPingType.tx => tx ?? answer, + BankedPingType.discovery => discovery ?? answer, + }; + } } /// [discoveryWindowTimer] and [cooldownTimer] are passed in only by the @@ -163,7 +205,7 @@ PingService _buildWith( rxWindowTimer: RxWindowTimer(), discoveryWindowTimer: discoveryWindowTimer ?? DiscoveryWindowTimer(), deviceId: 'TEST', - )..checkRecentCoverage = (lat, lon) => coverage.answer; + )..checkRecentCoverage = (lat, lon, kind) => coverage.answerFor(kind); PingService _build(_FakeGps gps, RecentCoverage answer) => _buildWith(gps, _Coverage(answer)); @@ -187,6 +229,14 @@ void main() { _build(gps, RecentCoverage.unknown).canPing(), PingValidation.valid); }); + test('the TX validator asks about TX', () { + final gps = _FakeGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.clear); + final ping = _buildWith(gps, coverage); + ping.canPing(); + expect(coverage.asked, [BankedPingType.tx]); + }); + test('no callback means no check', () { final gps = _FakeGps()..position = _pos(); final ping = _build(gps, RecentCoverage.covered)..checkRecentCoverage = null; @@ -678,15 +728,15 @@ void main() { reason: 'a banked ping must not go out on top of a live discovery'); expect(ping.bankedPing, BankedPingType.tx); - // Control: let that discovery finish into a covered square, so it banks - // itself and leaves nothing in flight. The very same clear square now - // releases, which is what makes the refusal above about the discovery and - // not about one of the other guards. + // Control: let that discovery finish into a covered square, so it defers + // (leaving the banked TX ping in place) and leaves nothing in flight. The + // very same clear square now releases, which is what makes the refusal + // above about the discovery and not about one of the other guards. coverage.answer = RecentCoverage.covered; gps.freshPositionGate!.complete(); await tester.pump(); expect(ping.pingInProgress, isFalse); - expect(ping.bankedPing, BankedPingType.discovery); + expect(ping.bankedPing, BankedPingType.tx); coverage.answer = RecentCoverage.clear; expect(ping.maybeSendBankedPing(_pos(lat: 45.01)), isTrue); @@ -828,6 +878,224 @@ void main() { discoveryWindow.stop(); }); + testWidgets('a hybrid discovery leg never replaces a banked TX ping', + (tester) async { + // Hybrid favours the TX ping: once one is held, the discovery legs that + // defer after it leave it in the bank, so the first ping into a fresh + // square is the one that can come back two-way. + final gps = _FakeGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.covered); + final discoveryWindow = DiscoveryWindowTimer(); + final ping = + _buildWith(gps, coverage, discoveryWindowTimer: discoveryWindow); + final reported = []; + ping.onPingDeferred = (lat, lon, held) => reported.add(held); + + // Hybrid opens on discovery, which the covered square banks: no TX ping + // is held yet, so the discovery takes the slot. + await ping.enableAutoPing(hybridMode: true); + expect(ping.bankedPing, BankedPingType.discovery); + + // The TX leg defers in the same square and takes the slot over. + await tester.pump(const Duration(seconds: 24)); + expect(ping.bankedPing, BankedPingType.tx); + + // The next discovery leg defers too and leaves the TX ping in place. + await tester.pump(const Duration(seconds: 24)); + expect(ping.bankedPing, BankedPingType.tx, + reason: 'a deferred discovery must not replace a banked TX ping'); + // The square's DEFER still names what was actually held each time. + expect(reported, [ + BankedPingType.discovery, + BankedPingType.tx, + BankedPingType.tx, + ]); + + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + }); + + // The discovery leg holds the in-progress latch across its own fresh fix, + // and that fix never reaches the GPS stream, so the release check cannot + // see it. With the stream quiet (iOS in the background) the leg itself has + // to hand the slot to the held TX, on 'unknown' as well as 'clear'. + for (final answer in [RecentCoverage.clear, RecentCoverage.unknown]) { + testWidgets( + 'a hybrid discovery leg on a ${answer.name} fix sends the banked TX', + (tester) async { + const discoveryLegWaitMs = 23000; + + final gps = _SendingGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.covered); + final conn = _CountingConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final cooldown = CooldownTimer(); + final ping = _buildWith(gps, coverage, + discoveryWindowTimer: discoveryWindow, + cooldownTimer: cooldown, + connection: conn); + ping.getSessionId = () => 'YOW-20261012-0001'; + ping.getNextPingCounter = () => 1; + final scheduled = []; + ping.onAutoPingScheduled = (intervalMs, _) => scheduled.add(intervalMs); + + // Discovery defers, then the TX leg defers and takes the slot. + await ping.enableAutoPing(hybridMode: true); + await tester.pump(const Duration(seconds: 24)); + expect(ping.bankedPing, BankedPingType.tx); + expect(conn.txTransmits, 0); + expect(conn.discoveryTransmits, 0); + + // The next leg is a discovery, and its fresh fix is not covered. No + // GPS tick runs the release check. + coverage.answer = answer; + await tester.pump(const Duration(seconds: 24)); + await tester.pump(); + expect(conn.txTransmits, 1, + reason: 'the held TX goes out in place of the discovery'); + expect(conn.discoveryTransmits, 0, + reason: 'a discovery must not replace a held TX ping'); + expect(ping.bankedPing, isNull); + + // The alternation carries on: the TX's RX window closes and arms a + // discovery leg, which then goes out. + await tester.pump(const Duration(seconds: 6)); + expect(scheduled.last, discoveryLegWaitMs, + reason: 'the leg after the handed over TX is a discovery'); + gps.position = _pos(lat: 45.01); + await tester.pump(const Duration(seconds: 24)); + await tester.pump(); + expect(conn.discoveryTransmits, 1); + expect(conn.txTransmits, 1); + + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + cooldown.stop(); + ping.dispose(); + }); + } + + // A square can be covered for TX while still clear for discovery. The + // discovery lane asks about its own kind, and only a square clear for TX + // hands a Hybrid leg over to a banked TX. + + testWidgets('passive: a discovery goes out when only TX is covered', + (tester) async { + final gps = _FakeGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.clear, + tx: RecentCoverage.covered, discovery: RecentCoverage.clear); + final conn = _CountingConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final ping = _buildWith(gps, coverage, + discoveryWindowTimer: discoveryWindow, connection: conn); + + await ping.enableAutoPing(passiveMode: true); + await tester.pump(); + expect(conn.discoveryTransmits, 1); + expect(ping.bankedPing, isNull); + + await tester.pump(const Duration(seconds: 8)); + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + }); + + testWidgets( + 'hybrid: a discovery leg in a square covered for TX sends the ' + 'discovery and keeps the banked TX', (tester) async { + final gps = _SendingGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.covered); + final conn = _CountingConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final cooldown = CooldownTimer(); + final ping = _buildWith(gps, coverage, + discoveryWindowTimer: discoveryWindow, + cooldownTimer: cooldown, + connection: conn); + ping.getSessionId = () => 'YOW-20261012-0001'; + ping.getNextPingCounter = () => 1; + + // Discovery defers, then the TX leg defers and takes the slot. + await ping.enableAutoPing(hybridMode: true); + await tester.pump(const Duration(seconds: 24)); + expect(ping.bankedPing, BankedPingType.tx); + + // The next leg is a discovery, into a square still covered for TX but + // clear for discovery. + coverage + ..tx = RecentCoverage.covered + ..discovery = RecentCoverage.clear; + await tester.pump(const Duration(seconds: 24)); + await tester.pump(); + expect(conn.discoveryTransmits, 1); + expect(conn.txTransmits, 0); + expect(ping.bankedPing, BankedPingType.tx, + reason: 'the TX stays held for a square clear for TX'); + + await tester.pump(const Duration(seconds: 8)); + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + cooldown.stop(); + ping.dispose(); + }); + + testWidgets('hybrid: a discovery leg clear for TX still hands over to the ' + 'banked TX', (tester) async { + final gps = _SendingGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.covered); + final conn = _CountingConnection(); + final discoveryWindow = DiscoveryWindowTimer(); + final cooldown = CooldownTimer(); + final ping = _buildWith(gps, coverage, + discoveryWindowTimer: discoveryWindow, + cooldownTimer: cooldown, + connection: conn); + ping.getSessionId = () => 'YOW-20261012-0001'; + ping.getNextPingCounter = () => 1; + + await ping.enableAutoPing(hybridMode: true); + await tester.pump(const Duration(seconds: 24)); + expect(ping.bankedPing, BankedPingType.tx); + + coverage + ..tx = RecentCoverage.clear + ..discovery = RecentCoverage.clear; + await tester.pump(const Duration(seconds: 24)); + await tester.pump(); + expect(conn.txTransmits, 1); + expect(conn.discoveryTransmits, 0); + expect(ping.bankedPing, isNull); + + await tester.pump(const Duration(seconds: 6)); + await ping.forceDisableAutoPing(); + discoveryWindow.stop(); + cooldown.stop(); + ping.dispose(); + }); + + test('a banked discovery releases when discovery is no longer held', + () async { + final gps = _FakeGps()..position = _pos(); + final coverage = _Coverage(RecentCoverage.covered); + final ping = _buildWith(gps, coverage); + final fired = Completer(); + ping.onAutoPingScheduled = (_, __) { + if (!fired.isCompleted) fired.complete(); + }; + + await ping.enableAutoPing(passiveMode: true); + await fired.future.timeout(const Duration(seconds: 5)); + expect(ping.bankedPing, BankedPingType.discovery); + + coverage + ..discovery = RecentCoverage.clear + ..tx = RecentCoverage.covered; + expect(ping.maybeSendBankedPing(_pos()), isTrue); + expect(coverage.asked.last, BankedPingType.discovery); + + await Future.delayed(Duration.zero); + await ping.forceDisableAutoPing(); + }); + // Smart pinging reports each held ping through onPingDeferred so the // provider can queue a DEFER for the square. One call per deferral, with // the fix that was validated. diff --git a/test/services/ping_service_trace_fresh_fix_test.dart b/test/services/ping_service_trace_fresh_fix_test.dart index 784796dc..03e15868 100644 --- a/test/services/ping_service_trace_fresh_fix_test.dart +++ b/test/services/ping_service_trace_fresh_fix_test.dart @@ -8,6 +8,7 @@ import 'package:mesh_mapper/models/connection_state.dart'; import 'package:mesh_mapper/models/device_model.dart'; import 'package:mesh_mapper/services/api_queue_service.dart'; import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; import 'package:mesh_mapper/services/gps_service.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/ping_service.dart'; @@ -19,6 +20,9 @@ import 'package:mesh_mapper/services/wakelock_service.dart'; /// that reads the cached position would never be ended by the block. class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => const FixAltitude.unknown(); + Position? position; Position? fresh; int freshCalls = 0; diff --git a/test/services/ping_service_tx_lease_test.dart b/test/services/ping_service_tx_lease_test.dart new file mode 100644 index 00000000..d33ecbcc --- /dev/null +++ b/test/services/ping_service_tx_lease_test.dart @@ -0,0 +1,186 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/models/ping_data.dart'; +import 'package:mesh_mapper/services/api_queue_service.dart'; +import 'package:mesh_mapper/services/countdown_timer_service.dart'; +import 'package:mesh_mapper/services/fix_altitude.dart'; +import 'package:mesh_mapper/services/gps_service.dart'; +import 'package:mesh_mapper/services/meshcore/crypto_service.dart'; +import 'package:mesh_mapper/services/meshcore/packet_metadata.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/tx_tracker.dart'; +import 'package:mesh_mapper/services/ping_service.dart'; +import 'package:mesh_mapper/services/wakelock_service.dart'; + +import 'meshcore/scope_test_support.dart'; + +/// A TX that queues behind a scope lease must not spend its echo window +/// waiting. The real PingService, connection, lease and TxTracker run +/// together: the lease holds the write gate for 3.5 s, and an echo that +/// arrives 2 s after the TX actually went out must still count. + +class _FakeGps implements GpsService { + @override + FixAltitude fixAltitudeOf(Position position) => FixAltitude.known( + meters: 84.0, reference: AltitudeReference.msl, accuracy: 6.0); + + final Position position = Position( + latitude: 45.0, + longitude: -75.0, + timestamp: DateTime(2026), + accuracy: 5.0, + altitude: 0.0, + altitudeAccuracy: 1.0, + heading: 0.0, + headingAccuracy: 1.0, + speed: 0.0, + speedAccuracy: 1.0, + ); + + @override + GpsStatus get status => GpsStatus.locked; + + @override + Position? get lastPosition => position; + + @override + bool isAccuracyAcceptableForPing(Position position) => true; + + @override + bool get isAirborne => false; + + @override + void markPingPosition(Position position) {} + + @override + void markActivityPosition(Position position) {} + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnimplementedError('GpsService.${invocation.memberName}'); +} + +class _FakeApiQueue implements ApiQueueService { + final List txHeard = []; + final List<(double?, String?, double?)> txAltitude = []; + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #enqueueTx) { + txHeard.add(invocation.namedArguments[#heardRepeats] as String); + txAltitude.add(( + invocation.namedArguments[#altitude] as double?, + invocation.namedArguments[#altitudeRef] as String?, + invocation.namedArguments[#altitudeAccuracy] as double?, + )); + return Future.value(); + } + if (invocation.memberName.toString().contains('enqueue')) { + return Future.value(); + } + throw UnimplementedError('ApiQueueService.${invocation.memberName}'); + } +} + +class _FakeWakelock implements WakelockService { + @override + bool get isEnabled => false; + + @override + Future enable() async {} + + @override + Future disable() async {} + + @override + Future dispose() async {} +} + +/// A one-hop flood echo of [message] on the channel with [key], heard via +/// repeater 0x4E. +PacketMetadata _echo(String message, Uint8List key) { + final plain = Uint8List.fromList( + [0, 0, 0, 0, 0, ...utf8.encode(message)]); // timestamp, flags, text + final encrypted = CryptoService.encryptChannelMessage(plain, key); + const header = (PayloadType.grpTxt << PacketHeader.typeShift) | + RouteType.flood; + return PacketMetadata.fromLogRxData({ + 'raw': Uint8List.fromList([ + header, + 0x01, // one 1-byte hop + 0x4E, + CryptoService.computeChannelHash(key), + 0, 0, // MAC + ...encrypted, + ]), + 'lastSnr': 5.0, + 'lastRssi': -80, + }); +} + +void main() { + test('a TX parked behind a lease starts its echo window when it goes out', + () { + onScopeClock(PollingScopeRadio.new, (async, radio, conn) { + conn.connect((_) async => null); + async.elapse(const Duration(seconds: 5)); + expect(conn.wardrivingChannelKey, isNotNull); + + final tracker = TxTracker(); + final queue = _FakeApiQueue(); + final ping = PingService( + gpsService: _FakeGps(), + connection: conn, + apiQueue: queue, + wakelockService: _FakeWakelock(), + cooldownTimer: CooldownTimer(), + manualPingCooldownTimer: ManualPingCooldownTimer(), + rxWindowTimer: RxWindowTimer(), + discoveryWindowTimer: DiscoveryWindowTimer(), + deviceId: 'TEST', + txTracker: tracker, + )..getSessionId = () => 'PAR-20260611-0013'; + TxPing? recorded; + ping.onTxPing = (txPing) => recorded = txPing; + + final lease = grant(async, conn)!; + var sent = false; + ping.sendTxPing(manual: true).then((ok) => sent = ok); + async.elapse(const Duration(milliseconds: 3500)); + expect(radio.count(CommandCodes.sendChannelTxtMsg), 0, + reason: 'the TX is still parked behind the lease'); + + lease.release(); + async.flushMicrotasks(); + expect(radio.count(CommandCodes.sendChannelTxtMsg), 1); + final wentOut = clock.now(); + radio.emit([ResponseCodes.ok]); + async.flushMicrotasks(); + expect(sent, isTrue); + expect(recorded?.timestamp, wentOut, + reason: 'the ping is recorded at the moment it went out'); + + async.elapse(const Duration(seconds: 2)); + expect(tracker.isListening, isTrue, + reason: 'the echo window runs from the send, not from the wait'); + TxEchoResult? result; + tracker + .handlePacket(_echo(tracker.sentPayload!, conn.wardrivingChannelKey!)) + .then((r) => result = r); + async.flushMicrotasks(); + expect(result, TxEchoResult.directEcho); + expect(recorded!.heardRepeaters.single.repeaterId, '4E'); + + async.elapse(const Duration(seconds: 4)); + expect(queue.txHeard, ['4E(5.00)']); + expect(queue.txAltitude, [(84.0, 'msl', 6.0)], + reason: 'the labelled altitude rides the TX enqueue'); + ping.dispose(); + }); + }); +} diff --git a/test/services/precise_location_gate_test.dart b/test/services/precise_location_gate_test.dart new file mode 100644 index 00000000..2c5b71b2 --- /dev/null +++ b/test/services/precise_location_gate_test.dart @@ -0,0 +1,261 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/services/precise_location_gate.dart'; + +/// The Precise Location check made at Connect. The server refuses every fix +/// worse than 50 m, so a phone on approximate location maps nothing. +void main() { + group('decidePreciseLocationStep', () { + PreciseLocationStep decide({ + PreciseLocationPlatform platform = PreciseLocationPlatform.ios, + bool simulatorEnabled = false, + bool locationGranted = true, + LocationAccuracyStatus? accuracy = LocationAccuracyStatus.precise, + bool alreadyAsked = false, + bool canPrompt = true, + }) => + decidePreciseLocationStep( + platform: platform, + simulatorEnabled: simulatorEnabled, + locationGranted: locationGranted, + accuracy: accuracy, + alreadyAsked: alreadyAsked, + canPrompt: canPrompt, + ); + + test('precise location connects', () { + expect(decide(), PreciseLocationStep.connect); + expect(decide(platform: PreciseLocationPlatform.android), + PreciseLocationStep.connect); + }); + + test('reduced on iOS asks for temporary full accuracy', () { + expect(decide(accuracy: LocationAccuracyStatus.reduced), + PreciseLocationStep.askTemporaryFullAccuracy); + }); + + test('still reduced after asking blocks the connect', () { + expect( + decide(accuracy: LocationAccuracyStatus.reduced, alreadyAsked: true), + PreciseLocationStep.block); + }); + + test('reduced on Android re-requests fine location once', () { + expect( + decide( + platform: PreciseLocationPlatform.android, + accuracy: LocationAccuracyStatus.reduced, + ), + PreciseLocationStep.requestFineLocation); + }); + + test('reduced on Android after the re-request blocks', () { + expect( + decide( + platform: PreciseLocationPlatform.android, + accuracy: LocationAccuracyStatus.reduced, + alreadyAsked: true, + ), + PreciseLocationStep.block); + }); + + test('reduced with no way to prompt blocks without asking', () { + expect(decide(accuracy: LocationAccuracyStatus.reduced, canPrompt: false), + PreciseLocationStep.block); + expect( + decide( + platform: PreciseLocationPlatform.android, + accuracy: LocationAccuracyStatus.reduced, + canPrompt: false, + ), + PreciseLocationStep.block); + }); + + test('web skips the check', () { + expect( + decide( + platform: PreciseLocationPlatform.web, + accuracy: LocationAccuracyStatus.reduced, + ), + PreciseLocationStep.skip); + }); + + test('the GPS simulator skips the check', () { + expect( + decide( + simulatorEnabled: true, + accuracy: LocationAccuracyStatus.reduced, + ), + PreciseLocationStep.skip); + }); + + test('location not granted is left to the existing denied path', () { + expect( + decide( + locationGranted: false, + accuracy: LocationAccuracyStatus.reduced, + ), + PreciseLocationStep.skip); + }); + + test('an unreadable accuracy fails open', () { + expect(decide(accuracy: null), PreciseLocationStep.connect); + expect(decide(accuracy: LocationAccuracyStatus.unknown), + PreciseLocationStep.connect); + }); + }); + + group('PreciseLocationGate', () { + group('isApproximateOnly', () { + PreciseLocationGate gate({ + bool granted = true, + LocationAccuracyStatus accuracy = LocationAccuracyStatus.reduced, + bool readThrows = false, + }) => + PreciseLocationGate( + checkGranted: () async => granted, + readAccuracy: () async => + readThrows ? throw Exception('no plugin') : accuracy, + ); + + Future check(PreciseLocationGate g, + {PreciseLocationPlatform platform = + PreciseLocationPlatform.android, + bool simulator = false}) => + g.isApproximateOnly(platform: platform, simulatorEnabled: simulator); + + test('true for granted, reduced accuracy', () async { + expect(await check(gate()), isTrue); + expect( + await check(gate(), platform: PreciseLocationPlatform.ios), isTrue); + }); + + test('false for precise, not granted, or a failed read', () async { + expect(await check(gate(accuracy: LocationAccuracyStatus.precise)), + isFalse); + expect(await check(gate(granted: false)), isFalse); + expect(await check(gate(readThrows: true)), isFalse); + }); + + test('false on web and with the GPS simulator', () async { + expect(await check(gate(), platform: PreciseLocationPlatform.web), + isFalse); + expect(await check(gate(), simulator: true), isFalse); + }); + }); + + test('iOS: allowed after the temporary full accuracy prompt', () async { + var asks = 0; + final gate = PreciseLocationGate( + checkGranted: () async => true, + readAccuracy: () async => LocationAccuracyStatus.reduced, + requestTemporaryFullAccuracy: () async { + asks++; + return LocationAccuracyStatus.precise; + }, + ); + final allowed = await gate.allowsConnect( + platform: PreciseLocationPlatform.ios, + simulatorEnabled: false, + canPrompt: true, + entry: 'BLE', + ); + expect(allowed, isTrue); + expect(asks, 1); + }); + + test('iOS: declined prompt blocks, asking only once', () async { + var asks = 0; + final gate = PreciseLocationGate( + checkGranted: () async => true, + readAccuracy: () async => LocationAccuracyStatus.reduced, + requestTemporaryFullAccuracy: () async { + asks++; + return LocationAccuracyStatus.reduced; + }, + ); + final allowed = await gate.allowsConnect( + platform: PreciseLocationPlatform.ios, + simulatorEnabled: false, + canPrompt: true, + entry: 'BLE', + ); + expect(allowed, isFalse); + expect(asks, 1); + }); + + test('iOS: a failing prompt counts as declined', () async { + final gate = PreciseLocationGate( + checkGranted: () async => true, + readAccuracy: () async => LocationAccuracyStatus.reduced, + requestTemporaryFullAccuracy: () async => + throw Exception('purpose key missing'), + ); + expect( + await gate.allowsConnect( + platform: PreciseLocationPlatform.ios, + simulatorEnabled: false, + canPrompt: true, + entry: 'BLE', + ), + isFalse); + }); + + test('Android: allowed when the fine re-request upgrades it', () async { + var accuracy = LocationAccuracyStatus.reduced; + var requests = 0; + final gate = PreciseLocationGate( + checkGranted: () async => true, + readAccuracy: () async => accuracy, + requestTemporaryFullAccuracy: () async => + fail('iOS prompt used on Android'), + ); + final allowed = await gate.allowsConnect( + platform: PreciseLocationPlatform.android, + simulatorEnabled: false, + canPrompt: true, + requestFineLocation: () async { + requests++; + accuracy = LocationAccuracyStatus.precise; + return true; + }, + entry: 'TCP', + ); + expect(allowed, isTrue); + expect(requests, 1); + }); + + test('Android: no re-request available blocks', () async { + final gate = PreciseLocationGate( + checkGranted: () async => true, + readAccuracy: () async => LocationAccuracyStatus.reduced, + requestTemporaryFullAccuracy: () async => + fail('iOS prompt used on Android'), + ); + expect( + await gate.allowsConnect( + platform: PreciseLocationPlatform.android, + simulatorEnabled: false, + canPrompt: true, + entry: 'USB', + ), + isFalse); + }); + + test('web never reads the platform', () async { + final gate = PreciseLocationGate( + checkGranted: () async => fail('permission read on web'), + readAccuracy: () async => fail('accuracy read on web'), + requestTemporaryFullAccuracy: () async => fail('prompt on web'), + ); + expect( + await gate.allowsConnect( + platform: PreciseLocationPlatform.web, + simulatorEnabled: false, + canPrompt: true, + entry: 'BLE', + ), + isTrue); + }); + }); +} diff --git a/test/services/recent_coverage_service_test.dart b/test/services/recent_coverage_service_test.dart index 100c35dd..91c4c1ca 100644 --- a/test/services/recent_coverage_service_test.dart +++ b/test/services/recent_coverage_service_test.dart @@ -151,16 +151,16 @@ void main() { ((la / 0.0027).floor(), (lo / 0.00384).floor()); test('unknown before any tile has loaded', () { - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); }); test('covered when the tile lists the cell, clear otherwise', () async { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); expect(svc.loadedTileCount, 1); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); // A different cell in the same tile. - expect(svc.isCovered(lat + 0.003, lon), RecentCoverage.clear); + expect(svc.isCovered(lat + 0.003, lon, forTx: true), RecentCoverage.clear); expect(fetches.calls.single.gsize, 300); expect(fetches.calls.single.days, 14); expect(fetches.calls.single.zone, 'YOW'); @@ -169,14 +169,14 @@ void main() { test('a 204 (empty body) is a loaded, empty tile', () async { fetches.answers['2373/2933'] = Uint8List(0); await svc.onPosition(lat, lon); - expect(svc.isCovered(lat, lon), RecentCoverage.clear); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.clear); }); test('a failed fetch stays unknown and retries after 30 s, not before', () async { fetches.answers['2373/2933'] = null; await svc.onPosition(lat, lon); - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); expect(fetches.calls.length, 1); now = now.add(const Duration(seconds: 10)); @@ -187,7 +187,7 @@ void main() { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); expect(fetches.calls.length, 2); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); }); test('a throwing fetch is a failed fetch, not a rejected future', () async { @@ -195,7 +195,7 @@ void main() { // An unhandled throw here fails the test: onPosition runs off the GPS // listener and must never reject. await svc.onPosition(lat, lon); - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); expect(fetches.calls.length, 1); now = now.add(const Duration(seconds: 10)); @@ -206,7 +206,7 @@ void main() { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); expect(fetches.calls.length, 2); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); }); test('a throwing refresh keeps the old set', () async { @@ -216,7 +216,7 @@ void main() { fetches.throwNext = StateError('the fetch blew up'); await svc.onPosition(lat + 0.002, lon); expect(fetches.calls.length, 2); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); }); test('a failed refresh keeps the old set', () async { @@ -226,7 +226,7 @@ void main() { fetches.answers['2373/2933'] = null; await svc.onPosition(lat + 0.002, lon); expect(fetches.calls.length, 2); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); }); test('a fresh tile is reused; a 5 minute old one is refetched', () async { @@ -277,13 +277,84 @@ void main() { statuses: [1, 5]); await svc.onPosition(lat, lon); expect(svc.loadedTileCount, 0); - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); }); test('a session mark is covered at once, even with no tile', () { - svc.markCovered(lat, lon); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); - expect(svc.isCovered(lat + 0.01, lon), RecentCoverage.unknown); + svc.markCovered(lat, lon, CoverageColor.green); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + expect(svc.isCovered(lat + 0.01, lon, forTx: true), RecentCoverage.unknown); + }); + + group('flood only', () { + void floodOnly(bool on) => svc.configure( + zone: 'YOW', gridSize: 300, days: 14, enabled: true, floodOnly: on); + + Future loadGreenAndCyan() async { + fetches.answers['2373/2933'] = tileWithCells( + [cellOf(lat, lon), cellOf(lat + 0.003, lon)], + statuses: [1, 2]); + await svc.onPosition(lat, lon); + } + + test('all pings: green and cyan cells hold both kinds', () async { + floodOnly(false); + await loadGreenAndCyan(); + for (final la in [lat, lat + 0.003]) { + expect(svc.isCovered(la, lon, forTx: true), RecentCoverage.covered); + expect(svc.isCovered(la, lon, forTx: false), RecentCoverage.covered); + } + }); + + test('a green cell holds TX, never discovery', () async { + floodOnly(true); + await loadGreenAndCyan(); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + expect(svc.isCovered(lat, lon, forTx: false), RecentCoverage.clear); + }); + + test('a cyan cell holds nothing', () async { + floodOnly(true); + await loadGreenAndCyan(); + expect(svc.isCovered(lat + 0.003, lon, forTx: true), + RecentCoverage.clear); + expect(svc.isCovered(lat + 0.003, lon, forTx: false), + RecentCoverage.clear); + }); + + test('discovery is clear even before a tile loads', () { + floodOnly(true); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: false), RecentCoverage.clear); + }); + + test('a cyan session mark does not hold TX, a green one does', () { + floodOnly(true); + svc.markCovered(lat, lon, CoverageColor.cyan); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); + svc.markCovered(lat, lon, CoverageColor.green); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + }); + + test('a green session mark is not downgraded by a later cyan mark', () { + floodOnly(true); + svc.markCovered(lat, lon, CoverageColor.green); + svc.markCovered(lat, lon, CoverageColor.cyan); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + }); + + test('switching flood only keeps loaded tiles', () async { + floodOnly(false); + await loadGreenAndCyan(); + expect(svc.loadedTileCount, 1); + final fetched = fetches.calls.length; + floodOnly(true); + expect(svc.floodOnly, isTrue); + expect(svc.loadedTileCount, 1); + await svc.onPosition(lat + 0.002, lon); + expect(fetches.calls.length, fetched); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + }); }); test('follows the 100 m grid when configured for it', () async { @@ -292,18 +363,19 @@ void main() { fetches.answers['2373/2933'] = tileWithCells([c]); await svc.onPosition(lat, lon); expect(fetches.calls.single.gsize, 100); - expect(svc.isCovered(lat, lon), RecentCoverage.covered); - expect(svc.isCovered(lat + 0.001, lon), RecentCoverage.clear); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered); + expect(svc.isCovered(lat + 0.001, lon, forTx: true), RecentCoverage.clear); }); test('reconfiguring the window or grid clears the cache', () async { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); - svc.markCovered(lat + 0.01, lon); + svc.markCovered(lat + 0.01, lon, CoverageColor.green); svc.configure(zone: 'YOW', gridSize: 300, days: 7, enabled: true); expect(svc.loadedTileCount, 0); - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); - expect(svc.isCovered(lat + 0.01, lon), RecentCoverage.unknown, + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); + expect(svc.isCovered(lat + 0.01, lon, forTx: true), + RecentCoverage.unknown, reason: 'session marks belong to the old configuration'); }); @@ -317,7 +389,7 @@ void main() { test('a radio preset change clears the cache', () async { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); - svc.markCovered(lat + 0.01, lon); + svc.markCovered(lat + 0.01, lon, CoverageColor.green); expect(svc.loadedTileCount, 1); svc.configure( zone: 'YOW', @@ -327,7 +399,8 @@ void main() { radioKey: '906.875,250,10'); expect(svc.loadedTileCount, 0, reason: 'tiles fetched under the old preset answer for the wrong layer'); - expect(svc.isCovered(lat + 0.01, lon), RecentCoverage.unknown, + expect(svc.isCovered(lat + 0.01, lon, forTx: true), + RecentCoverage.unknown, reason: 'session marks belong to the old preset'); }); @@ -354,7 +427,7 @@ void main() { svc.configure(zone: 'YOW', gridSize: 300, days: 14, enabled: false); await svc.onPosition(lat, lon); expect(svc.isActive, isFalse); - expect(svc.isCovered(lat, lon), RecentCoverage.clear); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.clear); svc.configure(zone: null, gridSize: 300, days: 14, enabled: true); await svc.onPosition(lat, lon); expect(svc.isActive, isFalse); @@ -364,10 +437,10 @@ void main() { test('clear drops everything', () async { fetches.answers['2373/2933'] = tileWithCells([cellOf(lat, lon)]); await svc.onPosition(lat, lon); - svc.markCovered(lat, lon); + svc.markCovered(lat, lon, CoverageColor.green); svc.clear(); expect(svc.loadedTileCount, 0); - expect(svc.isCovered(lat, lon), RecentCoverage.unknown); + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.unknown); }); group('deferral dedupe', () { @@ -414,11 +487,11 @@ void main() { }); test('clearDeferred empties only the deferred set', () { - svc.markCovered(lat, lon); + svc.markCovered(lat, lon, CoverageColor.green); expect(svc.markDeferred(lat, lon), isTrue); svc.clearDeferred(); expect(svc.markDeferred(lat, lon), isTrue); - expect(svc.isCovered(lat, lon), RecentCoverage.covered, + expect(svc.isCovered(lat, lon, forTx: true), RecentCoverage.covered, reason: 'the session mark is untouched'); }); diff --git a/test/services/reconnect_flap_guard_test.dart b/test/services/reconnect_flap_guard_test.dart new file mode 100644 index 00000000..8f4417d9 --- /dev/null +++ b/test/services/reconnect_flap_guard_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/reconnect_flap_guard.dart'; + +/// A radio that reconnects and then drops again within seconds must not loop +/// forever. One log showed about 140 reconnect cycles with no alert, because +/// every drop started a fresh 30 s budget and every success cleared it. + +void main() { + final t0 = DateTime(2026, 11, 8, 12); + DateTime at(int s) => t0.add(Duration(seconds: s)); + + test('three quick drops after reconnects in a row give up', () { + final guard = ReconnectFlapGuard(); + // The first drop follows a manual connect, not a reconnect. + expect(guard.onDrop(at(0)), isFalse); + guard.onReconnectSuccess(at(5)); + expect(guard.onDrop(at(10)), isFalse); + guard.onReconnectSuccess(at(15)); + expect(guard.onDrop(at(20)), isFalse); + guard.onReconnectSuccess(at(25)); + expect(guard.onDrop(at(30)), isTrue); + }); + + test('a connection that stays up past the window resets the count', () { + final guard = ReconnectFlapGuard(); + guard.onReconnectSuccess(at(0)); + expect(guard.onDrop(at(5)), isFalse); + guard.onReconnectSuccess(at(10)); + expect(guard.onDrop(at(15)), isFalse); + guard.onReconnectSuccess(at(20)); + // Up for 31 s: a healthy link that later dropped. + expect(guard.onDrop(at(51)), isFalse); + expect(guard.flaps, 0); + guard.onReconnectSuccess(at(55)); + expect(guard.onDrop(at(60)), isFalse); + guard.onReconnectSuccess(at(65)); + expect(guard.onDrop(at(70)), isFalse); + }); + + test('the window boundary counts as quick', () { + final guard = ReconnectFlapGuard(); + for (var i = 0; i < 2; i++) { + guard.onReconnectSuccess(at(i * 100)); + expect(guard.onDrop(at(i * 100 + 30)), isFalse); + } + guard.onReconnectSuccess(at(300)); + expect(guard.onDrop(at(330)), isTrue); + }); + + test('a drop with no reconnect before it does not count', () { + final guard = ReconnectFlapGuard(); + guard.onReconnectSuccess(at(0)); + expect(guard.onDrop(at(5)), isFalse); + guard.onReconnectSuccess(at(10)); + expect(guard.onDrop(at(15)), isFalse); + // A manual connect after the abandon: the next drop starts over. + guard.reset(); + expect(guard.onDrop(at(20)), isFalse); + expect(guard.flaps, 0); + }); +} diff --git a/test/services/repeater_admin/manage_target_test.dart b/test/services/repeater_admin/manage_target_test.dart index 043b0f6a..44119d5d 100644 --- a/test/services/repeater_admin/manage_target_test.dart +++ b/test/services/repeater_admin/manage_target_test.dart @@ -37,7 +37,7 @@ void main() { group('manageBlockReason', () { String? reason({bool connected = true, bool mode = false, bool inProgress = false, bool sending = false, bool admin = false, bool reconnecting = false, - bool firmwareOk = true}) => + bool firmwareOk = true, bool scopeBusy = false}) => manageBlockReason( isConnected: connected, isAnyModeRunning: mode, @@ -45,7 +45,11 @@ void main() { isPingSending: sending, isRepeaterAdminActive: admin, isAutoReconnecting: reconnecting, - companionFirmwareSupported: firmwareOk); + companionFirmwareSupported: firmwareOk, + scopeRadioBusy: scopeBusy); + + bool busy({bool lease = false, bool debt = false}) => + scopeRadioBusy(isScopeLeaseActive: lease, hasScopeReplyDebt: debt); test('allowed', () => expect(reason(), isNull)); test('not connected', () => expect(reason(connected: false), 'Connect a radio to manage this repeater')); @@ -59,6 +63,13 @@ void main() { expect(reason(reconnecting: true), 'Connect a radio to manage this repeater')); test('connection outranks the mode', () => expect(reason(connected: false, mode: true), 'Connect a radio to manage this repeater')); + test('a scope lease held, or only its reply debt left: wait', () { + const wait = 'Finishing a scope request. Try again in a few seconds.'; + expect(reason(scopeBusy: busy(lease: true)), wait); + expect(reason(scopeBusy: busy(debt: true)), wait); + expect(reason(scopeBusy: busy(lease: true, debt: true)), wait); + expect(reason(scopeBusy: busy()), isNull); + }); test('old companion firmware, once connected', () { expect(reason(firmwareOk: false), 'Update companion firmware to use Manage'); expect(reason(connected: false, firmwareOk: false), 'Connect a radio to manage this repeater'); diff --git a/test/services/repeater_admin/repeater_admin_session_test.dart b/test/services/repeater_admin/repeater_admin_session_test.dart index cc48d9f5..e71bf79f 100644 --- a/test/services/repeater_admin/repeater_admin_session_test.dart +++ b/test/services/repeater_admin/repeater_admin_session_test.dart @@ -1,9 +1,12 @@ +import 'dart:async'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:mesh_mapper/services/meshcore/buffer_utils.dart'; import 'package:mesh_mapper/services/meshcore/connection.dart'; import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; +import 'package:mesh_mapper/services/repeater_admin/manage_target.dart'; import 'package:mesh_mapper/services/repeater_admin/repeater_admin_models.dart'; import 'package:mesh_mapper/services/repeater_admin/repeater_admin_session.dart'; @@ -189,6 +192,22 @@ void main() { expect(session.busy, isFalse); }); + test('a contact list that never finishes is not a password problem', + () async { + final future = session.login('admin-pw'); + await transport.settle(); + expect(commands(), [CommandCodes.getContacts]); + transport.emit([ResponseCodes.contactsStart, 2, 0, 0, 0]); + transport.emit([ResponseCodes.contact, ...contactPayload(otherKey)]); + // The radio goes quiet before END_OF_CONTACTS: the silence window + // (5 s by default) runs out and no login is ever sent. + expect(await future, isFalse); + expect(session.state, RepeaterAdminState.failed); + expect(session.lastError, kContactListTimeoutSentence); + expect(commands(), [CommandCodes.getContacts]); + expect(session.busy, isFalse); + }, timeout: const Timeout(Duration(seconds: 15))); + test('a zero-hop contact reads as a direct route', () async { final future = session.login('admin-pw'); await answerContacts([contactPayload(repeaterKey, outPathLen: 0x80)]); @@ -392,6 +411,41 @@ void main() { expect(await retry, isTrue); }); + test('a scope lease, then its reply debt, refuse a command', () async { + final lease = await connection.acquireScopeLease( + admissionWait: const Duration(seconds: 1), + cancel: ScopeCancelToken()); + expect(lease, isNotNull); + final before = transport.writes.length; + expect(await session.login('admin-pw'), isFalse); + expect(session.lastError, kScopeRadioBusyHint); + // A command the lease wrote, still owed its reply after the lease + // ends. + unawaited(lease!.restore(ContactRecord.parse(BufferReader( + Uint8List.fromList(contactPayload(repeaterKey)))))); + await transport.settle(); + await lease.release(); + expect(connection.hasScopeReplyDebt, isTrue); + final owed = transport.writes.length; + expect(await session.login('admin-pw'), isFalse); + expect(session.lastError, kScopeRadioBusyHint); + expect(transport.writes.length, owed); + expect(owed, before + 1); + + // Once that reply lands the radio is Manage's again. + transport.emit([ResponseCodes.ok]); + await transport.settle(); + expect(connection.isScopeRadioBusy, isFalse); + }); + + test('reply debt from ordinary traffic is not a scope request', () async { + await connection.debugWriteRaw( + Uint8List.fromList([CommandCodes.getContactByKey, ...repeaterKey])); + expect(connection.repliesOwedCount, 1); + expect(connection.hasScopeReplyDebt, isFalse); + expect(connection.isScopeRadioBusy, isFalse); + }); + test('PATH_UPDATED re-reads the contact', () async { await loginAsAdmin(); final writes = transport.writes.length; diff --git a/test/services/scope_discovery/scope_discovery_rules_test.dart b/test/services/scope_discovery/scope_discovery_rules_test.dart new file mode 100644 index 00000000..4c5189a7 --- /dev/null +++ b/test/services/scope_discovery/scope_discovery_rules_test.dart @@ -0,0 +1,679 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_discovery_rules.dart'; + +void main() { + final keyA = 'AB' * 32; + final keyB = 'CD' * 32; + + group('isScopeQueryDue', () { + const days = 14; + const refreshSec = days * 86400; + const now = 2000000000; + + test('persistPending true is never due, even when both rules pass', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: null, + persistPending: true, + nowSec: now, + refreshDays: days, + ); + expect(due, isFalse); + }); + + test('server fresh, phone fresh: not due', () { + final due = isScopeQueryDue( + onServerList: true, + serverCheckedAt: now - 10, + phone: const ScopeCacheEntry(answeredAt: now - 10), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isFalse); + }); + + test('server stale (Rule 1 true), phone stale (Rule 2 true): due', () { + final due = isScopeQueryDue( + onServerList: true, + serverCheckedAt: now - refreshSec - 1, + phone: const ScopeCacheEntry(answeredAt: now - refreshSec - 1), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isTrue); + }); + + test('server never checked (null): Rule 1 true regardless of phone', () { + final due = isScopeQueryDue( + onServerList: true, + serverCheckedAt: null, + phone: const ScopeCacheEntry(answeredAt: now - refreshSec - 1), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isTrue); + }); + + test('not on the server list at all: Rule 1 true regardless of serverCheckedAt', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: now - 10, + phone: const ScopeCacheEntry(answeredAt: now - refreshSec - 1), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isTrue); + }); + + test('server stale but phone answered fresh: Rule 2 blocks, not due', () { + final due = isScopeQueryDue( + onServerList: true, + serverCheckedAt: now - refreshSec - 1, + phone: const ScopeCacheEntry(answeredAt: now - 10), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isFalse); + }); + + test('server fresh but phone has no answer: Rule 1 blocks, not due', () { + final due = isScopeQueryDue( + onServerList: true, + serverCheckedAt: now - 10, + phone: null, + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isFalse); + }); + + test('a non-answer leaves no phone entry, so it is due again at once ' + '(so long as the server rule also agrees)', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: const ScopeCacheEntry(answeredAt: null), + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isTrue); + }); + + test('interval 7 vs 14 both honoured on the boundary', () { + const answeredAt = now - 8 * 86400; // 8 days ago + final dueAt7 = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: const ScopeCacheEntry(answeredAt: answeredAt), + persistPending: false, + nowSec: now, + refreshDays: 7, + ); + final dueAt14 = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: const ScopeCacheEntry(answeredAt: answeredAt), + persistPending: false, + nowSec: now, + refreshDays: 14, + ); + expect(dueAt7, isTrue, reason: '8 days >= 7 day interval'); + expect(dueAt14, isFalse, reason: '8 days < 14 day interval'); + }); + + test('heldUntil in the future: not due, even when both rules pass', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: null, + persistPending: false, + nowSec: now, + refreshDays: days, + heldUntil: now + 1, + ); + expect(due, isFalse); + }); + + test('heldUntil exactly now: due (the hold has just expired)', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: null, + persistPending: false, + nowSec: now, + refreshDays: days, + heldUntil: now, + ); + expect(due, isTrue); + }); + + test('heldUntil in the past: due, same as no hold at all', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: null, + persistPending: false, + nowSec: now, + refreshDays: days, + heldUntil: now - 1, + ); + expect(due, isTrue); + }); + + test('heldUntil null: unaffected (no hold at all)', () { + final due = isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: null, + persistPending: false, + nowSec: now, + refreshDays: days, + ); + expect(due, isTrue); + }); + }); + + group('ScopeQueryCache', () { + const now = 2000000000; + + test('round trip keeps the answer stamp', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer(keyA, now); + final restored = ScopeQueryCache.fromJson(cache.toJson()); + expect(restored[keyA]?.answeredAt, now); + }); + + test('operator[] and recordAnswer normalize the key (lower case, prefix)', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer(keyA.toLowerCase(), now); + expect(cache[keyA]?.answeredAt, now); + expect(cache['0x$keyA']?.answeredAt, now); + }); + + test('an unrecognized key never lands in the cache', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer('not-a-key', now); + expect(cache.toJson(), isEmpty); + expect(cache['not-a-key'], isNull); + }); + + test('a repeater never recorded has no entry (due again at once)', () { + final cache = ScopeQueryCache.fromJson(null); + expect(cache[keyA], isNull); + }); + + test('fromJson tolerates junk: non-map root, bad key, bad value', () { + expect(ScopeQueryCache.fromJson(null).toJson(), isEmpty); + final cache = ScopeQueryCache.fromJson({ + 'not-a-key': {'answeredAt': now}, + keyA: 'not-a-map', + keyB: {'answeredAt': 'not-an-int'}, + }); + expect(cache.toJson(), isEmpty); + }); + + test('pendingPersist is memory-only and does not survive a round trip', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer(keyA, now); + cache.pendingPersist.add(keyA); + final json = cache.toJson(); + expect(json.values.any((v) => v.toString().contains('pendingPersist')), + isFalse); + final restored = ScopeQueryCache.fromJson(json); + expect(restored.pendingPersist, isEmpty); + // The stamp itself did survive; only the in-flight marker did not. + expect(restored[keyA]?.answeredAt, now); + }); + + test('prune keeps a 500-day-old answer under a 1000-day interval', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer(keyA, now - 500 * 86400); + cache.prune(nowSec: now, refreshDays: 1000); + expect(cache[keyA], isNotNull); + }); + + test('prune drops that same answer under a 400-day interval', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordAnswer(keyA, now - 500 * 86400); + cache.prune(nowSec: now, refreshDays: 400); + expect(cache[keyA], isNull); + }); + + test('prune under cache pressure evicts exactly the oldest answer', () { + final cache = ScopeQueryCache.fromJson(null); + // 20001 entries, none stale under the interval used below, spaced one + // second apart so there is exactly one oldest. + for (var i = 0; i < ScopeQueryCache.maxEntries + 1; i++) { + final key = i.toRadixString(16).padLeft(64, '0').toUpperCase(); + cache.recordAnswer(key, now - i); + } + final oldestKey = + ScopeQueryCache.maxEntries.toRadixString(16).padLeft(64, '0').toUpperCase(); + expect(cache[oldestKey], isNotNull); + cache.prune(nowSec: now, refreshDays: 36500); // interval keeps all + expect(cache.toJson().length, ScopeQueryCache.maxEntries); + expect(cache[oldestKey], isNull, reason: 'the single oldest answer is evicted'); + }); + + test('a repeater that has never missed has no hold', () { + final cache = ScopeQueryCache.fromJson(null); + expect(cache.heldUntil(keyA), isNull); + }); + + test('recordNoAnswer holds for 1 minute on the first miss', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + expect(cache.heldUntil(keyA), now + 60); + }); + + test('consecutive misses hold for 1, 5, 10, 20, then 30 minutes', () { + final cache = ScopeQueryCache.fromJson(null); + const expected = [1, 5, 10, 20, 30, 30, 30]; + for (var i = 0; i < expected.length; i++) { + cache.recordNoAnswer(keyA, now + i); + expect(cache.heldUntil(keyA), now + i + expected[i] * 60, + reason: 'miss #${i + 1}'); + } + }); + + test('after a miss, a retry needs a stronger signal until 30 minutes ' + 'have passed', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now, rssi: -100); + bool weak(int t, int rssi) => + cache.awaitingStrongerSignal(keyA, nowSec: t, rssi: rssi); + expect(weak(now + 60, -100), isTrue, reason: 'same signal'); + expect(weak(now + 60, -101), isTrue, reason: 'weaker'); + expect(weak(now + 60, -99), isFalse, reason: '1 dB stronger'); + expect(weak(now + 30 * 60 - 1, -100), isTrue); + expect(weak(now + 30 * 60, -100), isFalse, + reason: '30 minutes after the miss the rule lapses'); + }); + + test('the signal rule tracks the latest miss', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now, rssi: -100); + cache.recordNoAnswer(keyA, now + 60, rssi: -90); + expect(cache.awaitingStrongerSignal(keyA, nowSec: now + 400, rssi: -90), + isTrue, + reason: 'measured against -90, the latest miss'); + expect(cache.awaitingStrongerSignal(keyA, nowSec: now + 400, rssi: -89), + isFalse); + }); + + test('no signal rule without a miss RSSI, a hold, or after an answer', + () { + final cache = ScopeQueryCache.fromJson(null); + expect(cache.awaitingStrongerSignal(keyA, nowSec: now, rssi: -100), + isFalse, reason: 'never missed'); + cache.recordNoAnswer(keyA, now); + expect(cache.awaitingStrongerSignal(keyA, nowSec: now + 60, rssi: -100), + isFalse, reason: 'the miss carried no RSSI'); + cache.recordNoAnswer(keyA, now, rssi: -100); + cache.clearHold(keyA); + expect(cache.awaitingStrongerSignal(keyA, nowSec: now + 60, rssi: -100), + isFalse, reason: 'an answer cleared the hold'); + }); + + test('an answer clears the hold and resets the miss count', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + cache.recordNoAnswer(keyA, now + 1); + expect(cache.heldUntil(keyA), isNotNull); + cache.recordAnswer(keyA, now + 2); + expect(cache.heldUntil(keyA), isNull); + // The miss count reset too: the next miss holds for the first step's + // 1 minute again, not the third step's 10. + cache.recordNoAnswer(keyA, now + 3); + expect(cache.heldUntil(keyA), now + 3 + 60); + }); + + test('recordNoAnswer on an unrecognized key is a no-op', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer('not-a-key', now); + expect(cache.toJson(), isEmpty); + expect(cache.heldUntil('not-a-key'), isNull); + }); + + test('a hold does not survive a cache reload (memory only)', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + expect(cache.heldUntil(keyA), isNotNull); + final reloaded = ScopeQueryCache.fromJson(cache.toJson()); + expect(reloaded.heldUntil(keyA), isNull); + }); + + test('clearHold clears an existing hold without touching the answer ' + 'stamp', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + cache.recordNoAnswer(keyA, now + 1); + expect(cache.heldUntil(keyA), isNotNull); + cache.clearHold(keyA); + expect(cache.heldUntil(keyA), isNull); + // No answer stamp was ever recorded (a real answer that failed to + // persist does not get a durable stamp), and clearHold must not + // invent one. + expect(cache[keyA], isNull); + }); + + test('clearHold resets the miss count too: the next miss is the first ' + 'step again', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + cache.recordNoAnswer(keyA, now + 1); + cache.clearHold(keyA); + cache.recordNoAnswer(keyA, now + 2); + expect(cache.heldUntil(keyA), now + 2 + 60); + }); + + test('clearHold on a key with no hold is a no-op', () { + final cache = ScopeQueryCache.fromJson(null); + cache.clearHold(keyA); + expect(cache.heldUntil(keyA), isNull); + }); + + test('clearHold on an unrecognized key is a no-op', () { + final cache = ScopeQueryCache.fromJson(null); + cache.recordNoAnswer(keyA, now); + cache.clearHold('not-a-key'); + expect(cache.heldUntil(keyA), isNotNull, + reason: 'an unrecognized key must not touch keyA'); + }); + }); + + group('ScopeHourlyBudget', () { + const hour = 555; + const now = hour * 3600 + 100; + + Future noopSave(Map json) async {} + + test('allows 60 in one device-hour and refuses the 61st', () { + final budget = ScopeHourlyBudget(save: noopSave); + for (var i = 0; i < 60; i++) { + expect(budget.tryConsume(keyA, now), isTrue, reason: 'ask $i'); + } + expect(budget.tryConsume(keyA, now), isFalse); + expect(budget.canAsk(keyA, now), isFalse); + }); + + test('a new hour starts fresh', () { + final budget = ScopeHourlyBudget(save: noopSave); + for (var i = 0; i < 60; i++) { + budget.tryConsume(keyA, now); + } + expect(budget.tryConsume(keyA, now + 3600), isTrue); + }); + + test('the same device is still capped under a new session id ' + '(deviceKey is the radio key, not the session)', () { + final budget = ScopeHourlyBudget(save: noopSave); + for (var i = 0; i < 60; i++) { + budget.tryConsume(keyA, now); + } + // A "new session" changes nothing the budget sees: deviceKey is the + // radio's own public key, so the same key stays capped. + expect(budget.tryConsume(keyA, now), isFalse); + }); + + test('a different device starts fresh', () { + final budget = ScopeHourlyBudget(save: noopSave); + for (var i = 0; i < 60; i++) { + budget.tryConsume(keyA, now); + } + expect(budget.tryConsume(keyB, now), isTrue); + }); + + test('tryConsume in a full hour returns false', () { + final budget = ScopeHourlyBudget(save: noopSave); + for (var i = 0; i < 60; i++) { + budget.tryConsume(keyA, now); + } + expect(budget.tryConsume(keyA, now), isFalse); + }); + + test('tryConsume reserves synchronously and never waits on a stalled ' + 'persistReservation write', () { + final release = Completer(); + final stalled = ScopeHourlyBudget(save: (json) async { + await release.future; + }); + // Reserve, then kick off a persist that will hang. + expect(stalled.tryConsume(keyA, now), isTrue); + var finished = false; + // ignore: unawaited_futures + stalled.persistReservation(keyA, now ~/ 3600).then((_) => finished = true); + // The reservation itself is immediate: a second, different bucket can + // be consumed right away without waiting on the hung save. + expect(stalled.tryConsume(keyB, now), isTrue); + expect(finished, isFalse); + release.complete(); + }); + + test('a failed reservation write drops the answer but keeps the count', () async { + final budget = ScopeHourlyBudget(save: (json) async { + throw Exception('disk full'); + }); + expect(budget.tryConsume(keyA, now), isTrue); + final ok = await budget.persistReservation(keyA, now ~/ 3600); + expect(ok, isFalse); + // The in-memory reservation is not rolled back: it still counts + // against the hour, conservative rather than granting an extra slot. + for (var i = 0; i < 59; i++) { + expect(budget.tryConsume(keyA, now), isTrue); + } + expect(budget.tryConsume(keyA, now), isFalse); + }); + + test('a restart in the same device-hour (persist, reload) still ' + 'refuses the 61st', () async { + Map? stored; + final budget = ScopeHourlyBudget(save: (json) async { + stored = json; + }); + for (var i = 0; i < 60; i++) { + budget.tryConsume(keyA, now); + } + final ok = await budget.persistReservation(keyA, now ~/ 3600); + expect(ok, isTrue); + final reloaded = ScopeHourlyBudget.fromJson(stored, + save: (json) async {}, nowSec: now); + expect(reloaded.tryConsume(keyA, now), isFalse); + }); + + test('a restart between a persisted reservation and its enqueue leaves ' + '59 for that hour', () async { + Map? stored; + final budget = ScopeHourlyBudget(save: (json) async { + stored = json; + }); + expect(budget.tryConsume(keyA, now), isTrue); + final ok = await budget.persistReservation(keyA, now ~/ 3600); + expect(ok, isTrue); + // "Restart": a fresh budget rebuilt from what actually landed on disk. + final reloaded = ScopeHourlyBudget.fromJson(stored, + save: (json) async {}, nowSec: now); + var succeeded = 0; + for (var i = 0; i < 60; i++) { + if (reloaded.tryConsume(keyA, now)) succeeded++; + } + expect(succeeded, 59); + }); + + test('two answers persisting at once both land (serialized writes)', () async { + final release1 = Completer(); + final firstSaveStarted = Completer(); + final snapshots = >[]; + var saveCallCount = 0; + final budget = ScopeHourlyBudget(save: (json) async { + saveCallCount++; + // Capture the snapshot, and signal that this save has genuinely + // started, before doing anything else: production code fixes the + // snapshot at the moment it calls `save`, not at the moment `save` + // finishes, so the test must observe it at that same point. + snapshots.add(json); + if (saveCallCount == 1) { + firstSaveStarted.complete(); + // Hold the first save open so a second, concurrent persist has + // every chance to jump ahead if writes are not actually + // serialized. + await release1.future; + } + }); + + expect(budget.tryConsume(keyA, now), isTrue); + final f1 = budget.persistReservation(keyA, now ~/ 3600); + + // Wait for the first save to actually start, with its snapshot + // already taken, before reserving the second answer. Reserving it any + // earlier would let both reservations land in `_counts` before either + // save runs, which proves nothing about write ordering: the fix here + // is to only make the second reservation once the first save is + // provably mid-write. + await firstSaveStarted.future; + expect(snapshots[0]['$keyA|${now ~/ 3600}'], 1); + expect(snapshots[0].containsKey('$keyB|${now ~/ 3600}'), isFalse, + reason: + 'the first save must not see a reservation made after it started'); + + expect(budget.tryConsume(keyB, now), isTrue); + final f2 = budget.persistReservation(keyB, now ~/ 3600); + + // Let every pending microtask and timer run while the first save is + // still held open. Without serialization the second save would have + // started (and, being unheld, even landed) by now. + await Future.delayed(Duration.zero); + expect(saveCallCount, 1, + reason: 'the second save must wait for the first to finish'); + expect(snapshots.length, 1, reason: 'the second save has not landed yet'); + + release1.complete(); + final results = await Future.wait([f1, f2]); + expect(results, [isTrue, isTrue]); + expect(saveCallCount, 2); + + // The second save's own snapshot, the final state actually written, + // reflects both reservations: no lost update. + expect(snapshots[1]['$keyA|${now ~/ 3600}'], 1); + expect(snapshots[1]['$keyB|${now ~/ 3600}'], 1); + }); + + test('two overlapping reservations for the same bucket: it survives ' + 'until BOTH complete, not just the first', () async { + const hour10 = 10; + const hour13 = 13; + const hour14 = 14; + var saveCallCount = 0; + final release1 = Completer(); + final release2 = Completer(); + final budget = ScopeHourlyBudget(save: (json) async { + saveCallCount++; + if (saveCallCount == 1) { + await release1.future; + } else if (saveCallCount == 2) { + await release2.future; + } + }); + + expect(budget.tryConsume(keyA, hour10 * 3600), isTrue); + final f1 = budget.persistReservation(keyA, hour10); + + expect(budget.tryConsume(keyA, hour10 * 3600 + 1), isTrue); + final f2 = budget.persistReservation(keyA, hour10); + + // Let only the first of the two overlapping saves for hour10 finish. + release1.complete(); + await f1; + expect(budget.toJson()['$keyA|$hour10'], 2, + reason: 'the second save for the same bucket has not finished'); + + // A much later hour's own persist must not drop the still-in-flight + // hour10 bucket just because ONE of its two saves finished. + expect(budget.tryConsume(keyA, hour13 * 3600), isTrue); + final f13 = budget.persistReservation(keyA, hour13); + expect(budget.toJson()['$keyA|$hour10'], 2, + reason: 'hour10 is still in flight (second save not finished)'); + + // Finish the second save too. + release2.complete(); + await Future.wait([f2, f13]); + + // Now that BOTH persists for hour10 are done, it is no longer in + // flight, and a later persist is free to drop it once it is stale. + expect(budget.tryConsume(keyA, hour14 * 3600), isTrue); + await budget.persistReservation(keyA, hour14); + expect(budget.toJson()['$keyA|$hour10'], isNull, + reason: 'hour10 finished (both saves) and is now old enough to drop'); + }); + + test('an answer consumed at 10:59:59 whose persistence finishes at ' + '11:00:01 keeps the 10:00 bucket until it completes', () async { + const hour10 = 10; + const hour13 = 13; + const hour14 = 14; + final release = Completer(); + var releaseUsed = false; + final budget = ScopeHourlyBudget(save: (json) async { + if (!releaseUsed) { + releaseUsed = true; + await release.future; + } + }); + expect(budget.tryConsume(keyA, hour10 * 3600 + 3599), isTrue); + final f10 = budget.persistReservation(keyA, hour10); + + // A much later hour's own reservation must not drop the still-in-flight + // hour10 bucket just because it is now far older than "the previous + // hour" relative to hour13. + expect(budget.tryConsume(keyA, hour13 * 3600), isTrue); + final f13 = budget.persistReservation(keyA, hour13); + expect(budget.toJson()['$keyA|$hour10'], 1, + reason: 'hour10 is still in flight, so it must survive the drop'); + + release.complete(); + await Future.wait([f10, f13]); + + // Now that hour10's own persistence has finished, a later drop is free + // to remove it once it is actually stale. + expect(budget.tryConsume(keyA, hour14 * 3600), isTrue); + await budget.persistReservation(keyA, hour14); + expect(budget.toJson()['$keyA|$hour10'], isNull, + reason: 'hour10 finished and is now old enough to drop'); + }); + + test('fromJson tolerates junk: non-map root, malformed bucket key, ' + 'non-numeric count', () { + final budget = ScopeHourlyBudget.fromJson({ + 'no-pipe-here': 5, + '$keyA|not-a-number': 5, + '$keyA|$hour': 'not-a-number', + }, save: noopSave, nowSec: now); + expect(budget.tryConsume(keyA, now), isTrue); + expect(budget.canAsk(keyA, now), isTrue); + }); + + test('fromJson drops buckets older than the previous hour', () { + final budget = ScopeHourlyBudget.fromJson({ + '$keyA|${hour - 2}': 60, + '$keyA|${hour - 1}': 60, + '$keyA|$hour': 60, + }, save: noopSave, nowSec: now); + // hour-2 is dropped (older than the previous hour), so its slots are + // not held against a fresh ask in that same old hour. + expect(budget.tryConsume(keyA, (hour - 2) * 3600), isTrue); + // hour-1 and hour are both kept and still full. + expect(budget.tryConsume(keyA, (hour - 1) * 3600), isFalse); + expect(budget.tryConsume(keyA, hour * 3600), isFalse); + }); + }); +} diff --git a/test/services/scope_discovery/scope_lifecycle_test.dart b/test/services/scope_discovery/scope_lifecycle_test.dart new file mode 100644 index 00000000..5605360e --- /dev/null +++ b/test/services/scope_discovery/scope_lifecycle_test.dart @@ -0,0 +1,808 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:mesh_mapper/services/api_service.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_discovery_rules.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_lifecycle.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_runner.dart'; + +import '../meshcore/scope_test_support.dart' as support; + +/// A radio that grants a lease and holds the ask until it is cancelled, +/// recording every frame it would have written. +class _HoldingRadio implements ScopeRadio { + final List frames = []; + bool leaseHeld = false; + + @override + Future acquire( + {required Duration admissionWait, + required ScopeCancelToken cancel}) async { + if (cancel.isCancelled) return null; + leaseHeld = true; + return _HoldingLease(this, cancel); + } +} + +class _HoldingLease implements ScopeLeaseHandle { + final _HoldingRadio radio; + final ScopeCancelToken cancel; + _HoldingLease(this.radio, this.cancel); + + @override + List get unrestored => const []; + + @override + Future release() async => radio.leaseHeld = false; + + @override + Future restore(ContactRecord original) async { + if (cancel.isCancelled) return false; + radio.frames.add('restore'); + return true; + } + + @override + Future requestScopes(Uint8List pubkey, Uint8List request, + {required Duration? answerWait, + required DateTime notAfter, + void Function(Duration wait)? onSent}) async { + if (cancel.isCancelled) return const ScopeAborted(); + radio.frames.add('ask'); + await cancel.whenCancelled; + radio.leaseHeld = false; + return const ScopeAborted(); + } +} + +ScopeGateInputs _gate({ + bool offered = true, + bool enforced = false, + bool userEnabled = true, + bool offline = false, + int? firmware = 13, +}) => + ( + offered: offered, + enforced: enforced, + userEnabled: userEnabled, + offlineMode: offline, + firmwareCode: firmware, + ); + +ScopeCandidate _cand(int fill) => ( + keyHex: List.filled(32, fill.toRadixString(16).padLeft(2, '0')) + .join() + .toUpperCase(), + repeaterId: fill.toRadixString(16).toUpperCase(), + lat: 45.0, + lon: -75.0, + localRssi: -70, + localSnr: 5.0, + discoveryReplyAfter: const Duration(milliseconds: 400), + ); + +class _Harness { + final _HoldingRadio radio = _HoldingRadio(); + final List hostCancels = []; + int badgeNotifies = 0; + late final ScopeLifecycle lifecycle = ScopeLifecycle( + cancelHostRunner: hostCancels.add, + onBadgeChanged: () => badgeNotifies++, + ); + final Object connection = Object(); + final List tokens = []; + + ScopeRunner? build( + {ScopeGateInputs? gate, Object? connection, String? deviceKey = 'KEY'}) { + final token = ScopeCancelToken(); + tokens.add(token); + return lifecycle.buildRunner( + gate: gate ?? _gate(), + connection: connection ?? this.connection, + deviceKey: deviceKey, + create: (key, restores, knownNonContacts) => ScopeRunner( + radio: radio, + cancel: token, + hardStop: clock.now().add(const Duration(seconds: 30)), + refreshDays: () => 14, + deviceKey: () => key, + serverInfo: (_) => (onList: false, checkedAt: null), + cache: ScopeQueryCache.fromJson(null), + budget: ScopeHourlyBudget(save: (_) async {}), + enqueue: (_, __) async => true, + nowSec: () => clock.now().millisecondsSinceEpoch ~/ 1000, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: lifecycle.setRequestActive, + onLogged: (_) {}, + pendingRestores: restores, + knownNonContacts: knownNonContacts, + ), + ); + } +} + +void main() { + group('the gate', () { + test('open: offered, switched on, online, firmware 13', () { + expect(scopeDiscoveryGateOpen(_gate()), isTrue); + expect(_Harness().build(), isNotNull); + }); + + test('each closed input builds no runner', () { + final closed = { + 'key absent from /auth': _gate(offered: false), + 'switch off': _gate(userEnabled: false), + 'offline mode': _gate(offline: true), + 'firmware 12': _gate(firmware: 12), + 'firmware 11': _gate(firmware: 11), + 'firmware unknown': _gate(firmware: null), + }; + closed.forEach((name, gate) { + expect(scopeDiscoveryGateOpen(gate), isFalse, reason: name); + expect(_Harness().build(gate: gate), isNull, reason: name); + }); + }); + + test('the admin can switch it on for a user who has it off', () { + expect( + scopeDiscoveryGateOpen(_gate(userEnabled: false, enforced: true)), + isTrue); + expect( + scopeDiscoveryGateOpen( + _gate(userEnabled: false, enforced: true, offered: false)), + isFalse, + reason: 'no key on /auth: never, whatever else says on'); + }); + + test('no connection or no device key builds no runner', () { + final h = _Harness(); + expect( + h.lifecycle.buildRunner( + gate: _gate(), + connection: null, + deviceKey: 'KEY', + create: (_, __, ___) => fail('must not build')), + isNull); + expect(h.build(deviceKey: null), isNull); + }); + }); + + group('every stop event cancels the live runner at once', () { + for (final event in ScopeStopEvent.values) { + test(event.name, () { + fakeAsync((async) { + final h = _Harness(); + final runner = h.build()!; + runner.run([_cand(0x11), _cand(0x22)], + discPersisted: Future.value()); + async.flushMicrotasks(); + expect(h.radio.leaseHeld, isTrue); + expect(h.lifecycle.requestActive, isTrue); + final frames = List.of(h.radio.frames); + + h.lifecycle.onEvent(event); + + expect(h.tokens.single.isCancelled, isTrue); + expect(h.hostCancels, [event.reason]); + expect(h.lifecycle.requestActive, isFalse); + async.flushMicrotasks(); + expect(h.radio.leaseHeld, isFalse); + async.elapse(const Duration(seconds: 60)); + expect(h.radio.frames, frames, reason: 'nothing further written'); + }); + }); + } + + test('an event with no runner live only clears the badge', () { + final h = _Harness(); + h.lifecycle.setRequestActive(true); + h.lifecycle.onEvent(ScopeStopEvent.airborne); + expect(h.lifecycle.requestActive, isFalse); + expect(h.hostCancels, ['airborne']); + }); + }); + + group('an Offline Mode switch', () { + for (final event in [ + ScopeStopEvent.offlineSwitch, + ScopeStopEvent.onlineSwitch, + ]) { + test( + '${event.name}: a discovery window completing during the switch ' + 'builds no runner', () { + fakeAsync((async) { + final h = _Harness(); + final before = h.build()!; + before.run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + final frames = List.of(h.radio.frames); + + // The first line of the switch, before anything is awaited: the + // gate is still open (Offline Mode is not set yet). + h.lifecycle.beginModeSwitch(event); + expect(before.isCancelled, isTrue); + expect(h.hostCancels, [event.reason]); + expect(h.lifecycle.requestActive, isFalse); + + // The session recovery wait: a discovery window closes and asks + // for this sweep's runner. + async.elapse(const Duration(seconds: 10)); + expect(h.build(), isNull, reason: 'the switch is still running'); + async.elapse(const Duration(seconds: 60)); + expect(h.radio.frames, frames, reason: 'nothing further written'); + + // The switch is over and the gate is still open (a failed switch + // back to where it started): sweeps get runners again. + h.lifecycle.endModeSwitch(); + expect(h.build(), isNotNull); + }); + }); + } + + test('an overlapping switch keeps the block until both end', () { + final h = _Harness(); + h.lifecycle.beginModeSwitch(ScopeStopEvent.offlineSwitch); + h.lifecycle.beginModeSwitch(ScopeStopEvent.onlineSwitch); + h.lifecycle.endModeSwitch(); + expect(h.build(), isNull); + h.lifecycle.endModeSwitch(); + expect(h.build(), isNotNull); + }); + }); + + group('borrowed routes', () { + ContactRecord record() => ContactRecord.newRepeater( + publicKey: Uint8List.fromList(List.filled(32, 0x11)), + name: 'R', + lat: 1, + lon: 2, + nowSecs: 5); + + test('kept across runners on one connection, dropped on disconnect', () { + for (final event in ScopeStopEvent.values) { + final h = _Harness(); + h.lifecycle.restoresFor(h.connection).add(record()); + h.lifecycle.onEvent(event); + expect(h.lifecycle.restoresFor(h.connection), + event.dropsConnection ? isEmpty : hasLength(1), + reason: event.name); + } + }); + + test('a new connection starts with none', () { + final h = _Harness(); + h.lifecycle.restoresFor(h.connection).add(record()); + expect(h.lifecycle.restoresFor(Object()), isEmpty); + }); + }); + + group('known non-contacts', () { + test('kept across runners on one connection, dropped on disconnect', () { + for (final event in ScopeStopEvent.values) { + final h = _Harness(); + h.lifecycle.knownNonContactsFor(h.connection).add('AB' * 32); + h.lifecycle.onEvent(event); + expect(h.lifecycle.knownNonContactsFor(h.connection), + event.dropsConnection ? isEmpty : hasLength(1), + reason: event.name); + } + }); + + test('a new connection starts with none', () { + final h = _Harness(); + h.lifecycle.knownNonContactsFor(h.connection).add('AB' * 32); + expect(h.lifecycle.knownNonContactsFor(Object()), isEmpty); + }); + + test('reading restores and known non-contacts for the same new ' + 'connection resets both together, whichever is read first', () { + final h = _Harness(); + h.lifecycle.restoresFor(h.connection).add(ContactRecord.newRepeater( + publicKey: Uint8List.fromList(List.filled(32, 0x11)), + name: 'R', + lat: 1, + lon: 2, + nowSecs: 5)); + h.lifecycle.knownNonContactsFor(h.connection).add('AB' * 32); + final other = Object(); + // Read known-non-contacts first this time: it must not leave the + // restores list stale for the same new connection. + expect(h.lifecycle.knownNonContactsFor(other), isEmpty); + expect(h.lifecycle.restoresFor(other), isEmpty); + }); + }); + + group('connect-time repeater refresh', () { + test('a list landing after a zone change is discarded', () { + fakeAsync((async) { + final h = _Harness(); + var zone = 'YOW'; + List? applied; + var settled = false; + h.lifecycle + .resultIfStillCurrent>( + fetch: Future.delayed( + const Duration(seconds: 2), () => ['from YOW']), + zone: 'YOW', + preset: '910.525,62.5,7', + currentZone: () => zone, + currentPreset: () => '910.525,62.5,7', + ) + .then((r) { + applied = r; + settled = true; + }); + async.elapse(const Duration(seconds: 1)); + zone = 'YUL'; + async.elapse(const Duration(seconds: 2)); + expect(settled, isTrue); + expect(applied, isNull); + }); + }); + + test('a list landing after a preset change is discarded', () { + fakeAsync((async) { + final h = _Harness(); + var preset = '910.525,62.5,7'; + List? applied = const ['untouched']; + h.lifecycle + .resultIfStillCurrent>( + fetch: Future.delayed( + const Duration(seconds: 2), () => ['old preset']), + zone: 'YOW', + preset: preset, + currentZone: () => 'YOW', + currentPreset: () => preset, + ) + .then((r) => applied = r); + async.elapse(const Duration(seconds: 1)); + preset = '869.525,250,11'; + async.elapse(const Duration(seconds: 2)); + expect(applied, isNull); + }); + }); + + test('nothing moved: the list is applied', () { + fakeAsync((async) { + final h = _Harness(); + List? applied; + h.lifecycle + .resultIfStillCurrent>( + fetch: Future.delayed( + const Duration(seconds: 2), () => ['fresh']), + zone: 'YOW', + preset: null, + currentZone: () => 'YOW', + currentPreset: () => null, + ) + .then((r) => applied = r); + async.elapse(const Duration(seconds: 3)); + expect(applied, ['fresh']); + }); + }); + + test('a failed fetch reads as nothing to apply', () { + fakeAsync((async) { + final h = _Harness(); + var settled = false; + List? applied = const ['untouched']; + h.lifecycle + .resultIfStillCurrent>( + fetch: Future.error(StateError('offline')), + zone: 'YOW', + preset: null, + currentZone: () => 'YOW', + currentPreset: () => null, + ) + .then((r) { + applied = r; + settled = true; + }); + async.flushMicrotasks(); + expect(settled, isTrue); + expect(applied, isNull); + }); + }); + }); + + group('the periodic repeater refresh timer', () { + test('not running until started', () { + final h = _Harness(); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + }); + + test('ticks at 15 and 30 minutes, not before', () { + fakeAsync((async) { + final h = _Harness(); + var ticks = 0; + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () => ticks++); + expect(h.lifecycle.repeaterRefreshTimerRunning, isTrue); + + async.elapse(const Duration(minutes: 14, seconds: 59)); + expect(ticks, 0); + async.elapse(const Duration(seconds: 1)); + expect(ticks, 1); + + async.elapse(const Duration(minutes: 14, seconds: 59)); + expect(ticks, 1); + async.elapse(const Duration(seconds: 1)); + expect(ticks, 2); + }); + }); + + test('starting again reschedules from now rather than stacking ticks', + () { + fakeAsync((async) { + final h = _Harness(); + var ticks = 0; + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () => ticks++); + async.elapse(const Duration(minutes: 10)); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () => ticks++); + // The old schedule would have ticked at 15 minutes; the new one + // (restarted at 10) only ticks at 25. + async.elapse(const Duration(minutes: 5)); + expect(ticks, 0); + async.elapse(const Duration(minutes: 10)); + expect(ticks, 1); + }); + }); + + test('stopRepeaterRefreshTimer cancels it; idempotent when not running', + () { + fakeAsync((async) { + final h = _Harness(); + var ticks = 0; + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () => ticks++); + h.lifecycle.stopRepeaterRefreshTimer(); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + async.elapse(const Duration(minutes: 30)); + expect(ticks, 0); + // Stopping again (nothing running) does not throw. + h.lifecycle.stopRepeaterRefreshTimer(); + }); + }); + + for (final event in ScopeStopEvent.values) { + test('onEvent(${event.name}) stops it', () { + fakeAsync((async) { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + h.lifecycle.onEvent(event); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + }); + }); + } + + test('onGateChanged stops it when the gate closes, even with no live ' + 'runner', () { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + expect(h.lifecycle.repeaterRefreshTimerRunning, isTrue); + h.lifecycle.onGateChanged(_gate(userEnabled: false), + passiveOrHybridRunning: false, startRepeaterRefresh: () {}); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + }); + + test('onGateChanged leaves it running while the gate stays open', () { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + h.lifecycle.onGateChanged(_gate(), + passiveOrHybridRunning: true, startRepeaterRefresh: () {}); + expect(h.lifecycle.repeaterRefreshTimerRunning, isTrue); + }); + + test('onGateChanged re-arms the refresh when the gate reopens while ' + 'Passive or Hybrid is still running', () { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + // The gate closes (mode still running): the timer stops. + h.lifecycle.onGateChanged(_gate(userEnabled: false), + passiveOrHybridRunning: true, startRepeaterRefresh: () {}); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + + // The gate reopens with the mode still running: re-armed via the + // same sequence a fresh mode start uses. + var rearmed = false; + h.lifecycle.onGateChanged(_gate(), + passiveOrHybridRunning: true, + startRepeaterRefresh: () { + rearmed = true; + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + }); + expect(rearmed, isTrue); + expect(h.lifecycle.repeaterRefreshTimerRunning, isTrue); + }); + + test('onGateChanged does not re-arm when the gate reopens but Passive ' + 'or Hybrid is not running', () { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + h.lifecycle.onGateChanged(_gate(userEnabled: false), + passiveOrHybridRunning: false, startRepeaterRefresh: () {}); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + + var rearmed = false; + h.lifecycle.onGateChanged(_gate(), + passiveOrHybridRunning: false, + startRepeaterRefresh: () => rearmed = true); + expect(rearmed, isFalse); + expect(h.lifecycle.repeaterRefreshTimerRunning, isFalse); + }); + + test('onGateChanged does not re-invoke the re-arm callback when the ' + 'timer is already running', () { + final h = _Harness(); + h.lifecycle.startRepeaterRefreshTimer( + const Duration(minutes: 15), () {}); + var called = false; + h.lifecycle.onGateChanged(_gate(), + passiveOrHybridRunning: true, + startRepeaterRefresh: () => called = true); + expect(called, isFalse, + reason: 'already running: nothing to re-arm'); + expect(h.lifecycle.repeaterRefreshTimerRunning, isTrue); + }); + }); + + group('a live auth that withdraws scope discovery', () { + test('stops a pending lookup before the scope request is written', () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + var offerScopes = true; + final api = ApiService( + client: MockClient((request) async => http.Response( + json.encode({ + 'success': true, + 'session_id': 'YOW-20260905-0001', + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + if (offerScopes) 'scope_discovery': false, + }), + 200)), + ); + void auth() { + api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.42, + lon: -75.70); + async.elapse(const Duration(milliseconds: 10)); + } + + ScopeGateInputs gate() => ( + offered: api.scopeDiscoveryOffered, + enforced: api.enforceScopeDiscovery, + userEnabled: true, + offlineMode: false, + firmwareCode: 13, + ); + final h = _Harness(); + // The provider's wiring, as in AppStateProvider. No mode is running + // in this test, so the re-arm arm is exercised elsewhere. + api.onScopeDiscoveryChanged = () => h.lifecycle.onGateChanged(gate(), + passiveOrHybridRunning: false, startRepeaterRefresh: () {}); + + auth(); + expect(api.scopeDiscoveryOffered, isTrue); + final runner = h.lifecycle.buildRunner( + gate: gate(), + connection: conn, + deviceKey: 'KEY', + create: (key, restores, knownNonContacts) => ScopeRunner( + radio: MeshCoreScopeRadio(conn), + cancel: ScopeCancelToken(), + hardStop: clock.now().add(const Duration(seconds: 30)), + refreshDays: () => 14, + deviceKey: () => key, + serverInfo: (_) => (onList: false, checkedAt: null), + cache: ScopeQueryCache.fromJson(null), + budget: ScopeHourlyBudget(save: (_) async {}), + enqueue: (_, __) async => true, + nowSec: () => clock.now().millisecondsSinceEpoch ~/ 1000, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: h.lifecycle.setRequestActive, + onLogged: (_) {}, + pendingRestores: restores, + knownNonContacts: knownNonContacts, + ), + )!; + runner.run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + expect(radio.commands, [CommandCodes.getContactByKey], + reason: 'the lookup is out and unanswered'); + + // A session recovery's answer arrives without the key. + offerScopes = false; + auth(); + expect(api.scopeDiscoveryOffered, isFalse); + expect(runner.isCancelled, isTrue); + expect(h.lifecycle.requestActive, isFalse); + + // The lookup's reply (not a saved contact) would lead straight to + // the scope request. + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.elapse(const Duration(seconds: 10)); + expect(radio.commands, isNot(contains(CommandCodes.sendAnonReq))); + expect(radio.commands, [CommandCodes.getContactByKey]); + expect(conn.isScopeLeaseActive, isFalse); + }); + }); + + test( + 'with a new session id it stops the lookup before the stale TX ' + 'cleanup runs', () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + var offerScopes = true; + var sessionId = 'YOW-20260905-0001'; + final api = ApiService( + client: MockClient((request) async => http.Response( + json.encode({ + 'success': true, + 'session_id': sessionId, + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + if (offerScopes) 'scope_discovery': false, + }), + 200)), + ); + void auth() { + api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.42, + lon: -75.70); + async.elapse(const Duration(milliseconds: 10)); + } + + ScopeGateInputs gate() => ( + offered: api.scopeDiscoveryOffered, + enforced: api.enforceScopeDiscovery, + userEnabled: true, + offlineMode: false, + firmwareCode: 13, + ); + final h = _Harness(); + api.onScopeDiscoveryChanged = () => h.lifecycle.onGateChanged(gate(), + passiveOrHybridRunning: false, startRepeaterRefresh: () {}); + // The stale tagged TX cleanup, held open by the test. + final cleanup = Completer(); + final sessionChanges = []; + api.onSessionIdChanged = (previous, next) { + sessionChanges.add('$previous>$next'); + return cleanup.future; + }; + + auth(); + expect(api.scopeDiscoveryOffered, isTrue); + final runner = h.lifecycle.buildRunner( + gate: gate(), + connection: conn, + deviceKey: 'KEY', + create: (key, restores, knownNonContacts) => ScopeRunner( + radio: MeshCoreScopeRadio(conn), + cancel: ScopeCancelToken(), + hardStop: clock.now().add(const Duration(seconds: 30)), + refreshDays: () => 14, + deviceKey: () => key, + serverInfo: (_) => (onList: false, checkedAt: null), + cache: ScopeQueryCache.fromJson(null), + budget: ScopeHourlyBudget(save: (_) async {}), + enqueue: (_, __) async => true, + nowSec: () => clock.now().millisecondsSinceEpoch ~/ 1000, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: h.lifecycle.setRequestActive, + onLogged: (_) {}, + pendingRestores: restores, + knownNonContacts: knownNonContacts, + ), + )!; + runner.run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + expect(radio.commands, [CommandCodes.getContactByKey]); + + // A recovery's answer: no key, and a new session id. + offerScopes = false; + sessionId = 'YOW-20260905-0002'; + auth(); + expect(sessionChanges, + ['YOW-20260905-0001>YOW-20260905-0002'], + reason: 'the cleanup is running'); + expect(runner.isCancelled, isTrue, + reason: 'withdrawn before the cleanup is awaited'); + expect(h.lifecycle.requestActive, isFalse); + + // The lookup's reply lands while the cleanup is still running. + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.elapse(const Duration(seconds: 5)); + expect(radio.commands, isNot(contains(CommandCodes.sendAnonReq))); + + cleanup.complete(); + async.elapse(const Duration(seconds: 5)); + expect(api.sessionId, 'YOW-20260905-0002'); + expect(api.scopeDiscoveryOffered, isFalse); + expect(radio.commands, [CommandCodes.getContactByKey]); + expect(conn.isScopeLeaseActive, isFalse); + }); + }); + + test('a stale owner after the cleanup still leaves scope withdrawn', () { + fakeAsync((async) { + var offerScopes = true; + var sessionId = 'YOW-20260905-0001'; + final api = ApiService( + client: MockClient((request) async => http.Response( + json.encode({ + 'success': true, + 'session_id': sessionId, + 'tx_allowed': true, + 'rx_allowed': true, + 'expires_at': + clock.now().millisecondsSinceEpoch ~/ 1000 + 300, + if (offerScopes) 'scope_discovery': true, + }), + 200)), + ); + var fired = 0; + api.onScopeDiscoveryChanged = () => fired++; + var owner = true; + api.onSessionIdChanged = (_, __) async => owner = false; + void auth() { + api.requestAuth( + reason: 'connect', + publicKey: 'AB' * 32, + lat: 45.42, + lon: -75.70, + shouldStoreSession: () => owner); + async.elapse(const Duration(milliseconds: 10)); + } + + auth(); + expect(api.enforceScopeDiscovery, isTrue); + expect(fired, 1); + offerScopes = false; + sessionId = 'YOW-20260905-0002'; + auth(); + expect(api.scopeDiscoveryOffered, isFalse); + expect(api.enforceScopeDiscovery, isFalse); + expect(fired, 2); + expect(api.sessionId, 'YOW-20260905-0001', + reason: 'a stale owner stores no session'); + }); + }); + + test('an answer that keeps it offered cancels nothing', () { + final h = _Harness(); + final runner = h.build()!; + h.lifecycle.onGateChanged(_gate(), + passiveOrHybridRunning: false, startRepeaterRefresh: () {}); + expect(runner.isCancelled, isFalse); + expect(h.hostCancels, isEmpty); + }); + }); +} diff --git a/test/services/scope_discovery/scope_provider_support_test.dart b/test/services/scope_discovery/scope_provider_support_test.dart new file mode 100644 index 00000000..47ad4a60 --- /dev/null +++ b/test/services/scope_discovery/scope_provider_support_test.dart @@ -0,0 +1,284 @@ +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_provider_support.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_runner.dart'; + +Repeater _repeater(String hex, {int? checkedAt}) => Repeater.fromJson({ + 'id': hex.substring(0, 2), + 'hex_id': hex, + 'name': 'R', + 'lat': 1.0, + 'lon': 2.0, + 'last_heard': 0, + 'enabled': 1, + if (checkedAt != null) 'scopes_checked_at': checkedAt, + }); + +void main() { + group('whether a scope refresh changes the map', () { + test('only the scope stamps moved: no change', () { + expect( + scopeRefreshChangesMap( + [_repeater('ab' * 32), _repeater('cd' * 32, checkedAt: 1)], + [ + _repeater('ab' * 32, checkedAt: 1790000000), + _repeater('cd' * 32, checkedAt: 2), + ]), + isFalse); + }); + + test('a rendered field moved: changed', () { + final before = [_repeater('ab' * 32)]; + expect( + scopeRefreshChangesMap( + before, [before.single.copyWith(lastHeard: 1790000000)]), + isTrue); + expect(scopeRefreshChangesMap(before, [before.single.copyWith(enabled: 2)]), + isTrue); + expect(scopeRefreshChangesMap(before, [before.single.copyWith(lat: 3.0)]), + isTrue); + }); + + test('a repeater added, dropped or reordered: changed', () { + final a = _repeater('ab' * 32); + final b = _repeater('cd' * 32); + expect(scopeRefreshChangesMap([a], [a, b]), isTrue); + expect(scopeRefreshChangesMap([a, b], [a]), isTrue); + expect(scopeRefreshChangesMap([a, b], [b, a]), isTrue); + expect(scopeRefreshChangesMap(const [], [a]), isTrue); + }); + }); + + group('server info map', () { + test('keys are upper-case full keys; short ids are left out', () { + final map = scopeServerInfoMap([ + _repeater('ab' * 32, checkedAt: 1790000000), + _repeater('cd' * 32), + _repeater('4E7A'), + ]); + expect(map.keys, ['AB' * 32, 'CD' * 32]); + expect(scopeServerInfoFor(map, 'ab' * 32), + (onList: true, checkedAt: 1790000000)); + expect(scopeServerInfoFor(map, 'CD' * 32), + (onList: true, checkedAt: null)); + }); + + test('a ghost is not on the list', () { + final map = scopeServerInfoMap([_repeater('ab' * 32)]); + expect(scopeServerInfoFor(map, 'EF' * 32), + (onList: false, checkedAt: null)); + expect(scopeServerInfoFor(map, 'not a key'), + (onList: false, checkedAt: null)); + }); + }); + + group('connect-time repeater refresh', () { + final now = DateTime(2026, 9, 26, 12); + + test('due only when active and the list is missing or an hour old', () { + expect( + scopeRepeaterRefreshDue(active: false, loadedAt: null, now: now), + isFalse); + expect(scopeRepeaterRefreshDue(active: true, loadedAt: null, now: now), + isTrue); + expect( + scopeRepeaterRefreshDue( + active: true, + loadedAt: now.subtract(const Duration(minutes: 59)), + now: now), + isFalse); + expect( + scopeRepeaterRefreshDue( + active: true, + loadedAt: now.subtract(const Duration(hours: 1)), + now: now), + isTrue); + }); + + test('a custom maxAge is honoured (mode-start 5 minute check)', () { + expect( + scopeRepeaterRefreshDue( + active: true, + loadedAt: now.subtract(const Duration(minutes: 4)), + now: now, + maxAge: scopeListRefreshOnStartAge), + isFalse, + reason: '4 minutes < 5 minute maxAge'); + expect( + scopeRepeaterRefreshDue( + active: true, + loadedAt: now.subtract(const Duration(minutes: 6)), + now: now, + maxAge: scopeListRefreshOnStartAge), + isTrue, + reason: '6 minutes >= 5 minute maxAge'); + expect( + scopeRepeaterRefreshDue( + active: false, + loadedAt: now.subtract(const Duration(minutes: 6)), + now: now, + maxAge: scopeListRefreshOnStartAge), + isFalse, + reason: 'inactive: never due, whatever the age'); + }); + + test('a refetch landing after a zone change is discarded', () { + expect( + scopeRepeaterRefreshStillCurrent( + requestedZone: 'YOW', + requestedFilterKey: '910.525,62.5,7', + currentZone: 'YUL', + currentFilterKey: '910.525,62.5,7'), + isFalse); + }); + + test('a refetch landing after a preset change is discarded', () { + expect( + scopeRepeaterRefreshStillCurrent( + requestedZone: 'YOW', + requestedFilterKey: '910.525,62.5,7', + currentZone: 'YOW', + currentFilterKey: '869.525,250,11'), + isFalse); + }); + + test('neither moved: applied', () { + expect( + scopeRepeaterRefreshStillCurrent( + requestedZone: 'YOW', + requestedFilterKey: null, + currentZone: 'YOW', + currentFilterKey: null), + isTrue); + }); + }); + + group('the Passive/Hybrid mode-start refresh plan', () { + final now = DateTime(2026, 9, 26, 12); + + test('a 4-minute-old list: timer armed, no immediate refresh', () { + final plan = scopeModeStartRefreshPlan( + active: true, + zone: 'YOW', + loadedAt: now.subtract(const Duration(minutes: 4)), + now: now); + expect(plan.refreshNow, isFalse); + expect(plan.armTimer, isTrue); + }); + + test('a 6-minute-old list: refreshes at once and arms the timer', () { + final plan = scopeModeStartRefreshPlan( + active: true, + zone: 'YOW', + loadedAt: now.subtract(const Duration(minutes: 6)), + now: now); + expect(plan.refreshNow, isTrue); + expect(plan.armTimer, isTrue); + }); + + test('no list loaded yet: refreshes at once and arms the timer', () { + final plan = scopeModeStartRefreshPlan( + active: true, zone: 'YOW', loadedAt: null, now: now); + expect(plan.refreshNow, isTrue); + expect(plan.armTimer, isTrue); + }); + + test('scope discovery inactive: nothing at all, whatever the age', () { + final plan = scopeModeStartRefreshPlan( + active: false, + zone: 'YOW', + loadedAt: now.subtract(const Duration(hours: 1)), + now: now); + expect(plan.refreshNow, isFalse); + expect(plan.armTimer, isFalse); + }); + + test('no zone yet: nothing at all', () { + final plan = scopeModeStartRefreshPlan( + active: true, zone: null, loadedAt: null, now: now); + expect(plan.refreshNow, isFalse); + expect(plan.armTimer, isFalse); + }); + + test('an empty zone string: nothing at all', () { + final plan = scopeModeStartRefreshPlan( + active: true, zone: '', loadedAt: null, now: now); + expect(plan.refreshNow, isFalse); + expect(plan.armTimer, isFalse); + }); + }); + + group('whether a periodic refresh tick should run', () { + test('active, mode running, known zone: runs', () { + expect( + scopePeriodicRefreshShouldRun( + active: true, passiveOrHybridRunning: true, zone: 'YOW'), + isTrue); + }); + + test('the mode is off: does nothing, even though scope discovery is ' + 'active', () { + expect( + scopePeriodicRefreshShouldRun( + active: true, passiveOrHybridRunning: false, zone: 'YOW'), + isFalse); + }); + + test('scope discovery inactive: does nothing, even with the mode ' + 'running', () { + expect( + scopePeriodicRefreshShouldRun( + active: false, passiveOrHybridRunning: true, zone: 'YOW'), + isFalse); + }); + + test('no zone: does nothing', () { + expect( + scopePeriodicRefreshShouldRun( + active: true, passiveOrHybridRunning: true, zone: null), + isFalse); + }); + + test('an empty zone string: does nothing', () { + expect( + scopePeriodicRefreshShouldRun( + active: true, passiveOrHybridRunning: true, zone: ''), + isFalse); + }); + }); + + test('stored JSON decodes from a string or a map, junk reads null', () { + expect(decodeScopeJsonMap('{"a":1}'), {'a': 1}); + expect(decodeScopeJsonMap({'a': 1}), {'a': 1}); + expect(decodeScopeJsonMap('not json'), isNull); + expect(decodeScopeJsonMap('[1]'), isNull); + expect(decodeScopeJsonMap(null), isNull); + }); + + test('the serial writer runs one write at a time and survives a throw', () { + fakeAsync((async) { + var running = 0; + var maxRunning = 0; + var runs = 0; + var fail = true; + final writer = ScopeSerialWriter('test state', () async { + running++; + if (running > maxRunning) maxRunning = running; + await Future.delayed(const Duration(milliseconds: 10)); + running--; + runs++; + if (fail) { + fail = false; + throw StateError('disk'); + } + }); + writer.schedule(); + writer.schedule(); + writer.schedule(); + async.elapse(const Duration(seconds: 1)); + expect(runs, 3); + expect(maxRunning, 1); + }); + }); +} diff --git a/test/services/scope_discovery/scope_regions_codec_test.dart b/test/services/scope_discovery/scope_regions_codec_test.dart new file mode 100644 index 00000000..1928feca --- /dev/null +++ b/test/services/scope_discovery/scope_regions_codec_test.dart @@ -0,0 +1,93 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_regions_codec.dart'; + +Uint8List reply(String names) => Uint8List.fromList( + [0x10, 0x20, 0x30, 0x40, ...utf8.encode(names)]); // 4-byte repeater clock first + +void main() { + test('request is regions type with a zero-hop reply path', () { + expect(buildRegionsRequest(), [0x01, 0x00]); + }); + test('names keep case and order, * kept', () { + expect(parseRegionsReply(reply('*,YOW,on')), ['*', 'YOW', 'on']); + }); + test('clock only is a valid empty answer', () { + expect(parseRegionsReply(reply('')), []); + }); + test('shorter than the clock is no answer', () { + expect(parseRegionsReply(Uint8List.fromList([1, 2, 3])), isNull); + }); + test('a space fails the token rule, so the reply is malformed', () { + expect(parseRegionsReply(reply('a, b')), isNull); + }); + test('token rule: 30 bytes ok, 31 malformed', () { + expect(parseRegionsReply(reply('A' * 30)), ['A' * 30]); + expect(parseRegionsReply(reply('A' * 31)), isNull); + }); + test('token rule: leading # malformed, inner # ok', () { + expect(parseRegionsReply(reply('#yow')), isNull); + expect(parseRegionsReply(reply('y#w')), ['y#w']); + }); + test('token rule: * only valid alone', () { + expect(parseRegionsReply(reply('*')), ['*']); + expect(parseRegionsReply(reply('*PAH')), isNull); + }); + test('token rule: - \$ digits and bytes >= A are valid', () { + expect(parseRegionsReply(reply('ILM-MM,a\$1,Zürich')), ['ILM-MM', 'a\$1', 'Zürich']); + expect(parseRegionsReply(reply('a.b')), isNull); + }); + test('empty segment is malformed', () { + expect(parseRegionsReply(reply('a,,b')), isNull); + expect(parseRegionsReply(reply('a,')), isNull); + expect(parseRegionsReply(reply(',a')), isNull); + }); + test('trailing zero padding from the cipher block is ignored', () { + // The body a real repeater sent (clock, names, then block padding). + final d = Uint8List.fromList([ + 0xeb, 0x94, 0xba, 0x6a, // + ...utf8.encode('*,yow,on,onqc,can'), + 0, 0, 0, 0, 0, 0, 0, + ]); + expect(parseRegionsReply(d), ['*', 'yow', 'on', 'onqc', 'can']); + }); + test('padding only after the clock is a valid empty answer', () { + expect(parseRegionsReply(Uint8List.fromList([1, 2, 3, 4, 0, 0, 0])), + []); + }); + test('a NUL before the end is malformed', () { + expect(parseRegionsReply(reply('a\u0000b')), isNull); + expect(parseRegionsReply(reply('a,\u0000,b')), isNull); + }); + test('invalid UTF-8 is malformed, never throws', () { + final d = Uint8List.fromList([0, 0, 0, 0, 0x61, 0xFF, 0x2C, 0x62]); + expect(parseRegionsReply(d), isNull); + }); + test('33 names is fine, 34 is malformed', () { + String n(int c) => List.generate(c, (i) => 'r$i').join(','); + expect(parseRegionsReply(reply(n(33))), hasLength(33)); + expect(parseRegionsReply(reply(n(34))), isNull); + }); + test('leading byte order mark is preserved in first name', () { + const bom = '\u{FEFF}'; + final d = Uint8List.fromList([0, 0, 0, 0, 0xEF, 0xBB, 0xBF, 0x59, 0x4F, 0x57]); // clock + BOM + YOW + expect(parseRegionsReply(d), ['$bom' 'YOW']); + expect(parseRegionsReply(d)![0].length, 4); // BOM (1 char) + YOW (3 chars) + }); + test('BOM plus 28 ASCII letters (31 bytes) is malformed', () { + final d = Uint8List.fromList([0, 0, 0, 0, 0xEF, 0xBB, 0xBF, ...List.generate(28, (_) => 0x41)]); // clock + BOM + 28 A's + expect(parseRegionsReply(d), isNull); + }); + test('BOM plus 27 ASCII letters (30 bytes) is accepted and preserved', () { + const bom = '\u{FEFF}'; + final letters = List.generate(27, (_) => 0x41); + final d = Uint8List.fromList([0, 0, 0, 0, 0xEF, 0xBB, 0xBF, ...letters]); // clock + BOM + 27 A's + final result = parseRegionsReply(d); + expect(result, isNotNull); + if (result != null) { + expect(result[0].startsWith(bom), true); + expect(result[0].length, 28); // BOM (1 char) + 27 A's + } + }); +} diff --git a/test/services/scope_discovery/scope_runner_test.dart b/test/services/scope_discovery/scope_runner_test.dart new file mode 100644 index 00000000..8d9b9491 --- /dev/null +++ b/test/services/scope_discovery/scope_runner_test.dart @@ -0,0 +1,1433 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:clock/clock.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:geolocator/geolocator.dart'; +import 'package:mesh_mapper/models/scope_log_entry.dart'; +import 'package:mesh_mapper/services/meshcore/connection.dart'; +import 'package:mesh_mapper/services/meshcore/protocol_constants.dart'; +import 'package:mesh_mapper/services/meshcore/scope_lease.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_discovery_rules.dart'; +import 'package:mesh_mapper/services/scope_discovery/scope_runner.dart'; + +import '../meshcore/scope_test_support.dart' as support; + +// --------------------------------------------------------------------------- +// A fake radio: one lease at a time, a scripted answer per repeater, and a +// record of everything that would have gone on the air. +// --------------------------------------------------------------------------- + +/// How one repeater behaves when asked. +class _Script { + /// Time the lease stage takes (lookup, borrow, send, SENT, restore). + final Duration leaseTime; + + /// The answer body arrives this long after SENT; null never answers. + final Duration? answerAfter; + + /// The reply body, clock bytes included. + final List body; + + /// An outcome returned from inside the lease instead of a wait. + final ScopeRequestOutcome? inLease; + + /// A record borrowed during the lease (left unrestored on cancel). + final ContactRecord? borrow; + + /// The radio's est_timeout, for the fallback wait. + final Duration est; + + const _Script({ + this.leaseTime = const Duration(milliseconds: 100), + this.answerAfter, + this.body = const [1, 2, 3, 4], + this.inLease, + this.borrow, + this.est = const Duration(seconds: 2), + }); + + static _Script answers(String names, + {Duration after = const Duration(milliseconds: 300)}) => + _Script(answerAfter: after, body: [1, 2, 3, 4, ...utf8.encode(names)]); +} + +class _AskRecord { + final String key; + final Duration? answerWait; + final DateTime notAfter; + final DateTime at; + Duration? wait; + _AskRecord(this.key, this.answerWait, this.notAfter, this.at); +} + +class _FakeRadio implements ScopeRadio { + final Map scripts = {}; + final List<_AskRecord> asks = []; + + /// Every frame the fake would have written, in order. + final List frames = []; + final List overlaps = []; + bool refuse = false; + Duration admissionDelay = Duration.zero; + bool restoreOk = true; + bool busy = false; + _FakeLease? current; + int acquires = 0; + + @override + Future acquire( + {required Duration admissionWait, + required ScopeCancelToken cancel}) async { + acquires++; + if (busy) overlaps.add('acquire while busy'); + if (admissionDelay > Duration.zero) { + await _race(admissionDelay, cancel); + } + if (refuse || cancel.isCancelled) return null; + busy = true; + return current = _FakeLease(this, cancel); + } +} + +/// Waits [d], or less when [cancel] fires. True when the wait ran out. +Future _race(Duration d, ScopeCancelToken cancel) { + final done = Completer(); + final t = Timer(d, () { + if (!done.isCompleted) done.complete(true); + }); + cancel.whenCancelled.then((_) { + t.cancel(); + if (!done.isCompleted) done.complete(false); + }); + return done.future; +} + +class _FakeLease implements ScopeLeaseHandle { + final _FakeRadio radio; + final ScopeCancelToken cancel; + bool active = true; + final List _unrestored = []; + + _FakeLease(this.radio, this.cancel); + + void _end() { + if (!active) return; + active = false; + radio.busy = false; + } + + @override + List get unrestored => List.unmodifiable(_unrestored); + + @override + Future release() async => _end(); + + @override + Future restore(ContactRecord original) async { + if (!active || cancel.isCancelled) return false; + radio.frames.add('restore:${_hex(original.publicKey).substring(0, 8)}'); + if (!radio.restoreOk) { + _unrestored.add(original); + return false; + } + return true; + } + + @override + Future requestScopes(Uint8List pubkey, Uint8List request, + {required Duration? answerWait, + required DateTime notAfter, + void Function(Duration wait)? onSent}) async { + final key = _hex(pubkey); + if (!active || cancel.isCancelled) { + _end(); + return const ScopeAborted(); + } + final record = _AskRecord(key, answerWait, notAfter, clock.now()); + radio.asks.add(record); + radio.frames.add('ask:${key.substring(0, 8)}'); + final s = radio.scripts[key] ?? const _Script(); + if (s.borrow != null) _unrestored.add(s.borrow!); + final ran = await _race(s.leaseTime, cancel); + if (!ran || !active) { + _end(); + return ScopeAborted( + restoreOwed: s.borrow != null, borrowedFrom: s.borrow); + } + if (s.inLease != null) { + _end(); + return s.inLease!; + } + if (s.borrow != null) _unrestored.remove(s.borrow); + var wait = answerWait ?? s.est + kScopeAnswerFallbackMargin; + if (wait > kScopeAnswerWaitCap) wait = kScopeAnswerWaitCap; + final sentAt = clock.now(); + var end = sentAt.add(wait); + if (notAfter.isBefore(end)) end = notAfter; + record.wait = wait; + onSent?.call(wait); + _end(); + // Answer wait, outside the lease. + final remaining = end.difference(clock.now()); + final answerAfter = s.answerAfter; + if (answerAfter != null && answerAfter <= remaining) { + final ran2 = await _race(answerAfter, cancel); + if (!ran2) return const ScopeAborted(); + return ScopeAnswered(Uint8List.fromList(s.body), clock.now()); + } + final ran3 = await _race(remaining, cancel); + if (!ran3) return const ScopeAborted(); + return const ScopeNoAnswer(); + } +} + +String _hex(Uint8List b) => + b.map((x) => x.toRadixString(16).padLeft(2, '0')).join().toUpperCase(); + +String _key(int fill) => + List.filled(32, fill.toRadixString(16).padLeft(2, '0')).join().toUpperCase(); + +ScopeCandidate _cand(int fill, + {int rssi = -80, + double snr = 5, + Duration? reply = const Duration(milliseconds: 400), + double lat = 45.0, + double lon = -75.0}) => + ( + keyHex: _key(fill), + repeaterId: _key(fill).substring(0, 2), + lat: lat, + lon: lon, + localRssi: rssi, + localSnr: snr, + discoveryReplyAfter: reply, + ); + +/// Everything a runner is built from, with knobs for the tests. +class _Harness { + final _FakeRadio radio = _FakeRadio(); + final ScopeCancelToken cancel = ScopeCancelToken(); + late ScopeQueryCache cache = ScopeQueryCache.fromJson(null); + final Map savedBudget = {}; + Map? savedCache; + Completer? budgetSaveGate; + bool budgetSaveFails = false; + late ScopeHourlyBudget budget = ScopeHourlyBudget(save: (json) async { + if (budgetSaveGate != null) await budgetSaveGate!.future; + if (budgetSaveFails) throw StateError('disk full'); + savedBudget + ..clear() + ..addAll(json); + }); + final Map server = {}; + bool serverListLoaded = true; + final List<({ScopeAnswer answer, ScopePersistContext ctx})> enqueued = []; + Future Function(ScopeAnswer, ScopePersistContext)? enqueueOverride; + final List badge = []; + final List logged = []; + ({double lat, double lon})? position = (lat: 45.0, lon: -75.0); + bool wanted = true; + int queueGeneration = 1; + final List pendingRestores = []; + final Set knownNonContacts = {}; + bool cannotAskNonContacts = false; + int cacheSaves = 0; + + int nowSec() => clock.now().millisecondsSinceEpoch ~/ 1000; + + ScopeRunner build({DateTime? hardStop, ScopeCancelToken? token}) { + return ScopeRunner( + radio: radio, + cancel: token ?? cancel, + hardStop: hardStop ?? clock.now().add(const Duration(seconds: 30)), + refreshDays: () => 14, + deviceKey: () => 'DEVICEKEY', + sessionId: () => 'OTT-20260926-0001', + queueGeneration: () => queueGeneration, + serverInfo: (k) => serverListLoaded + ? (server[k] ?? (onList: false, checkedAt: null)) + : (onList: false, checkedAt: null), + cache: cache, + budget: budget, + enqueue: (a, ctx) { + final o = enqueueOverride; + if (o != null) return o(a, ctx); + enqueued.add((answer: a, ctx: ctx)); + return Future.value(true); + }, + onCacheStamped: () { + cacheSaves++; + savedCache = cache.toJson(); + }, + nowSec: nowSec, + currentPosition: () => position, + stillWanted: () => wanted, + onActiveChanged: badge.add, + onLogged: logged.add, + pendingRestores: pendingRestores, + knownNonContacts: knownNonContacts, + cannotAskNonContacts: () => cannotAskNonContacts, + ); + } +} + +final DateTime _t0 = DateTime(2026, 9, 26, 10, 0, 0); + +void _run(void Function(FakeAsync async, _Harness h) body) { + fakeAsync((async) { + final h = _Harness(); + body(async, h); + async.elapse(const Duration(minutes: 2)); + async.flushMicrotasks(); + }, initialTime: _t0); +} + +/// Runs [runner] to completion on the fake clock and returns once done. +bool Function() _start(FakeAsync async, ScopeRunner runner, + List found, + {Future? discPersisted}) { + var done = false; + runner + .run(found, discPersisted: discPersisted ?? Future.value()) + .then((_) => done = true); + async.flushMicrotasks(); + return () => done; +} + +/// A point [meters] north of 45.0, -75.0. +({double lat, double lon}) _north(double meters) { + // Search the latitude offset against the same distance function the runner + // uses, so 299 m and 301 m are really on either side of 300 m. + var lo = 0.0, hi = 0.01; + for (var i = 0; i < 60; i++) { + final mid = (lo + hi) / 2; + final d = Geolocator.distanceBetween(45.0, -75.0, 45.0 + mid, -75.0); + if (d < meters) { + lo = mid; + } else { + hi = mid; + } + } + return (lat: 45.0 + hi, lon: -75.0); +} + +void main() { + group('choosing', () { + test('at most 3 asks, one at a time, strongest RSSI first', () { + _run((async, h) { + final found = [ + _cand(0x11, rssi: -90), + _cand(0x22, rssi: -60), + _cand(0x33, rssi: -70), + _cand(0x44, rssi: -100), + _cand(0x55, rssi: -80), + ]; + final done = _start(async, h.build(), found); + async.elapse(const Duration(seconds: 30)); + expect(done(), isTrue); + expect(h.radio.overlaps, isEmpty); + expect(h.radio.asks.map((a) => a.key), + [_key(0x22), _key(0x33), _key(0x55)]); + }); + }); + + test('SNR then key break RSSI ties', () { + _run((async, h) { + final found = [ + _cand(0x33, rssi: -70, snr: 2), + _cand(0x22, rssi: -70, snr: 8), + _cand(0x55, rssi: -70, snr: 2), + _cand(0x11, rssi: -70, snr: 2), + ]; + _start(async, h.build(), found); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.map((a) => a.key), + [_key(0x22), _key(0x11), _key(0x33)]); + }); + }); + + test('five found with the two strongest answered recently: 3rd to 5th asked', + () { + _run((async, h) { + h.cache.recordAnswer(_key(0x11), h.nowSec() - 86400); + h.server[_key(0x22)] = (onList: true, checkedAt: h.nowSec() - 3600); + final found = [ + _cand(0x11, rssi: -50), + _cand(0x22, rssi: -55), + _cand(0x33, rssi: -60), + _cand(0x44, rssi: -65), + _cand(0x55, rssi: -70), + ]; + _start(async, h.build(), found); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.map((a) => a.key), + [_key(0x33), _key(0x44), _key(0x55)]); + }); + }); + + test('due: fresh server stamp and phone answer skipped, ghost asked', () { + _run((async, h) { + h.server[_key(0x11)] = (onList: true, checkedAt: h.nowSec() - 60); + h.cache.recordAnswer(_key(0x22), h.nowSec() - 60); + h.server[_key(0x44)] = + (onList: true, checkedAt: h.nowSec() - 30 * 86400); + // 0x33 is a ghost: not on the server list at all. + _start(async, h.build(), [ + _cand(0x11, rssi: -50), + _cand(0x22, rssi: -51), + _cand(0x33, rssi: -52), + _cand(0x44, rssi: -53), + ]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.map((a) => a.key), [_key(0x33), _key(0x44)]); + }); + }); + + test('a key whose answer is still being written is not asked', () { + _run((async, h) { + h.cache.pendingPersist.add(_key(0x11)); + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.map((a) => a.key), [_key(0x22)]); + }); + }); + + test('pendingPersist at 32 stops the runner before asking', () { + _run((async, h) { + for (var i = 0; i < ScopeQueryCache.maxPendingPersist; i++) { + h.cache.pendingPersist.add(_key(0x80 + i)); + } + final done = _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + }); + }); + + test('DISC items not persisted within 2 s: the runner ends, nothing asked', + () { + _run((async, h) { + final done = _start(async, h.build(), [_cand(0x11)], + discPersisted: Completer().future); + async.elapse(const Duration(milliseconds: 1999)); + expect(done(), isFalse); + async.elapse(const Duration(milliseconds: 2)); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + expect(h.badge, isEmpty); + }); + }); + + test('a DISC write that failed ends the runner, nothing asked', () { + _run((async, h) { + final done = _start(async, h.build(), [_cand(0x11)], + discPersisted: Future.error(StateError('disk'))); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + }); + }); + + test('DISC items persisted after 1 s: asks go ahead', () { + _run((async, h) { + final persisted = Completer(); + _start(async, h.build(), [_cand(0x11)], + discPersisted: persisted.future); + async.elapse(const Duration(seconds: 1)); + expect(h.radio.acquires, 0); + persisted.complete(); + async.elapse(const Duration(seconds: 10)); + expect(h.radio.asks, hasLength(1)); + }); + }); + }); + + group('waits', () { + test('each ask waits its own reply time plus 2 s, capped at 7 s', () { + _run((async, h) { + _start(async, h.build(), [ + _cand(0x11, rssi: -50, reply: const Duration(milliseconds: 400)), + _cand(0x22, rssi: -60, reply: const Duration(seconds: 3)), + ]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.map((a) => a.answerWait), [ + const Duration(milliseconds: 2400), + const Duration(seconds: 5), + ]); + }); + _run((async, h) { + _start(async, h.build(), + [_cand(0x11, reply: const Duration(seconds: 6))]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.single.answerWait, const Duration(seconds: 7)); + }); + }); + + test('unknown reply time passes no wait: the radio estimate plus 1 s', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + const _Script(est: Duration(milliseconds: 1500)); + _start(async, h.build(), [_cand(0x11, reply: null)]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks.single.answerWait, isNull); + expect(h.radio.asks.single.wait, const Duration(milliseconds: 2500)); + }); + }); + + test('an answer ends the wait early and the badge clears then', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + _Script.answers('Ottawa', after: const Duration(milliseconds: 300)); + final done = _start(async, h.build(), + [_cand(0x11, reply: const Duration(seconds: 6))]); + expect(h.badge, [true]); + async.elapse(const Duration(milliseconds: 399)); + expect(h.badge, [true]); + async.elapse(const Duration(milliseconds: 2)); + expect(h.badge, [true, false]); + async.flushMicrotasks(); + expect(done(), isTrue); + }); + }); + }); + + group('hard stop', () { + test('an ask that would run past the hard stop is not started', () { + _run((async, h) { + // Admission 3 s + lease 4 s + 2.4 s wait = 9.4 s: the first fits + // in 11 s, the second (due 2.5 s later, at 11.9 s) does not. + final done = _start( + async, + h.build(hardStop: clock.now().add(const Duration(seconds: 11))), + [_cand(0x11, rssi: -50), _cand(0x22, rssi: -60)]); + async.elapse(const Duration(seconds: 11)); + expect(done(), isTrue); + expect(h.radio.asks.map((a) => a.key), [_key(0x11)]); + }); + }); + + test('an unknown reply time reserves the full 7 s', () { + _run((async, h) { + final done = _start( + async, + h.build(hardStop: clock.now().add(const Duration(seconds: 13))), + [_cand(0x11, reply: null)]); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + }); + _run((async, h) { + _start( + async, + h.build(hardStop: clock.now().add(const Duration(seconds: 14))), + [_cand(0x11, reply: null)]); + async.elapse(const Duration(seconds: 14)); + expect(h.radio.asks, hasLength(1)); + }); + }); + + test('the hard-stop timer cancels a runner mid-ask', () { + _run((async, h) { + // A radio slower than any real lease, so the ask is still running + // when the hard stop arrives. + h.radio.scripts[_key(0x11)] = + const _Script(leaseTime: Duration(seconds: 9)); + final done = _start( + async, + h.build(hardStop: clock.now().add(const Duration(seconds: 10))), + [_cand(0x11)]); + async.elapse(const Duration(milliseconds: 9999)); + expect(done(), isFalse); + async.elapse(const Duration(seconds: 10)); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.cancel.isCancelled, isTrue); + expect(h.badge.last, isFalse); + }); + }); + + test('the runner never outlives 30 s, whatever hard stop it is given', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + const _Script(leaseTime: Duration(seconds: 40)); + final done = _start( + async, h.build(hardStop: clock.now().add(const Duration(minutes: 5))), + [_cand(0x11)]); + async.elapse(const Duration(milliseconds: 29999)); + expect(done(), isFalse); + async.elapse(const Duration(milliseconds: 1)); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.cancel.isCancelled, isTrue); + }); + }); + }); + + group('distance gate', () { + void check(double meters, int expectedAsks) { + _run((async, h) { + final runner = h.build(); + _start(async, runner, [_cand(0x11, rssi: -50), _cand(0x22)]); + // Move after the first ask has started. + h.position = _north(meters); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks, hasLength(expectedAsks), reason: '$meters m'); + }); + } + + test('301 m before the 2nd ask stops the runner', () => check(301, 1)); + test('299 m continues', () => check(299, 2)); + test('a null position does not block', () { + _run((async, h) { + h.position = null; + _start(async, h.build(), [_cand(0x11), _cand(0x22)]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks, hasLength(2)); + }); + }); + }); + + group('outcomes', () { + test('an answer with names: one enqueue at the discovery point, stamped', + () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa,*,west'); + h.position = (lat: 45.1, lon: -75.2); + _start(async, h.build(), [_cand(0x11, lat: 45.1, lon: -75.2)]); + async.elapse(const Duration(milliseconds: 100)); + final answerAt = clock.now().add(const Duration(milliseconds: 300)); + async.elapse(const Duration(seconds: 10)); + final e = h.enqueued.single; + expect(e.answer.keyHex, _key(0x11)); + expect(e.answer.scopes, ['Ottawa', '*', 'west']); + expect(e.answer.lat, 45.1); + expect(e.answer.lon, -75.2); + expect(e.answer.timestampSec, answerAt.millisecondsSinceEpoch ~/ 1000); + expect(e.ctx.deviceKey, 'DEVICEKEY'); + expect(e.ctx.sessionId, 'OTT-20260926-0001'); + expect(e.ctx.queueGeneration, 1); + expect(e.ctx.budgetHour, e.answer.timestampSec ~/ 3600); + expect(h.cache[_key(0x11)]?.answeredAt, e.answer.timestampSec); + expect(h.cacheSaves, 1); + expect(h.logged.single.outcome, ScopeLogOutcome.answered); + expect(h.logged.single.scopes, ['Ottawa', '*', 'west']); + expect(h.logged.single.latitude, 45.1); + }); + }); + + test('an empty answer is enqueued as []', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = _Script.answers(''); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.enqueued.single.answer.scopes, isEmpty); + expect(h.cache[_key(0x11)], isNotNull); + }); + }); + + test('a timeout logs no response, stamps nothing, and holds the repeater', + () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.noResponse); + expect(h.enqueued, isEmpty); + expect(h.cache[_key(0x11)], isNull); + // A no-answer never stamps an answer, but it does start a hold: the + // very next sweep must not re-ask it. + expect(h.cache.heldUntil(_key(0x11)), isNotNull); + final second = ScopeCancelToken(); + _start(async, h.build(token: second), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.radio.asks, hasLength(1), + reason: 'held: the second sweep must not re-ask it'); + }); + }); + + test('a first miss holds for 1 minute: not re-asked one second short, ' + 'asked again exactly at the deadline when heard stronger', () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + final heldUntil = h.cache.heldUntil(_key(0x11)); + expect(heldUntil, isNotNull); + + // One second short of the deadline: still held, however strong. A + // held sweep resolves on microtasks alone (nothing to ask), so this + // must not itself advance the clock any further than the boundary + // being tested. + async.elapse(Duration(seconds: heldUntil! - h.nowSec() - 1)); + _start(async, h.build(token: ScopeCancelToken()), + [_cand(0x11, rssi: -50)]); + expect(h.radio.asks, hasLength(1), + reason: 'one second short of the 1 minute deadline'); + + // The deadline itself, heard 1 dB stronger: due again. + async.elapse(const Duration(seconds: 1)); + expect(h.nowSec(), heldUntil); + _start(async, h.build(token: ScopeCancelToken()), + [_cand(0x11, rssi: -79)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks, hasLength(2), + reason: 'at the deadline and 1 dB stronger: due again'); + }); + }); + + test('after the hold, a repeater heard no stronger waits out the full ' + '30 minutes from the miss', () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + final missAt = h.nowSec(); + final heldUntil = h.cache.heldUntil(_key(0x11))!; + + async.elapse(Duration(seconds: heldUntil - h.nowSec())); + _start(async, h.build(token: ScopeCancelToken()), + [_cand(0x11, rssi: -80)]); + expect(h.radio.asks, hasLength(1), + reason: 'no stronger: not worth another ask yet'); + + // missAt is when the timeout landed; the hold was stamped a moment + // before that, so this is at or just past 30 minutes from the miss. + async.elapse(Duration(seconds: missAt + 30 * 60 - h.nowSec())); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks, hasLength(2), + reason: '30 minutes after the miss the signal rule lapses'); + }); + }); + + test('a second consecutive miss holds for 5 minutes', () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + final firstHeldUntil = h.cache.heldUntil(_key(0x11))!; + + // Wait out the first hold exactly, then miss again. + async.elapse(Duration(seconds: firstHeldUntil - h.nowSec())); + _start(async, h.build(token: ScopeCancelToken()), + [_cand(0x11, rssi: -70)]); + async.elapse(const Duration(seconds: 10)); + final secondHeldUntil = h.cache.heldUntil(_key(0x11))!; + expect(h.radio.asks, hasLength(2)); + // Both asks take the same fixed lease + answer-wait time to miss, so + // the gap between the two deadlines is ~5 minutes if the second + // hold stepped up, ~1 minute if it did not. + final gap = secondHeldUntil - firstHeldUntil; + expect(gap, greaterThan(4 * 60), + reason: 'the second hold must be 5 minutes, not another 1'); + expect(gap, lessThan(6 * 60)); + }); + }); + + test('an answer clears the hold: the same repeater is due again at once ' + 'once it finally answers', () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.cache.heldUntil(_key(0x11)), isNotNull); + + // Wait out the hold, then let the second, stronger ask answer. + final heldUntil = h.cache.heldUntil(_key(0x11))!; + async.elapse(Duration(seconds: heldUntil - h.nowSec())); + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(token: ScopeCancelToken()), + [_cand(0x11, rssi: -70)]); + async.elapse(const Duration(seconds: 10)); + expect(h.cache[_key(0x11)], isNotNull); + expect(h.cache.heldUntil(_key(0x11)), isNull, + reason: 'an answer clears the hold'); + }); + }); + + test('flooded, radio error, malformed and aborted outcomes never hold ' + 'the repeater', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = const _Script(inLease: ScopeFlooded()); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.cache.heldUntil(_key(0x11)), isNull); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks.where((a) => a.key == _key(0x11)).length, 2, + reason: 'flooded never holds: asked again at once'); + + h.radio.scripts[_key(0x22)] = + const _Script(inLease: ScopeRadioError(3)); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x22)]); + async.elapse(const Duration(seconds: 5)); + expect(h.cache.heldUntil(_key(0x22)), isNull); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x22)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks.where((a) => a.key == _key(0x22)).length, 2, + reason: 'a radio error never holds: asked again at once'); + + h.radio.scripts[_key(0x33)] = const _Script( + answerAfter: Duration(milliseconds: 300), body: [1, 2]); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x33)]); + async.elapse(const Duration(seconds: 5)); + expect(h.cache.heldUntil(_key(0x33)), isNull); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x33)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks.where((a) => a.key == _key(0x33)).length, 2, + reason: 'a malformed answer never holds: asked again at once'); + + h.radio.scripts[_key(0x44)] = const _Script(inLease: ScopeAborted()); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x44)]); + async.elapse(const Duration(seconds: 5)); + expect(h.cache.heldUntil(_key(0x44)), isNull); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x44)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.asks.where((a) => a.key == _key(0x44)).length, 2, + reason: 'an aborted ask never holds: asked again at once'); + }); + }); + + test('a malformed answer logs unreadable, stamps nothing', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = const _Script( + answerAfter: Duration(milliseconds: 300), body: [1, 2]); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.malformed); + expect(h.enqueued, isEmpty); + expect(h.cache[_key(0x11)], isNull); + }); + }); + + test('a malformed answer never parsed OK: it does NOT clear an existing ' + 'hold', () { + _run((async, h) { + h.cache.recordNoAnswer(_key(0x11), h.nowSec()); + final heldBefore = h.cache.heldUntil(_key(0x11))!; + // Wait out the hold so the repeater is due again for this ask; + // otherwise it would never be chosen at all, malformed or not. + async.elapse(Duration(seconds: heldBefore - h.nowSec())); + h.radio.scripts[_key(0x11)] = const _Script( + answerAfter: Duration(milliseconds: 300), body: [1, 2]); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.malformed); + expect(h.cache.heldUntil(_key(0x11)), heldBefore, + reason: 'malformed never parsed, so the (now expired) hold is ' + 'left exactly as it was'); + }); + }); + + test('flood and radio error are logged and the next repeater is asked', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = const _Script(inLease: ScopeFlooded()); + h.radio.scripts[_key(0x22)] = + const _Script(inLease: ScopeRadioError(3)); + _start(async, h.build(), + [_cand(0x11, rssi: -50), _cand(0x22, rssi: -60), _cand(0x33)]); + async.elapse(const Duration(seconds: 30)); + expect(h.logged.map((e) => e.outcome), [ + ScopeLogOutcome.flooded, + ScopeLogOutcome.radioError, + ScopeLogOutcome.noResponse, + ]); + expect(h.cache[_key(0x11)], isNull); + expect(h.cache[_key(0x22)], isNull); + }); + }); + + test('a local failure ends the runner, nothing logged or stamped', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + const _Script(inLease: ScopeLocalFailure('hold_cap')); + final done = + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(seconds: 30)); + expect(done(), isTrue); + expect(h.radio.asks, hasLength(1)); + expect(h.logged, isEmpty); + expect(h.badge, [true, false]); + }); + }); + + test('a refused lease ends the runner for this sweep', () { + _run((async, h) { + h.radio.refuse = true; + final done = + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(seconds: 5)); + expect(done(), isTrue); + expect(h.radio.acquires, 1); + expect(h.logged, isEmpty); + expect(h.badge, [true, false]); + }); + }); + + test('stillWanted false stops before the next ask', () { + _run((async, h) { + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + h.wanted = false; + async.elapse(const Duration(seconds: 30)); + expect(h.radio.asks, hasLength(1)); + }); + }); + + test('run never throws: a throwing dependency is logged and ends it', () { + _run((async, h) { + final runner = ScopeRunner( + radio: h.radio, + cancel: h.cancel, + hardStop: clock.now().add(const Duration(seconds: 30)), + refreshDays: () => throw StateError('boom'), + deviceKey: () => 'D', + serverInfo: (_) => (onList: false, checkedAt: null), + cache: h.cache, + budget: h.budget, + enqueue: (_, __) async => true, + nowSec: h.nowSec, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: h.badge.add, + onLogged: h.logged.add, + pendingRestores: h.pendingRestores, + ); + final done = _start(async, runner, [_cand(0x11)]); + async.flushMicrotasks(); + expect(done(), isTrue); + }); + }); + }); + + group('budget', () { + test('exhausted before asking: nothing asked', () { + _run((async, h) { + for (var i = 0; i < ScopeHourlyBudget.perHour; i++) { + h.budget.tryConsume('DEVICEKEY', h.nowSec()); + } + final done = _start(async, h.build(), [_cand(0x11)]); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + }); + }); + + test('full on arrival: withheld, not enqueued, not stamped', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + // Another answer fills the hour while this one is in flight. + async.elapse(const Duration(milliseconds: 200)); + for (var i = 0; i < ScopeHourlyBudget.perHour; i++) { + h.budget.tryConsume('DEVICEKEY', h.nowSec()); + } + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.withheldHourlyCap); + expect(h.enqueued, isEmpty); + expect(h.cache[_key(0x11)], isNull); + }); + }); + + test('full on arrival: withheld, but the parsed answer still clears an ' + 'existing hold', () { + _run((async, h) { + h.cache.recordNoAnswer(_key(0x11), h.nowSec()); + final heldUntil = h.cache.heldUntil(_key(0x11))!; + // Wait out the hold so the repeater is due again for this ask. + async.elapse(Duration(seconds: heldUntil - h.nowSec())); + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(milliseconds: 200)); + for (var i = 0; i < ScopeHourlyBudget.perHour; i++) { + h.budget.tryConsume('DEVICEKEY', h.nowSec()); + } + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.withheldHourlyCap); + expect(h.cache.heldUntil(_key(0x11)), isNull, + reason: 'it answered and parsed OK, whatever the hourly cap did'); + }); + }); + + test('a failed reservation write drops the answer, not stamped', () { + _run((async, h) { + h.budgetSaveFails = true; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.enqueued, isEmpty); + expect(h.cache[_key(0x11)], isNull); + expect(h.cache.pendingPersist, isEmpty); + }); + }); + + test('a failed reservation write drops the answer, but still clears an ' + 'existing hold (the repeater proved it is reachable)', () { + _run((async, h) { + h.cache.recordNoAnswer(_key(0x11), h.nowSec()); + final heldUntil = h.cache.heldUntil(_key(0x11))!; + // Wait out the hold so the repeater is due again for this ask. + async.elapse(Duration(seconds: heldUntil - h.nowSec())); + h.budgetSaveFails = true; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.enqueued, isEmpty); + expect(h.cache[_key(0x11)], isNull, + reason: 'the durable answer stamp still needs persistence'); + expect(h.cache.heldUntil(_key(0x11)), isNull, + reason: 'a failed save must not leave the miss count in place'); + }); + }); + + test('a stalled reservation write does not hold the runner', () { + _run((async, h) { + h.budgetSaveGate = Completer(); + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + final done = + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(seconds: 30)); + expect(done(), isTrue); + expect(h.radio.asks, hasLength(2)); + expect(h.enqueued, isEmpty); + expect(h.cache.pendingPersist, {_key(0x11)}); + h.budgetSaveGate!.complete(); + async.flushMicrotasks(); + expect(h.enqueued, hasLength(1)); + expect(h.cache.pendingPersist, isEmpty); + }); + }); + }); + + group('persistence', () { + test('enqueue false: no stamp', () { + _run((async, h) { + h.enqueueOverride = (_, __) async => false; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.cache[_key(0x11)], isNull); + expect(h.cacheSaves, 0); + expect(h.cache.pendingPersist, isEmpty); + }); + }); + + test('enqueue false: still clears an existing hold', () { + _run((async, h) { + h.cache.recordNoAnswer(_key(0x11), h.nowSec()); + final heldUntil = h.cache.heldUntil(_key(0x11))!; + // Wait out the hold so the repeater is due again for this ask. + async.elapse(Duration(seconds: heldUntil - h.nowSec())); + h.enqueueOverride = (_, __) async => false; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.cache[_key(0x11)], isNull); + expect(h.cache.heldUntil(_key(0x11)), isNull, + reason: 'a refused enqueue must not leave the miss count ' + 'in place'); + }); + }); + + test( + 'an enqueue that never completes: not stamped, not re-asked while ' + 'pending, stamped once when it lands', () { + _run((async, h) { + final gate = Completer(); + h.enqueueOverride = (_, __) => gate.future; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.cache[_key(0x11)], isNull); + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.radio.asks, hasLength(1), + reason: 'a pending answer keeps its repeater off the list'); + gate.complete(true); + async.flushMicrotasks(); + expect(h.cache[_key(0x11)], isNotNull); + expect(h.cacheSaves, 1); + }); + }); + + test('a queue cleared between the answer and the enqueue drops it', () { + _run((async, h) { + final hold = Completer(); + h.budgetSaveGate = hold; + h.enqueueOverride = (a, ctx) async => + ctx.queueGeneration == h.queueGeneration; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 1)); + h.queueGeneration++; // the queue is cleared + hold.complete(); + async.elapse(const Duration(seconds: 10)); + expect(h.cache[_key(0x11)], isNull); + }); + }); + + test('a queue cleared during the answer wait: refused, nothing stamped', + () { + _run((async, h) { + // The real queue refuses a stale generation. + h.enqueueOverride = (a, ctx) async => + ctx.queueGeneration == h.queueGeneration; + h.radio.scripts[_key(0x11)] = + _Script.answers('Ottawa', after: const Duration(seconds: 1)); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(milliseconds: 500)); // in the wait + h.queueGeneration++; // the queue (and the sweep's DISC) is cleared + async.elapse(const Duration(seconds: 10)); + expect(h.logged.single.outcome, ScopeLogOutcome.answered); + expect(h.cache[_key(0x11)], isNull, + reason: 'the answer belongs to the sweep that was cleared'); + expect(h.cacheSaves, 0); + }); + }); + + test('every answer of a sweep carries the generation from its start', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = _Script.answers('A'); + h.radio.scripts[_key(0x22)] = _Script.answers('B'); + _start(async, h.build(), [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(milliseconds: 50)); + h.queueGeneration = 7; + async.elapse(const Duration(seconds: 20)); + expect(h.enqueued.map((e) => e.ctx.queueGeneration), [1, 1]); + }); + }); + + test( + 'an enqueue landing after a newer runner started stamps the cache and ' + 'touches nothing else', () { + _run((async, h) { + final gate = Completer(); + h.enqueueOverride = (_, __) => gate.future; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + final first = h.build(); + _start(async, first, [_cand(0x11)]); + async.elapse(const Duration(seconds: 1)); + first.cancel('next discovery'); + async.flushMicrotasks(); + final badgeBefore = List.of(h.badge); + final token2 = ScopeCancelToken(); + final second = h.build(token: token2); + _start(async, second, [_cand(0x22)]); + expect(h.badge.last, isTrue); + gate.complete(true); + async.flushMicrotasks(); + expect(h.cache[_key(0x11)], isNotNull); + expect(h.badge.last, isTrue, + reason: 'the newer runner still owns the badge'); + expect(h.badge.length, badgeBefore.length + 1); + expect(token2.isCancelled, isFalse); + }); + }); + + test('a late answer stamp survives a cache reload', () { + _run((async, h) { + final gate = Completer(); + h.enqueueOverride = (_, __) => gate.future; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + final done = _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(done(), isTrue); + gate.complete(true); + async.flushMicrotasks(); + final reloaded = ScopeQueryCache.fromJson(h.savedCache); + expect( + isScopeQueryDue( + onServerList: false, + serverCheckedAt: null, + phone: reloaded[_key(0x11)], + persistPending: false, + nowSec: h.nowSec(), + refreshDays: 14), + isFalse); + }); + }); + }); + + group('cancellation', () { + test('cancel mid-lease: nothing more written, badge clears, record kept', + () { + _run((async, h) { + final borrowed = ContactRecord.newRepeater( + publicKey: Uint8List.fromList(List.filled(32, 0x11)), + name: 'R', + lat: 1, + lon: 2, + nowSecs: 5); + h.radio.scripts[_key(0x11)] = _Script( + leaseTime: const Duration(seconds: 2), borrow: borrowed); + final runner = h.build(); + final done = + _start(async, runner, [_cand(0x11, rssi: -50), _cand(0x22)]); + async.elapse(const Duration(milliseconds: 500)); + runner.cancel('stop'); + expect(h.badge.last, isFalse, reason: 'cleared at once'); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.radio.busy, isFalse); + final framesAtCancel = List.of(h.radio.frames); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.frames, framesAtCancel); + expect(h.pendingRestores.single.publicKey, borrowed.publicKey); + + // The next runner on the same connection restores it first. + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x33)]); + async.elapse(const Duration(seconds: 30)); + expect(h.radio.frames.sublist(framesAtCancel.length), + ['restore:11111111', 'ask:33333333']); + expect(h.pendingRestores, isEmpty); + }); + }); + + test('cancel mid-wait: the late answer is ignored', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + _Script.answers('Ottawa', after: const Duration(seconds: 3)); + final runner = h.build(); + _start(async, runner, + [_cand(0x11, reply: const Duration(seconds: 5))]); + async.elapse(const Duration(seconds: 1)); + runner.cancel('next discovery'); + async.elapse(const Duration(seconds: 10)); + expect(h.enqueued, isEmpty); + expect(h.logged, isEmpty); + expect(h.badge, [true, false]); + }); + }); + + test('a cancelled runner never flips a newer runner\'s badge', () { + _run((async, h) { + final first = h.build(); + var current = first; + first.isCurrent = () => identical(current, first); + _start(async, first, [_cand(0x11, reply: const Duration(seconds: 5))]); + async.elapse(const Duration(milliseconds: 500)); + first.cancel('next discovery'); + final second = h.build(token: ScopeCancelToken()); + current = second; + second.isCurrent = () => identical(current, second); + _start(async, second, [_cand(0x22, reply: const Duration(seconds: 5))]); + final badgeAfterSecondStart = List.of(h.badge); + expect(badgeAfterSecondStart.last, isTrue); + async.elapse(const Duration(milliseconds: 500)); + expect(h.badge, badgeAfterSecondStart); + }); + }); + + test('an already cancelled runner asks nothing', () { + _run((async, h) { + final runner = h.build(); + runner.cancel('stop'); + final done = _start(async, runner, [_cand(0x11)]); + async.flushMicrotasks(); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + expect(h.badge, isEmpty); + }); + }); + }); + + group('contact table full', () { + test('a non-contact table-full radio error is logged distinctly and ' + 'remembered', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = const _Script( + inLease: ScopeRadioError(3, nonContactTableFull: true)); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.logged.single.outcome, ScopeLogOutcome.radioContactsFull); + }); + }); + + test('a saved contact\'s table-full radio error is logged as the ' + 'ordinary radio error', () { + _run((async, h) { + h.radio.scripts[_key(0x11)] = + const _Script(inLease: ScopeRadioError(3)); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.logged.single.outcome, ScopeLogOutcome.radioError); + }); + }); + + test('with the flag set, a known non-contact is skipped with no lease', + () { + _run((async, h) { + h.cannotAskNonContacts = true; + h.knownNonContacts.add(_key(0x11)); + final done = _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(done(), isTrue); + expect(h.radio.acquires, 0); + expect(h.radio.frames, isEmpty); + expect(h.logged, isEmpty); + }); + }); + + test('with the flag set, an unknown repeater is still looked up, and a ' + 'refusal is remembered but never logged', () { + _run((async, h) { + h.cannotAskNonContacts = true; + h.radio.scripts[_key(0x11)] = + const _Script(inLease: ScopeNonContactRefused()); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.acquires, 1, reason: 'the lookup is still taken'); + expect(h.logged, isEmpty, + reason: 'never shown in the log tab, debug log only'); + expect(h.knownNonContacts, contains(_key(0x11))); + + // The next sweep skips it without a lease. + final acquiresBefore = h.radio.acquires; + _start(async, h.build(token: ScopeCancelToken()), [_cand(0x11)]); + async.elapse(const Duration(seconds: 5)); + expect(h.radio.acquires, acquiresBefore, + reason: 'now known, so no lease this time'); + }); + }); + + test('the flag alone (no known-non-contact entry) does not block an ask', + () { + _run((async, h) { + h.cannotAskNonContacts = true; + h.radio.scripts[_key(0x11)] = _Script.answers('Ottawa'); + _start(async, h.build(), [_cand(0x11)]); + async.elapse(const Duration(seconds: 10)); + expect(h.enqueued.single.answer.scopes, ['Ottawa']); + }); + }); + + test( + 'three blocked strongest repeaters do not starve a weaker saved ' + 'contact out of the top 3', () { + _run((async, h) { + h.cannotAskNonContacts = true; + h.knownNonContacts.addAll([_key(0x11), _key(0x22), _key(0x33)]); + h.radio.scripts[_key(0x44)] = _Script.answers('Ottawa'); + final found = [ + _cand(0x11, rssi: -50), + _cand(0x22, rssi: -55), + _cand(0x33, rssi: -60), + _cand(0x44, rssi: -65), + ]; + _start(async, h.build(), found); + async.elapse(const Duration(seconds: 30)); + // The three known non-contacts are filtered out before the top-3 + // cut, not skipped after it, so the 4th (weaker but askable) + // repeater gets a slot instead of being starved forever. + expect(h.radio.asks.map((a) => a.key), [_key(0x44)]); + expect(h.radio.acquires, 1); + }); + }); + }); + + group('on a real connection', () { + ScopeRunner realRunner(_Harness h, MeshCoreConnection conn, + {ScopeCancelToken? token}) => + ScopeRunner( + radio: MeshCoreScopeRadio(conn), + cancel: token ?? h.cancel, + hardStop: clock.now().add(const Duration(seconds: 30)), + refreshDays: () => 14, + deviceKey: () => 'DEVICEKEY', + serverInfo: (_) => (onList: false, checkedAt: null), + cache: h.cache, + budget: h.budget, + enqueue: (a, ctx) async { + h.enqueued.add((answer: a, ctx: ctx)); + return true; + }, + nowSec: h.nowSec, + currentPosition: () => null, + stillWanted: () => true, + onActiveChanged: h.badge.add, + onLogged: h.logged.add, + pendingRestores: h.pendingRestores, + ); + + test('a TX issued during the lease goes out when it releases, within 4 s', + () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + final h = _Harness(); + realRunner(h, conn) + .run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + expect(conn.isScopeLeaseActive, isTrue); + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) {}); + // The radio never answers the lookup: the lease runs out at 4 s. + async.elapse(const Duration(milliseconds: 3999)); + expect(radio.commands, isNot(contains(CommandCodes.sendChannelTxtMsg))); + async.elapse(const Duration(milliseconds: 1)); + expect(radio.commands, contains(CommandCodes.sendChannelTxtMsg)); + async.elapse(const Duration(seconds: 30)); + }); + }); + + test('a TX and a discovery during the answer wait go out at once', () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + final h = _Harness(); + realRunner(h, conn).run([_cand(0x11, reply: null)], + discPersisted: Future.value()); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(support.sentFrame(est: 1500)); + async.flushMicrotasks(); + expect(conn.isScopeLeaseActive, isFalse); + expect(conn.isScopeListenActive, isTrue); + final before = radio.writes.length; + conn.sendChannelTextMessage(0, 1, 0, 'MM:x').then((_) {}); + conn.sendDiscoveryRequest(); + async.flushMicrotasks(); + expect(radio.commands.sublist(before), + [CommandCodes.sendChannelTxtMsg, CommandCodes.sendControlData]); + // Unknown reply time: est 1.5 s + 1 s. + async.elapse(const Duration(milliseconds: 2499)); + expect(h.logged, isEmpty); + async.elapse(const Duration(milliseconds: 2)); + expect(h.logged.single.outcome, ScopeLogOutcome.noResponse); + async.elapse(const Duration(seconds: 30)); + }); + }); + + test('cancel during the lease releases the radio and writes nothing more', + () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + final h = _Harness(); + final runner = realRunner(h, conn); + runner.run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + expect(conn.isScopeLeaseActive, isTrue); + final written = radio.writes.length; + runner.cancel('stop'); + expect(conn.isScopeLeaseActive, isFalse, reason: 'released at once'); + expect(h.badge.last, isFalse); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.elapse(const Duration(seconds: 30)); + expect(radio.writes.length, written); + }); + }); + + test('cancel during the answer wait frees the slot', () { + support.onScopeClock(support.ScopeRadio.new, (async, radio, conn) { + final h = _Harness(); + final runner = realRunner(h, conn); + runner.run([_cand(0x11)], discPersisted: Future.value()); + async.flushMicrotasks(); + radio.emit([ResponseCodes.err, ErrorCodes.notFound]); + async.flushMicrotasks(); + radio.emit(support.sentFrame()); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isTrue); + runner.cancel('stop'); + async.flushMicrotasks(); + expect(conn.isScopeListenActive, isFalse); + expect(conn.hasPendingAdminCommand, isFalse); + radio.emit(support.answerPush(body: [1, 2, 3, 4, 0x41])); + async.elapse(const Duration(seconds: 30)); + expect(h.enqueued, isEmpty); + }); + }); + }); +} diff --git a/test/services/session_recovery_join_test.dart b/test/services/session_recovery_join_test.dart new file mode 100644 index 00000000..8beb495e --- /dev/null +++ b/test/services/session_recovery_join_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/services/session_recovery_join.dart'; + +/// A group handoff drains the queue under the old session. If that session +/// has lapsed, the drain's upload comes back session_expired and asks for a +/// recovery; handing it the handoff's own future deadlocked both (TX held for +/// good, the queue stuck uploading). The rule here is what prevents that. +void main() { + test('a handoff holding the slot answers every joiner superseded', () { + expect( + resolveSessionRecoveryJoin( + groupHandoffOwnsSlot: true, recoveryInFlight: true), + SessionRecoveryJoin.supersededByHandoff, + reason: 'the in-flight future is the handoff itself', + ); + expect( + resolveSessionRecoveryJoin( + groupHandoffOwnsSlot: true, recoveryInFlight: false), + SessionRecoveryJoin.supersededByHandoff, + reason: 'the flag outranks the slot, which is set a moment later', + ); + }); + + test('a running recovery is joined, otherwise one is started', () { + expect( + resolveSessionRecoveryJoin( + groupHandoffOwnsSlot: false, recoveryInFlight: true), + SessionRecoveryJoin.joinInFlight, + ); + expect( + resolveSessionRecoveryJoin( + groupHandoffOwnsSlot: false, recoveryInFlight: false), + SessionRecoveryJoin.startNew, + ); + }); + + group('sessionCheckWaitsForHandoff', () { + test('the check waits for a handoff that holds the slot', () { + expect( + sessionCheckWaitsForHandoff( + groupHandoffOwnsSlot: true, recoveryInFlight: true), + isTrue, + reason: 'the held id is null between the release and the mint, ' + 'which the check would read as "session has ended"', + ); + }); + + test('an ordinary recovery is not waited for', () { + expect( + sessionCheckWaitsForHandoff( + groupHandoffOwnsSlot: false, recoveryInFlight: true), + isFalse, + reason: 'it keeps the old id until its mint lands, and the check ' + 'joins it through session_expired', + ); + }); + + test('nothing in flight means nothing to wait for', () { + expect( + sessionCheckWaitsForHandoff( + groupHandoffOwnsSlot: false, recoveryInFlight: false), + isFalse, + ); + expect( + sessionCheckWaitsForHandoff( + groupHandoffOwnsSlot: true, recoveryInFlight: false), + isFalse, + reason: 'the slot is already clear, so the check runs at once', + ); + }); + }); +} diff --git a/test/services/status/android_notification_test.dart b/test/services/status/android_notification_test.dart index bf931f72..56d8ca54 100644 --- a/test/services/status/android_notification_test.dart +++ b/test/services/status/android_notification_test.dart @@ -36,4 +36,22 @@ void main() { expect(n.title, 'MeshMapper - Trace Mode'); expect(n.body, 'Trace: 3 | RX: 7 | Queue: 2'); }); + + test('connected with no mode running names the radio', () { + final n = androidConnectedNotificationContent(radioName: 'MeshCore-AB12'); + expect(n.title, 'MeshMapper - Connected'); + expect(n.body, 'Connected to MeshCore-AB12'); + }); + + test('connecting claims no connection and names no radio', () { + final n = androidConnectingNotificationContent(); + expect(n.title, 'MeshMapper - Connecting'); + expect(n.body, 'Connecting to your radio'); + }); + + test('the zone grace period says it is looking for a zone', () { + final n = androidZoneGraceNotificationContent(); + expect(n.title, 'MeshMapper - Outside zone'); + expect(n.body, 'Searching for a nearby zone'); + }); } diff --git a/test/services/watch/watch_geo_builder_test.dart b/test/services/watch/watch_geo_builder_test.dart index 476ca92f..cb6a5a82 100644 --- a/test/services/watch/watch_geo_builder_test.dart +++ b/test/services/watch/watch_geo_builder_test.dart @@ -7,6 +7,7 @@ import 'package:mesh_mapper/providers/app_state_provider.dart' import 'package:mesh_mapper/services/watch/watch_geo_builder.dart'; import 'package:mesh_mapper/services/watch/watch_models.dart'; import 'package:mesh_mapper/utils/ping_colors.dart'; +import 'package:mesh_mapper/utils/repeater_nicknames.dart'; TxPing _tx(DateTime at, {List heard = const []}) => TxPing( latitude: 47.6, @@ -556,6 +557,25 @@ void main() { ); expect(built.length, WatchWire.maxHeard); + expect(built.map((n) => n.id).toList(), ['A', 'B', 'C', 'E'], + reason: 'the RX row stays and the fourth ping row is the one cut'); + }); + + test('five ping rows and no RX slot keep the first four', () { + final built = WatchGeoBuilder.buildHeard( + top: const [ + (repeaterId: 'A', snr: 5, type: OverlayPingType.tx), + (repeaterId: 'B', snr: 4, type: OverlayPingType.tx), + (repeaterId: 'C', snr: 3, type: OverlayPingType.tx), + (repeaterId: 'D', snr: 2, type: OverlayPingType.tx), + (repeaterId: 'E', snr: 1, type: OverlayPingType.tx), + ], + repeaterByHex: const {}, + topAt: DateTime(2026, 8, 12), + rxAt: null, + ); + + expect(built.map((n) => n.id).toList(), ['A', 'B', 'C', 'D']); }); test('uppercases the hex id and resolves name plus distance', () { @@ -593,6 +613,47 @@ void main() { reason: 'a confidently wrong name is worse than none'); expect(built.single.distanceM, isNull); }); + + test('a nickname replaces the name only on the repeater it belongs to', () { + final keyedKey = '4E5D82AA'.padRight(64, '0'); + final capitol = _repeater( + id: '01', + hexId: keyedKey, + name: 'Capitol Hill', + lat: 47.61, + lon: -122.3); + final beacon = _repeater( + id: '02', + hexId: '77A1B0CC'.padRight(64, '0'), + name: 'Beacon Hill', + lat: 47.62, + lon: -122.3); + + final built = WatchGeoBuilder.buildHeard( + top: const [ + (repeaterId: '4E5D', snr: 8, type: OverlayPingType.tx), + (repeaterId: '77A1', snr: 6, type: OverlayPingType.tx), + (repeaterId: 'AB', snr: 4, type: OverlayPingType.tx), + ], + repeaterByHex: {'4E5D': capitol, '77A1': beacon}, + topAt: DateTime(2026, 8, 12), + rxAt: null, + lat: 47.6, + lon: -122.3, + nicknames: { + keyedKey: const RepeaterNickname( + nickname: 'Mell', name: 'Capitol Hill', hex: '4E5D'), + }, + ); + + expect(built[0].name, 'Mell'); + expect(built[0].distanceM, isNotNull, + reason: 'a nickname changes the label, never the match'); + expect(built[1].name, 'Beacon Hill', + reason: 'a repeater without a nickname keeps the server name'); + expect(built[2].name, isNull, + reason: 'an unresolved hash stays unnamed, nicknames or not'); + }); }); group('resolveRepeater', () { @@ -657,6 +718,98 @@ void main() { }); }); + group('resolveOverlayRow - identity first, then the display hash', () { + // Two repeaters sharing a leading byte, so the one-byte hash alone is + // genuinely ambiguous. + final capitol = _repeater( + id: '01', + hexId: '4E5D82AA', + name: 'Capitol Hill', + lat: 47.6, + lon: -122.3, + ); + final beacon = _repeater( + id: '02', + hexId: '4E99F1BB', + name: 'Beacon Hill', + lat: 47.5, + lon: -122.3, + ); + final other = _repeater( + id: '03', + hexId: '9C12D4EE', + name: 'Queen Anne', + lat: 47.7, + lon: -122.3, + ); + + test('the identity wins when the display hash is shared', () { + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '4E', + repeaters: [capitol, beacon], + hopBytes: 1, + ), + isNull, + reason: 'the hash alone is genuinely ambiguous', + ); + + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '4E', + identity: '4E99F1BB2233445566', + repeaters: [capitol, beacon], + hopBytes: 1, + )?.name, + 'Beacon Hill', + ); + }); + + test('a missing identity falls back to the display hash', () { + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '9c', + repeaters: [capitol, beacon, other], + hopBytes: 1, + )?.name, + 'Queen Anne', + reason: 'the display hash is matched case-insensitively', + ); + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '9C', + identity: '', + repeaters: [capitol, beacon, other], + hopBytes: 1, + )?.name, + 'Queen Anne', + reason: 'an empty identity is no identity', + ); + }); + + test('an identity that resolves to nothing falls back to the hash', () { + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '9C', + identity: 'FFFFFFFF0011', + repeaters: [capitol, beacon, other], + hopBytes: 1, + )?.name, + 'Queen Anne', + ); + expect( + WatchGeoBuilder.resolveOverlayRow( + displayId: '4E', + identity: 'FFFFFFFF0011', + repeaters: [capitol, beacon, other], + hopBytes: 1, + ), + isNull, + reason: 'the fallback keeps the uniqueness rule', + ); + }); + }); + group('resolveOverlayRepeaters — name from the identity the ping carried', () { // Two repeaters sharing a leading byte. With one hop byte the wrist shows diff --git a/test/utils/compact_count_test.dart b/test/utils/compact_count_test.dart new file mode 100644 index 00000000..ae4f1a5b --- /dev/null +++ b/test/utils/compact_count_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/compact_count.dart'; + +void main() { + group('formatCompactCount', () { + test('keeps counts under 1000 as they are', () { + expect(formatCompactCount(0), '0'); + expect(formatCompactCount(7), '7'); + expect(formatCompactCount(42), '42'); + expect(formatCompactCount(999), '999'); + }); + + test('shows one decimal from 1000 up to 9999', () { + expect(formatCompactCount(1000), '1.0k'); + expect(formatCompactCount(1049), '1.0k'); + expect(formatCompactCount(1400), '1.4k'); + expect(formatCompactCount(1499), '1.4k'); + expect(formatCompactCount(9999), '9.9k'); + }); + + test('drops the decimal from 10k', () { + expect(formatCompactCount(10000), '10k'); + expect(formatCompactCount(12345), '12k'); + expect(formatCompactCount(999999), '999k'); + }); + + test('switches to M from one million', () { + expect(formatCompactCount(1000000), '1.0M'); + expect(formatCompactCount(1234567), '1.2M'); + expect(formatCompactCount(9999999), '9.9M'); + expect(formatCompactCount(12345678), '12M'); + }); + + test('never rounds up past the real count', () { + // Rounding would show 10.0k for 9999 and 1.0M for 999999. + expect(formatCompactCount(9950), '9.9k'); + expect(formatCompactCount(999950), '999k'); + }); + + test('leaves a negative count alone', () { + expect(formatCompactCount(-5), '-5'); + }); + }); +} diff --git a/test/utils/coverage_refresh_test.dart b/test/utils/coverage_refresh_test.dart new file mode 100644 index 00000000..81fb7ec4 --- /dev/null +++ b/test/utils/coverage_refresh_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/api_queue_item.dart'; +import 'package:mesh_mapper/utils/coverage_refresh.dart'; + +/// After an upload the app asks the region server to re-render the tiles the +/// batch touched. DEFER and SCOPES change no tile, so a batch of nothing but +/// those arms no refresh and contributes no coordinates. +void main() { + const key = 'A3B2C1D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2'; + + ApiQueueItem disc(double lat) => ApiQueueItem.fromDisc( + latitude: lat, + longitude: -75.0, + repeaterId: 'A3', + nodeType: 'REPEATER', + localSnr: 1, + localRssi: -90, + remoteSnr: 1, + pubkeyFull: key, + timestamp: 1757400000, + externalAntenna: false, + ); + ApiQueueItem scopes(double lat) => ApiQueueItem.fromScopes( + publicKeyHex: key, scopes: ['*'], lat: lat, lon: -75.0, + timestamp: 1757400001); + ApiQueueItem defer(double lat) => ApiQueueItem.fromDefer( + latitude: lat, longitude: -75.0, timestamp: 1757400002, held: 'disc'); + + test('DEFER and SCOPES change no coverage, everything else does', () { + expect(changesCoverage('DEFER'), isFalse); + expect(changesCoverage('SCOPES'), isFalse); + for (final t in ['TX', 'RX', 'DISC', 'TRACE', 'DISC_DROP']) { + expect(changesCoverage(t), isTrue, reason: t); + } + }); + + test('a SCOPES-only batch arms nothing and adds no coordinates', () { + final r = coverageRefreshFor([scopes(45.1), scopes(45.2)], + alreadyPending: 0); + expect(r.armsRefresh, isFalse); + expect(r.coords, isEmpty); + }); + + test('a DISC beside its SCOPES and a DEFER contributes only its own fix', + () { + final r = coverageRefreshFor([disc(45.1), scopes(45.2), defer(45.3)], + alreadyPending: 0); + expect(r.armsRefresh, isTrue); + expect(r.coords, [ + [45.1, -75.0] + ]); + }); + + test('coordinates stop at the cap, counting what is already pending', () { + final r = coverageRefreshFor( + [for (var i = 0; i < 10; i++) disc(45.0 + i / 100)], + alreadyPending: 14); + expect(r.armsRefresh, isTrue); + expect(r.coords, hasLength(2)); + }); +} diff --git a/test/utils/debouncer_test.dart b/test/utils/debouncer_test.dart new file mode 100644 index 00000000..0480ec0a --- /dev/null +++ b/test/utils/debouncer_test.dart @@ -0,0 +1,61 @@ +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/debouncer.dart'; + +void main() { + const delay = Duration(milliseconds: 1500); + + test('a burst of changes ends in one call with the newest action', () { + fakeAsync((async) { + final d = Debouncer(delay); + final calls = []; + for (var i = 0; i < 10; i++) { + d.schedule(() => calls.add(i)); + async.elapse(const Duration(milliseconds: 100)); + } + expect(calls, isEmpty); + async.elapse(delay); + expect(calls, [9]); + expect(d.isPending, isFalse); + }); + }); + + test('each schedule restarts the wait', () { + fakeAsync((async) { + final d = Debouncer(delay); + var calls = 0; + d.schedule(() => calls++); + async.elapse(const Duration(milliseconds: 1400)); + d.schedule(() => calls++); + async.elapse(const Duration(milliseconds: 1400)); + expect(calls, 0); + async.elapse(const Duration(milliseconds: 100)); + expect(calls, 1); + }); + }); + + test('flush runs a pending action now, once', () { + fakeAsync((async) { + final d = Debouncer(delay); + var calls = 0; + d.schedule(() => calls++); + d.flush(); + expect(calls, 1); + async.elapse(delay * 2); + expect(calls, 1); + d.flush(); + expect(calls, 1); + }); + }); + + test('cancel drops the pending action', () { + fakeAsync((async) { + final d = Debouncer(delay); + var calls = 0; + d.schedule(() => calls++); + d.cancel(); + async.elapse(delay * 2); + expect(calls, 0); + }); + }); +} diff --git a/test/utils/gps_marker_colors_test.dart b/test/utils/gps_marker_colors_test.dart new file mode 100644 index 00000000..cc99d1c8 --- /dev/null +++ b/test/utils/gps_marker_colors_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/gps_marker_colors.dart'; + +const _styles = ['arrow', 'car', 'bike', 'boat', 'walk', 'dog', 'chomper']; + +void main() { + group('normalize', () { + test('keeps every known choice', () { + for (final choice in GpsMarkerColors.choices) { + expect(GpsMarkerColors.normalize(choice), choice); + } + }); + + test('reads null and unknown values as the default', () { + for (final value in [null, '', 'purple', 'Green']) { + expect(GpsMarkerColors.normalize(value), 'default', + reason: 'value $value'); + } + }); + }); + + group('forStyle', () { + test('the default keeps the colours the markers always had', () { + for (final style in _styles.where((s) => s != 'chomper')) { + final colors = GpsMarkerColors.forStyle(style, 'default'); + expect(colors.body, const Color(0xFF2196F3), reason: style); + expect(colors.shade, const Color(0xFF1565C0), reason: style); + expect(colors.light, const Color(0xFF64B5F6), reason: style); + } + expect(GpsMarkerColors.forStyle('chomper', 'default').body, + const Color(0xFF00BCD4)); + }); + + test('green applies to every style, Chomper included', () { + for (final style in _styles) { + expect(GpsMarkerColors.forStyle(style, 'green'), GpsMarkerColors.green, + reason: style); + } + }); + + test('an unknown choice paints the default', () { + expect(GpsMarkerColors.forStyle('car', 'purple'), GpsMarkerColors.blue); + expect( + GpsMarkerColors.forStyle('chomper', 'purple'), GpsMarkerColors.cyan); + }); + + test('green is darker than a bidirectional coverage square', () { + // The pale green coverage fill the marker most often sits on. + const bidir = Color(0xFF7EE094); + expect(GpsMarkerColors.green.body.computeLuminance(), + lessThan(bidir.computeLuminance() / 2)); + }); + + test('each palette has a darker shade and a lighter accent', () { + for (final colors in [ + GpsMarkerColors.blue, + GpsMarkerColors.cyan, + GpsMarkerColors.green, + ]) { + final body = colors.body.computeLuminance(); + expect(colors.shade.computeLuminance(), lessThan(body)); + expect(colors.light.computeLuminance(), greaterThan(body)); + } + }); + }); +} diff --git a/test/utils/marker_data_version_test.dart b/test/utils/marker_data_version_test.dart new file mode 100644 index 00000000..5ea59aec --- /dev/null +++ b/test/utils/marker_data_version_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/ping_data.dart'; +import 'package:mesh_mapper/utils/marker_data_version.dart'; + +TxPing _zeroEchoPing(int i) => TxPing( + latitude: 45.0 + i * 0.0001, + longitude: -75.0, + power: 22, + timestamp: DateTime.utc(2026, 10, 6).add(Duration(seconds: i)), + deviceId: 'dev', + ); + +void main() { + group('cappedListSignature', () { + test('a 501st zero-echo ping into a full FIFO changes the signature', () { + const cap = 500; + final pings = [for (var i = 0; i < cap; i++) _zeroEchoPing(i)]; + final before = cappedListSignature(pings); + + // What AppStateProvider does at the cap: append, evict the oldest. + pings.add(_zeroEchoPing(cap)); + pings.removeAt(0); + + expect(pings.length, cap); + expect(cappedListSignature(pings), isNot(before)); + }); + + test('newest-first lists (DISC, trace) also change at the cap', () { + const cap = 500; + final entries = [for (var i = 0; i < cap; i++) Object()]; + final before = cappedListSignature(entries); + + entries.insert(0, Object()); + entries.removeLast(); + + expect(cappedListSignature(entries), isNot(before)); + }); + + test('a pure eviction changes the signature', () { + final entries = [Object(), Object(), Object()]; + final before = cappedListSignature(entries); + entries.removeAt(0); + expect(cappedListSignature(entries), isNot(before)); + }); + + test('is stable when nothing changed', () { + final entries = [Object(), Object()]; + expect(cappedListSignature(entries), cappedListSignature(entries)); + expect(cappedListSignature(const []), 0); + }); + }); +} diff --git a/test/utils/mvt_cells_test.dart b/test/utils/mvt_cells_test.dart index cf293d15..6dcdb4ca 100644 --- a/test/utils/mvt_cells_test.dart +++ b/test/utils/mvt_cells_test.dart @@ -1,4 +1,7 @@ import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; +import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:mesh_mapper/utils/mvt_cells.dart'; @@ -43,4 +46,296 @@ void main() { test('garbage input decodes to empty, never throws', () { expect(decodeCoverageCells(base64Decode('aGVsbG8gd29ybGQ=')), isEmpty); }); + + group('coverage format 2 blocks', () { + // Real sea.meshmapper.net tiles captured 2026-10-11 (server v1.5.130), + // each trimmed to its first 300 features with every byte of those kept. + // z7..z10 were requested with cf=2; z6 blocks go to every client. At + // z7..z9 the gsize=100 and gsize=300 answers are byte-identical, so one + // capture covers both grids. (z, x, y, file, expected k) + const captured = [ + (6, 10, 22, 'coverage_z6_sea_10_22.mvt', 8), + (7, 20, 44, 'coverage_cf2_z7_sea_20_44.mvt', 4), + (8, 41, 89, 'coverage_cf2_z8_sea_41_89.mvt', 2), + (9, 82, 178, 'coverage_cf2_z9_sea_82_178.mvt', 1), + (10, 164, 357, 'coverage_cf2_z10_sea_164_357_gsize300.mvt', null), + ]; + for (final (z, x, y, file, k) in captured) { + test('real z$z tile: k=$k and rectangles match the geometry', () { + final bytes = File('test/fixtures/$file').readAsBytesSync(); + final cells = decodeCoverageCells(bytes); + expect(cells.length, 300); + for (final c in cells) { + expect(c.k, k); + expect(c.isBlock, k != null); + expect(c.st, inInclusiveRange(1, 6)); + } + // gsize 300 for the z10 capture; ignored for blocks, whose bounds + // come from k whatever grid the user picked. + for (final gsize in [300, if (k != null) 100]) { + expect(_checkAgainstGeometry(bytes, cells, z, x, y, gsize), + greaterThan(0)); + } + }); + } + + test('a k=1 block on a 100 m request is a plain 300 m cell', () { + final c = decodeCoverageCells(_tile([(10, 20, 1, 1)])).single; + expect(c.bounds(100), [ + closeTo(10 * 0.0027, 1e-12), + closeTo(20 * 0.00384, 1e-12), + closeTo(0.0027, 1e-12), + closeTo(0.00384, 1e-12), + ]); + }); + + test('z10+ cells without k keep the requested grid', () { + final cells = decodeCoverageCells(_tile([(10, 20, 1, null)])); + expect(cells.single.k, isNull); + expect(cells.single.isBlock, isFalse); + expect(cells.single.bounds(300), + [closeTo(0.027, 1e-12), closeTo(0.0768, 1e-12), 0.0027, 0.00384]); + expect(cells.single.bounds(100), + [closeTo(0.009, 1e-12), closeTo(0.0256, 1e-12), 0.0009, 0.00128]); + }); + + test('any positive k works and a non-positive k is dropped', () { + final cells = decodeCoverageCells( + _tile([(1, 1, 1, 128), (2, 2, 1, 3), (3, 3, 1, 0), (4, 4, 1, -2)])); + expect(cells.map((c) => c.k), [128, 3]); + }); + + test('the known format-1 tile still decodes without k', () { + final cells = decodeCoverageCells(base64Decode(_knownTile)); + expect(cells.every((c) => c.k == null), isTrue); + }); + }); + + group('patch base filter', () { + // Truth table: the filter SHOWS a feature when it returns true. + final filter = coveragePatchBaseFilter(['3_7', '-5_7']); + bool shows(Map props) => _eval(filter, props) as bool; + + test('a block whose index is a patched key is shown', () { + expect(shows({'i': 3, 'j': 7, 'st': 1, 'k': 4}), isTrue); + }); + test('a block whose index is not patched is shown', () { + expect(shows({'i': 9, 'j': 9, 'st': 1, 'k': 4}), isTrue); + }); + test('a fine cell that is patched is hidden', () { + expect(shows({'i': 3, 'j': 7, 'st': 1}), isFalse); + expect(shows({'i': -5, 'j': 7, 'st': 1}), isFalse); + }); + test('a fine cell that is not patched is shown', () { + expect(shows({'i': 7, 'j': 3, 'st': 1}), isTrue); + }); + test('blocks stay visible with no keys and with many keys', () { + expect(_eval(coveragePatchBaseFilter([]), {'i': 1, 'j': 1, 'k': 2}), + isTrue); + }); + }); +} + +double _sinh(double v) => (math.exp(v) - math.exp(-v)) / 2; + +/// Tiny evaluator for the expression operators the patch filter uses, so +/// the truth table runs against the real expression without a device. +Object? _eval(Object? e, Map props) { + if (e is! List) return e; + switch (e[0]) { + case 'any': + return e.skip(1).any((x) => _eval(x, props) == true); + case 'has': + return props.containsKey(e[1]); + case '!': + return !(_eval(e[1], props) as bool); + case 'in': + final needle = _eval(e[1], props); + final hay = _eval(e[2], props) as List; + return hay.contains(needle); + case 'concat': + return e.skip(1).map((x) => _eval(x, props).toString()).join(); + case 'to-string': + return _eval(e[1], props).toString(); + case 'get': + return props[e[1]]; + case 'literal': + return e[1]; + } + throw UnsupportedError('operator ${e[0]}'); +} + +void _varint(List b, int v) { + while (v >= 128) { + b.add((v % 128) + 128); + v = v ~/ 128; + } + b.add(v); +} + +void _bytesField(List b, int field, List payload) { + _varint(b, field * 8 + 2); + _varint(b, payload.length); + b.addAll(payload); +} + +/// Single-layer MVT with features `(i, j, st, k)`; `k` null leaves it out. +Uint8List _tile(List<(int, int, int, int?)> features) { + int zigzag(int n) => n >= 0 ? n * 2 : -n * 2 - 1; + final layer = []; + _bytesField(layer, 1, 'coverage'.codeUnits); + for (final key in ['i', 'j', 'st', 'k']) { + _bytesField(layer, 3, key.codeUnits); + } + final valueIndex = {}; + int valueOf(int n) => valueIndex.putIfAbsent(n, () { + final v = []; + _varint(v, 6 * 8); + _varint(v, zigzag(n)); + _bytesField(layer, 4, v); + return valueIndex.length; + }); + final feats = >[]; + var id = 1; + for (final f in features) { + final tags = [0, valueOf(f.$1), 1, valueOf(f.$2), 2, valueOf(f.$3)]; + if (f.$4 != null) tags.addAll([3, valueOf(f.$4!)]); + final feat = []; + _varint(feat, 1 * 8); + _varint(feat, id++); + final packed = []; + for (final t in tags) { + _varint(packed, t); + } + _bytesField(feat, 2, packed); + feats.add(feat); + } + for (final f in feats) { + _bytesField(layer, 2, f); + } + final tile = []; + _bytesField(tile, 3, layer); + return Uint8List.fromList(tile); +} + +/// Feature id -> [minX, minY, maxX, maxY, extent] in tile coordinates, read +/// from the real geometry (the decoder under test skips geometry entirely). +Map> _decodeGeometryBoxes(Uint8List bytes) { + var pos = 0; + int varint(Uint8List buf) { + var value = 0, mult = 1; + while (true) { + final b = buf[pos++]; + value += (b % 128) * mult; + if (b < 128) return value; + mult *= 128; + } + } + + int unzig(int n) => n.isOdd ? -((n + 1) ~/ 2) : n ~/ 2; + // Find the layer. + late Uint8List layer; + while (pos < bytes.length) { + final tag = varint(bytes); + final len = varint(bytes); + if (tag == 3 * 8 + 2) { + layer = Uint8List.sublistView(bytes, pos, pos + len); + break; + } + pos += len; + } + pos = 0; + var extent = 4096; + final features = []; + while (pos < layer.length) { + final tag = varint(layer); + if (tag % 8 == 0) { + final v = varint(layer); + if (tag ~/ 8 == 5) extent = v; + continue; + } + final len = varint(layer); + if (tag ~/ 8 == 2) { + features.add(Uint8List.sublistView(layer, pos, pos + len)); + } + pos += len; + } + final out = >{}; + for (final f in features) { + pos = 0; + var id = 0; + var geom = []; + while (pos < f.length) { + final tag = varint(f); + if (tag % 8 == 0) { + final v = varint(f); + if (tag ~/ 8 == 1) id = v; + continue; + } + final len = varint(f); + if (tag ~/ 8 == 4) { + final end = pos + len; + geom = []; + while (pos < end) { + geom.add(varint(f)); + } + } else { + pos += len; + } + } + var cx = 0, cy = 0; + var minX = 1 << 30, minY = 1 << 30, maxX = -(1 << 30), maxY = -(1 << 30); + var g = 0; + while (g < geom.length) { + final cmd = geom[g++]; + final op = cmd % 8, count = cmd ~/ 8; + if (op == 7) continue; + for (var c = 0; c < count; c++) { + cx += unzig(geom[g++]); + cy += unzig(geom[g++]); + minX = math.min(minX, cx); + minY = math.min(minY, cy); + maxX = math.max(maxX, cx); + maxY = math.max(maxY, cy); + } + } + out[id] = [ + minX.toDouble(), + minY.toDouble(), + maxX.toDouble(), + maxY.toDouble(), + extent.toDouble() + ]; + } + return out; +} + +/// Compares every feature's [CoverageCell.bounds] with its real geometry, +/// to within one 512 px tile pixel, for the features wholly inside the tile +/// (edge features are clipped). Returns how many were compared. +int _checkAgainstGeometry(Uint8List bytes, List cells, int z, + int x, int y, int gsize) { + final geo = _decodeGeometryBoxes(bytes); + final n = math.pow(2, z).toDouble(); + double lonAt(double tx) => tx / n * 360 - 180; + double latAt(double ty) => + math.atan(_sinh(math.pi * (1 - 2 * ty / n))) * 180 / math.pi; + final pixelLon = (lonAt(x + 1.0) - lonAt(x.toDouble())) / 512; + final pixelLat = (latAt(y.toDouble()) - latAt(y + 1.0)) / 512; + var checked = 0; + for (final c in cells) { + final b = c.bounds(gsize); + final g = geo[c.id]!; + final interior = b[1] > lonAt(x.toDouble()) + pixelLon && + b[1] + b[3] < lonAt(x + 1.0) - pixelLon && + b[0] + b[2] < latAt(y.toDouble()) - pixelLat && + b[0] > latAt(y + 1.0) + pixelLat; + if (!interior) continue; + checked++; + expect(lonAt(x + g[0] / g[4]), closeTo(b[1], pixelLon)); + expect(lonAt(x + g[2] / g[4]), closeTo(b[1] + b[3], pixelLon)); + expect(latAt(y + g[3] / g[4]), closeTo(b[0], pixelLat)); + expect(latAt(y + g[1] / g[4]), closeTo(b[0] + b[2], pixelLat)); + } + return checked; } diff --git a/test/utils/ping_colors_scopes_test.dart b/test/utils/ping_colors_scopes_test.dart new file mode 100644 index 00000000..df02cf59 --- /dev/null +++ b/test/utils/ping_colors_scopes_test.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/ping_colors.dart'; +import 'package:mesh_mapper/utils/repeater_marker_style.dart'; + +/// The log tab's dark card background (`main.dart`'s `darkColorScheme.surface`, +/// which `surfaceContainerHigh` falls back to when unset). Mirrors how +/// `repeater_marker_style_test.dart` checks its accents against a fixed +/// background rather than a live theme. +const _cardBackground = Color(0xFF1E293B); + +/// The light theme's card background (`main.dart`'s `lightColorScheme.surface`). +const _lightCardBackground = Color(0xFFF8FAFC); + +/// [accent] at 15% over [card]: the fill behind a scope chip's text. +Color _chipFill(Color accent, Color card) => + Color.alphaBlend(accent.withValues(alpha: 0.15), card); + +void main() { + tearDown(() { + PingColors.setColorVisionType(ColorVisionType.none); + }); + + group('PingColors.scopes', () { + for (final cvd in ColorVisionType.values) { + for (final (theme, brightness, card) in [ + ('dark', Brightness.dark, _cardBackground), + ('light', Brightness.light, _lightCardBackground), + ]) { + test('${cvd.name}: clears 3:1 on the $theme card and chip fill', () { + PingColors.setColorVisionType(cvd); + final ink = PingColors.scopesFor(brightness); + for (final bg in [card, _chipFill(ink, card)]) { + final ratio = RepeaterMarkerStyle.contrastRatio(ink, bg); + expect(ratio, greaterThanOrEqualTo(3.0), + reason: 'scopes on the $theme ${cvd.name} card is only ' + '${ratio.toStringAsFixed(2)}:1'); + } + }); + } + + test('${cvd.name}: the dark theme keeps the plain accent', () { + PingColors.setColorVisionType(cvd); + expect(PingColors.scopesFor(Brightness.dark), PingColors.scopes); + }); + + test('${cvd.name}: distinct from every other log type accent', () { + PingColors.setColorVisionType(cvd); + final others = { + 'txSuccess': PingColors.txSuccess, + 'rx': PingColors.rx, + 'discSuccess': PingColors.discSuccess, + 'traceSuccess': PingColors.traceSuccess, + }; + final scopesArgb = PingColors.scopes.toARGB32(); + others.forEach((name, color) { + expect(scopesArgb, isNot(color.toARGB32()), + reason: 'scopes matches $name under ${cvd.name}'); + }); + }); + } + }); +} diff --git a/test/utils/repeater_coverage_lines_test.dart b/test/utils/repeater_coverage_lines_test.dart new file mode 100644 index 00000000..258cd508 --- /dev/null +++ b/test/utils/repeater_coverage_lines_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/coverage_summary.dart'; + +void main() { + const segments = [ + (lat: 45.01, lon: -75.01, color: '#00ff00'), + (lat: 45.02, lon: -75.02, color: '#ffff00'), + ]; + const drawn = RepeaterCoverageLines( + repeaterId: 'a1b2c3d4', + lat: 45.0, + lon: -75.0, + segments: segments, + ); + + group('RepeaterCoverageLines.visible', () { + test('switch on draws every line', () { + expect(drawn.visible(true), segments); + }); + + test('switch off draws none, which clears the layer', () { + expect(drawn.visible(false), isEmpty); + }); + }); + + group('repeaterCoverageLinesAfterSwitch', () { + test('on redraws the selected repeater\'s lines', () { + expect( + repeaterCoverageLinesAfterSwitch(drawn, + show: true, selectedRepeaterId: 'a1b2c3d4', tileSelected: false), + segments); + }); + + test('off clears the selected repeater\'s lines', () { + expect( + repeaterCoverageLinesAfterSwitch(drawn, + show: false, selectedRepeaterId: 'a1b2c3d4', tileSelected: false), + isEmpty); + }); + + test('no repeater coverage on the map leaves the layer alone', () { + for (final show in [true, false]) { + expect( + repeaterCoverageLinesAfterSwitch(null, + show: show, + selectedRepeaterId: 'a1b2c3d4', + tileSelected: false), + isNull); + } + }); + + test('a tapped tile owns the layer, so its fan-out is left alone', () { + for (final show in [true, false]) { + expect( + repeaterCoverageLinesAfterSwitch(drawn, + show: show, selectedRepeaterId: 'a1b2c3d4', tileSelected: true), + isNull); + } + }); + + test('lines kept for another repeater are never drawn back', () { + for (final selected in ['ffff0000', null]) { + expect( + repeaterCoverageLinesAfterSwitch(drawn, + show: true, selectedRepeaterId: selected, tileSelected: false), + isNull); + } + }); + }); +} diff --git a/test/utils/repeater_nicknames_test.dart b/test/utils/repeater_nicknames_test.dart new file mode 100644 index 00000000..4978186d --- /dev/null +++ b/test/utils/repeater_nicknames_test.dart @@ -0,0 +1,645 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; +import 'package:mesh_mapper/utils/repeater_nicknames.dart'; + +/// A full 64-hex public key that starts with [prefix]. +String _key(String prefix) => prefix.toUpperCase().padRight(64, '0'); + +Repeater _repeater( + String id, + String hexId, { + int hopBytes = 1, + String name = 'Rep', +}) => + Repeater( + id: id, + hexId: hexId, + name: name, + lat: 47.6, + lon: -122.3, + lastHeard: 1787535900, + enabled: 1, + hopBytes: hopBytes, + ); + +RepeaterNickname _nick(String nickname, + {String name = 'Rep', String hex = ''}) => + RepeaterNickname(nickname: nickname, name: name, hex: hex); + +void main() { + group('normalizeNickname', () { + test('trims and collapses whitespace runs to one space', () { + expect(RepeaterNicknames.normalizeNickname(' Mell '), 'Mell'); + expect(RepeaterNicknames.normalizeNickname('Me Kr'), 'Me Kr'); + expect(RepeaterNicknames.normalizeNickname('Me\t\n Kr'), 'Me Kr'); + }); + + test('caps at ${RepeaterNicknames.maxLength} characters', () { + expect(RepeaterNicknames.maxLength, 8); + expect(RepeaterNicknames.normalizeNickname('ABCDEFGHIJ'), 'ABCDEFGH'); + expect(RepeaterNicknames.normalizeNickname('ABCDEFGH'), 'ABCDEFGH'); + }); + + test('a cap that lands on a space leaves no trailing space', () { + final once = RepeaterNicknames.normalizeNickname('abcdefg hij'); + expect(once, 'abcdefg'); + expect(RepeaterNicknames.normalizeNickname(once), once, + reason: 'normalizing a stored nickname again must not change it'); + }); + + test('blank and null give null', () { + expect(RepeaterNicknames.normalizeNickname(' '), isNull); + expect(RepeaterNicknames.normalizeNickname(''), isNull); + expect(RepeaterNicknames.normalizeNickname('\t\n'), isNull); + expect(RepeaterNicknames.normalizeNickname(null), isNull); + }); + + test('a nickname nobody could see is blank', () { + expect(RepeaterNicknames.normalizeNickname('\u200B\u200B'), isNull); + expect(RepeaterNicknames.normalizeNickname('\u200D'), isNull); + expect(RepeaterNicknames.normalizeNickname('\u200E \uFEFF'), isNull); + }); + + test('zero-width spaces are dropped from a visible nickname', () { + expect(RepeaterNicknames.normalizeNickname('\u200BMe\u200Bll'), 'Mell'); + }); + + test('counts user-perceived characters, not code units', () { + // Each smiley is two UTF-16 code units; a code-unit cap would keep four. + expect(RepeaterNicknames.normalizeNickname('😀' * 10), '😀' * 8); + + // A family emoji is seven code points joined by zero-width joiners but + // one character to the user. + const family = '👨‍👩‍👧'; + expect(RepeaterNicknames.normalizeNickname(family * 9), family * 8); + + // A combining accent is a separate code point on the letter before it. + const accented = 'é'; + expect(RepeaterNicknames.normalizeNickname(accented * 10), accented * 8); + }); + }); + + group('sanitize', () { + final keyA = _key('5007'); + + test('keeps a valid entry', () { + final out = RepeaterNicknames.sanitize({ + keyA: {'nickname': 'Mell', 'name': 'Capitol Hill', 'hex': '5007'}, + }); + + expect(out, { + keyA: _nick('Mell', name: 'Capitol Hill', hex: '5007'), + }); + }); + + test('normalizes the key from lower case and from a 0x prefix', () { + final out = RepeaterNicknames.sanitize({ + keyA.toLowerCase(): {'nickname': 'Mell', 'name': 'A', 'hex': '5007'}, + '0x${_key('9c12').toLowerCase()}': { + 'nickname': 'Kr', + 'name': 'B', + 'hex': '9C12', + }, + }); + + expect(out.keys, unorderedEquals([keyA, _key('9c12')])); + expect(out[keyA]?.nickname, 'Mell'); + expect(out[_key('9c12')]?.nickname, 'Kr'); + }); + + test('drops a short key, a blank nickname and a non-map value', () { + final out = RepeaterNicknames.sanitize({ + '5007': {'nickname': 'Short', 'name': 'A', 'hex': '5007'}, + _key('1111'): {'nickname': ' ', 'name': 'B', 'hex': '1111'}, + _key('2222'): 'Mell', + _key('3333'): null, + _key('4444'): {'nickname': 'Keep', 'name': 'C', 'hex': '4444'}, + }); + + expect(out.keys, [_key('4444')]); + }); + + test('tolerates garbage without throwing', () { + expect(RepeaterNicknames.sanitize(null), isEmpty); + expect(RepeaterNicknames.sanitize('nope'), isEmpty); + expect(RepeaterNicknames.sanitize(['a', 'b']), isEmpty); + expect(RepeaterNicknames.sanitize(42), isEmpty); + + final out = RepeaterNicknames.sanitize({ + 7: {'nickname': 'IntKey', 'name': 'A', 'hex': 'A'}, + _key('5555'): {'nickname': 9, 'name': 'B', 'hex': 'B'}, + _key('6666'): {'nickname': 'Fine', 'name': 12, 'hex': null}, + }); + + expect(out.keys, [_key('6666')]); + expect(out[_key('6666')], _nick('Fine', name: '', hex: '6666'), + reason: 'a non-string name falls back to empty, a non-string hex ' + 'to the key prefix'); + }); + + test('a missing or blank hex falls back to the key prefix', () { + final out = RepeaterNicknames.sanitize({ + _key('7A7A'): {'nickname': 'NoHex', 'name': 'A'}, + _key('8B8B'): {'nickname': 'Blank', 'name': 'B', 'hex': ' '}, + }); + + expect(out[_key('7A7A')]?.hex, '7A7A'); + expect(out[_key('8B8B')]?.hex, '8B8B'); + }); + + test('re-caps a stored nickname that is too long', () { + final out = RepeaterNicknames.sanitize({ + keyA: {'nickname': ' ABCDEFGHIJ ', 'name': 'A', 'hex': '5007'}, + }); + + expect(out[keyA]?.nickname, 'ABCDEFGH'); + }); + }); + + test('toStorage round-trips through sanitize', () { + final nicknames = { + _key('5007'): _nick('Mell', name: 'Capitol Hill', hex: '5007'), + _key('9C12'): _nick('Me Kr', name: 'Queen Anne', hex: '9C12'), + }; + + final stored = RepeaterNicknames.toStorage(nicknames); + + expect(stored[_key('5007')], { + 'nickname': 'Mell', + 'name': 'Capitol Hill', + 'hex': '5007', + }); + expect(RepeaterNicknames.sanitize(stored), nicknames); + }); + + group('nicknameFor', () { + final keyA = _key('5007'); + final nicknames = {keyA: _nick('Mell')}; + + test('matches a repeater whose hexId is lower case', () { + expect( + RepeaterNicknames.nicknameFor( + _repeater('r1', keyA.toLowerCase()), nicknames), + 'Mell', + ); + expect( + RepeaterNicknames.nicknameFor(_repeater('r1', keyA), nicknames), + 'Mell', + ); + }); + + test('returns null for an empty or short hexId', () { + expect( + RepeaterNicknames.nicknameFor( + _repeater('r1', ''), {'': _nick('Ghost'), ...nicknames}), + isNull, + reason: 'an empty key in the map must not name a repeater with no key', + ); + expect( + RepeaterNicknames.nicknameFor(_repeater('r1', '5007'), nicknames), + isNull, + reason: 'a short hexId is not a unique identity', + ); + }); + + test('returns null for a repeater with no nickname', () { + expect( + RepeaterNicknames.nicknameFor(_repeater('r2', _key('9C12')), nicknames), + isNull, + ); + }); + }); + + group('labelFor', () { + // Two repeaters share the leading byte 50, so a one-byte hash cannot tell + // them apart. Their two-byte hashes differ. + final keyMell = _key('5007'); + final keyOther = _key('5099'); + final mell = _repeater('r1', keyMell, hopBytes: 2, name: 'Capitol Hill'); + final other = _repeater('r2', keyOther, hopBytes: 2, name: 'Queen Anne'); + final nicknames = {keyMell: _nick('Mell', name: 'Capitol Hill')}; + + test('a unique 2-byte display hash gives the nickname', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + ), + 'Mell', + ); + expect( + RepeaterNicknames.labelFor( + displayId: '5007'.toLowerCase(), + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + ), + 'Mell', + reason: 'the display hash is matched case-insensitively', + ); + }); + + test('a 1-byte hash shared by two repeaters gives null', () { + expect( + RepeaterNicknames.labelFor( + displayId: '50', + repeaters: [mell, other], + hopBytes: 1, + nicknames: nicknames, + ), + isNull, + reason: 'a confidently wrong name is worse than none', + ); + }); + + test("the shared hash plus one repeater's discovery key names it", () { + expect( + RepeaterNicknames.labelFor( + displayId: '50', + identity: keyMell, + repeaters: [mell, other], + hopBytes: 1, + nicknames: nicknames, + ), + 'Mell', + ); + expect( + RepeaterNicknames.labelFor( + displayId: '50', + identity: keyOther, + repeaters: [mell, other], + hopBytes: 1, + nicknames: nicknames, + ), + isNull, + reason: 'the other repeater resolves but has no nickname', + ); + }); + + test('an identity that resolves to nothing falls back to the hash', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + identity: _key('FFFF'), + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + ), + 'Mell', + ); + }); + + test('a repeater with an empty hexId is never matched', () { + final noHex = _repeater('50', '', name: 'Site Without Hex'); + + expect( + RepeaterNicknames.labelFor( + displayId: '50', + repeaters: [noHex], + hopBytes: 1, + nicknames: {'': _nick('Ghost'), ...nicknames}, + ), + isNull, + reason: 'it resolves by its short id, but a nickname needs a full key', + ); + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [noHex, mell], + hopBytes: 2, + nicknames: {'': _nick('Ghost'), ...nicknames}, + ), + 'Mell', + reason: 'the empty entry neither blocks nor steals the lookup', + ); + }); + + test('empty nicknames give null', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [mell, other], + hopBytes: 2, + nicknames: const {}, + ), + isNull, + ); + }); + + test('a resolved repeater with no nickname gives null', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5099', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + ), + isNull, + ); + }); + + group('with useServerName', () { + test('a nickname beats the server name', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + useServerName: true, + ), + 'Mell', + ); + }); + + test('the server name is used when there is no nickname', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5099', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + useServerName: true, + ), + 'Queen An\u2026', + ); + }); + + test('an empty nickname map still resolves the server name', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5099', + repeaters: [mell, other], + hopBytes: 2, + nicknames: const {}, + useServerName: true, + ), + 'Queen An\u2026', + ); + }); + + test('a long server name is shortened', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [mell, other], + hopBytes: 2, + nicknames: const {}, + useServerName: true, + ), + 'Capitol\u2026', + ); + }); + + test('a short server name is shown whole', () { + final short = + _repeater('r3', _key('7A11'), hopBytes: 2, name: 'Hilltop'); + + expect( + RepeaterNicknames.labelFor( + displayId: '7A11', + repeaters: [short], + hopBytes: 2, + nicknames: const {}, + useServerName: true, + ), + 'Hilltop', + ); + }); + + test('the placeholder name Unknown gives null', () { + final unknown = + _repeater('r3', _key('7A11'), hopBytes: 2, name: 'Unknown'); + + expect( + RepeaterNicknames.labelFor( + displayId: '7A11', + repeaters: [unknown], + hopBytes: 2, + nicknames: const {}, + useServerName: true, + ), + isNull, + ); + }); + + test('an anonymised name gives null, prefix or suffix', () { + final prefixed = _repeater('r3', _key('7A11'), + hopBytes: 2, name: '\u{1F6AB} Secret'); + final suffixed = _repeater('r4', _key('7B22'), + hopBytes: 2, name: 'Secret \u{1F6AB}'); + + for (final (id, hidden) in [('7A11', prefixed), ('7B22', suffixed)]) { + expect(hidden.isHidden, isTrue); + expect( + RepeaterNicknames.labelFor( + displayId: id, + repeaters: [prefixed, suffixed], + hopBytes: 2, + nicknames: const {}, + useServerName: true, + ), + isNull, + reason: '$id is anonymised, so its name must not be shown', + ); + } + }); + + test('a nickname still names an anonymised repeater', () { + final hidden = _repeater('r3', _key('7A11'), + hopBytes: 2, name: '\u{1F6AB} Secret'); + + expect( + RepeaterNicknames.labelFor( + displayId: '7A11', + repeaters: [hidden], + hopBytes: 2, + nicknames: {_key('7A11'): _nick('Mine')}, + useServerName: true, + ), + 'Mine', + ); + }); + + test('a hash shared by two repeaters gives null, never a guess', () { + expect( + RepeaterNicknames.labelFor( + displayId: '50', + repeaters: [mell, other], + hopBytes: 1, + nicknames: nicknames, + useServerName: true, + ), + isNull, + ); + expect( + RepeaterNicknames.labelFor( + displayId: '50', + repeaters: [mell, other], + hopBytes: 1, + nicknames: const {}, + useServerName: true, + ), + isNull, + ); + }); + + test('a row that matches no repeater gives null', () { + expect( + RepeaterNicknames.labelFor( + displayId: 'AB', + repeaters: [mell, other], + hopBytes: 1, + nicknames: const {}, + useServerName: true, + ), + isNull, + ); + }); + + test('the shared hash plus a discovery key names the server name', () { + expect( + RepeaterNicknames.labelFor( + displayId: '50', + identity: keyOther, + repeaters: [mell, other], + hopBytes: 1, + nicknames: const {}, + useServerName: true, + ), + 'Queen An\u2026', + ); + }); + }); + + group('without useServerName', () { + test('the server name is never used', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5099', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + ), + isNull, + ); + expect( + RepeaterNicknames.labelFor( + displayId: '5099', + repeaters: [mell, other], + hopBytes: 2, + nicknames: nicknames, + useServerName: false, + ), + isNull, + ); + }); + + test('an empty nickname map still returns null', () { + expect( + RepeaterNicknames.labelFor( + displayId: '5007', + repeaters: [mell, other], + hopBytes: 2, + nicknames: const {}, + useServerName: false, + ), + isNull, + ); + }); + }); + }); + + group('shortenServerName', () { + test( + 'a name of exactly ${RepeaterNicknames.maxLength} characters has no ' + 'ellipsis', () { + expect(RepeaterNicknames.shortenServerName('Lakeview'), 'Lakeview'); + }); + + test( + 'a name of ${RepeaterNicknames.maxLength + 1} characters is cut and ' + 'gets an ellipsis', () { + expect( + RepeaterNicknames.shortenServerName('Lakeviews'), 'Lakeview\u2026'); + }); + + test('a longer name is cut to the first characters', () { + expect( + RepeaterNicknames.shortenServerName('SE-JKP-Nyk\u00F6ping-4F'), + 'SE-JKP-N\u2026', + ); + }); + + test('a cut that lands on a space leaves no gap before the ellipsis', () { + expect( + RepeaterNicknames.shortenServerName('Capitol Hill'), 'Capitol\u2026'); + }); + + test('surrounding whitespace is trimmed and not counted', () { + expect(RepeaterNicknames.shortenServerName(' Lakeview '), 'Lakeview'); + expect( + RepeaterNicknames.shortenServerName(' Lakeviews '), + 'Lakeview\u2026', + ); + }); + + test('a short name is returned as is', () { + expect(RepeaterNicknames.shortenServerName('Mell'), 'Mell'); + }); + + test('an emoji at the cut is kept whole', () { + // Seven letters then a family emoji (one grapheme, several code points). + const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}'; + expect( + RepeaterNicknames.shortenServerName('Abcdefg${family}Zed'), + 'Abcdefg$family\u2026', + ); + expect( + RepeaterNicknames.shortenServerName('Abcdefg$family'), + 'Abcdefg$family', + reason: 'eight characters including the emoji need no ellipsis', + ); + }); + + test('the ellipsis is a single character', () { + expect('\u2026'.length, 1); + expect( + RepeaterNicknames.shortenServerName('Lakeviews')!.endsWith('\u2026'), + isTrue); + }); + + test('blank gives null', () { + expect(RepeaterNicknames.shortenServerName(''), isNull); + expect(RepeaterNicknames.shortenServerName(' '), isNull); + expect(RepeaterNicknames.shortenServerName('\t\n'), isNull); + }); + + test('a newline inside the name collapses to one space', () { + expect(RepeaterNicknames.shortenServerName('Cap\nHill'), 'Cap Hill'); + }); + + test('a run of whitespace collapses before the cut is counted', () { + expect( + RepeaterNicknames.shortenServerName('Capitol \t Hill Road'), + 'Capitol\u2026', + ); + }); + + test('a zero-width character is dropped before the cut is counted', () { + // Nine characters once the zero-width space is gone, so it is cut. + expect( + RepeaterNicknames.shortenServerName('Lake\u200BUnion'), + 'LakeUnio\u2026', + ); + }); + + test('a name of only zero-width or format characters gives null', () { + expect(RepeaterNicknames.shortenServerName('\u200B\u2060'), isNull); + expect(RepeaterNicknames.shortenServerName('\u200E\u200F'), isNull, + reason: 'direction marks alone show as nothing'); + }); + }); +} diff --git a/test/utils/short_hop_ids_test.dart b/test/utils/short_hop_ids_test.dart new file mode 100644 index 00000000..e46fbe2f --- /dev/null +++ b/test/utils/short_hop_ids_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/repeater.dart'; +import 'package:mesh_mapper/utils/short_hop_ids.dart'; + +/// A full 64-hex public key that starts with [prefix]. +String _key(String prefix) => prefix.toUpperCase().padRight(64, '0'); + +Repeater _repeater(String hexId, {String id = '', int advertBytes = 3}) => + Repeater( + id: id, + hexId: hexId, + name: 'Rep', + lat: 59.3, + lon: 18.0, + lastHeard: 1787535900, + enabled: 1, + hopBytes: advertBytes, + advertBytes: advertBytes, + ); + +void main() { + final norra = _repeater(_key('A81EA4')); + final other = _repeater(_key('B7C2D9')); + + group('resolve', () { + test('a unique 1-byte prefix resolves to its repeater', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.resolve('A8'), same(norra)); + }); + + test('a unique 2-byte prefix resolves to its repeater', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.resolve('A81E'), same(norra)); + }); + + test('a prefix two repeaters share stays unresolved', () { + final twin = _repeater(_key('A8FF01')); + final index = ShortHopIds.fromRepeaters([norra, twin, other]); + expect(index.resolve('A8'), isNull); + expect(index.resolve('A81E'), same(norra)); + }); + + test('a prefix no repeater has stays unresolved', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.resolve('C4'), isNull); + }); + + test('matching ignores case', () { + final index = + ShortHopIds.fromRepeaters([_repeater(_key('a81ea4').toLowerCase())]); + expect(index.resolve('a8'), isNotNull); + expect(index.resolve('A8'), isNotNull); + }); + + test('rows of the same device in a prefix chain are one repeater', () { + // A legacy row that only has a short id, plus the full-key row. + final legacy = _repeater('', id: 'a81e'); + final index = ShortHopIds.fromRepeaters([legacy, norra]); + expect(index.resolve('A8'), same(norra)); + }); + + test('a repeater with no hex is never a candidate', () { + final blank = _repeater('', id: ''); + final index = ShortHopIds.fromRepeaters([blank, norra]); + expect(index.resolve('A8'), same(norra)); + }); + + test('a prefix of an unindexed length still resolves', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.resolve('A81EA'), same(norra)); + expect(index.resolve('A81EA400'), same(norra)); + }); + + test('rejects non-hex and too-short ids', () { + final index = ShortHopIds.fromRepeaters([norra]); + expect(index.resolve('A'), isNull); + expect(index.resolve(''), isNull); + expect(index.resolve('ZZ'), isNull); + }); + }); + + group('displayId', () { + test('a short id shows as the full-width id of its one match', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.displayId('A8', hopBytes: 1), 'A81EA4'); + expect(index.displayId('a81e', hopBytes: 1), 'A81EA4'); + }); + + test('the region width widens a repeater that advertises narrower', () { + final narrow = _repeater(_key('A81EA4'), advertBytes: 1); + final index = ShortHopIds.fromRepeaters([narrow]); + expect(index.displayId('A8', hopBytes: 1), 'A8'); + expect(index.displayId('A8', hopBytes: 3), 'A81EA4'); + }); + + test('a full-length id is unchanged', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + expect(index.displayId('A81EA4', hopBytes: 3), 'A81EA4'); + expect(index.displayId('a81ea4', hopBytes: 3), 'A81EA4'); + }); + + test('an ambiguous or unknown id is unchanged', () { + final twin = _repeater(_key('A8FF01')); + final index = ShortHopIds.fromRepeaters([norra, twin]); + expect(index.displayId('A8', hopBytes: 3), 'A8'); + expect(index.displayId('C4', hopBytes: 3), 'C4'); + }); + }); + + group('bestSnrByRepeater', () { + test('Top Heard merges a short id and the full id into one row', () { + final index = ShortHopIds.fromRepeaters([norra, other]); + final rows = index.bestSnrByRepeater([ + (repeaterId: 'A81EA4', snr: 0.0), + (repeaterId: 'A8', snr: -6.0), + (repeaterId: 'B7C2D9', snr: 3.0), + ], hopBytes: 3); + expect(rows, {'A81EA4': 0.0, 'B7C2D9': 3.0}); + }); + + test('an ambiguous short id keeps its own row', () { + final twin = _repeater(_key('A8FF01')); + final index = ShortHopIds.fromRepeaters([norra, twin]); + final rows = index.bestSnrByRepeater([ + (repeaterId: 'A81EA4', snr: 0.0), + (repeaterId: 'A8', snr: 2.0), + ], hopBytes: 3); + expect(rows, {'A81EA4': 0.0, 'A8': 2.0}); + }); + }); +} diff --git a/test/utils/slots_chip_test.dart b/test/utils/slots_chip_test.dart new file mode 100644 index 00000000..c44ebf5e --- /dev/null +++ b/test/utils/slots_chip_test.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/slots_chip.dart'; + +void main() { + SlotsChipState chip({ + bool auth = false, + bool? zone, + int? available, + int? max, + }) => + slotsChipState( + authFloodDisabled: auth, + zoneFloodDisabled: zone, + slotsAvailable: available, + slotsMax: max, + ); + + test('flood on with slots shows the open count', () { + final s = chip(zone: false, available: 2, max: 3); + expect(s.kind, SlotsChipKind.open); + expect(s.label, '2/3 Open'); + expect(s.color, Colors.orange); + expect(s.tappable, isFalse); + }); + + test('flood on with 0 slots shows 0 Slots, not Flood Off', () { + final s = chip(zone: false, available: 0, max: 0); + expect(s.kind, SlotsChipKind.zeroSlots); + expect(s.label, '0 Slots'); + expect(s.color, Colors.blue); + expect(s.tappable, isFalse); + }); + + test('status flood_disabled true shows Flood Off even with slots', () { + final s = chip(zone: true, available: 3, max: 3); + expect(s.kind, SlotsChipKind.floodOff); + expect(s.label, 'Flood Off'); + expect(s.color, Colors.blue); + expect(s.tappable, isTrue); + }); + + test('auth floodDisabled outranks a status flood-on answer', () { + final s = chip(auth: true, zone: false, available: 3, max: 3); + expect(s.kind, SlotsChipKind.floodOff); + expect(s.tappable, isTrue); + }); + + test('key absent with 0 slots keeps the legacy Flood Off guess', () { + final s = chip(available: 0, max: 0); + expect(s.kind, SlotsChipKind.floodOff); + expect(s.label, 'Flood Off'); + }); + + test('key absent with slots shows the open count', () { + final s = chip(available: 5, max: 5); + expect(s.kind, SlotsChipKind.open); + expect(s.label, '5/5 Open'); + expect(s.color, Colors.green); + }); + + test('a full zone with flood on stays red', () { + final s = chip(zone: false, available: 0, max: 3); + expect(s.kind, SlotsChipKind.open); + expect(s.color, Colors.red); + }); + + test('no slot data shows --', () { + final s = chip(zone: false); + expect(s.kind, SlotsChipKind.unknown); + expect(s.label, '--'); + expect(s.color, Colors.grey); + }); +} diff --git a/test/utils/store_links_test.dart b/test/utils/store_links_test.dart new file mode 100644 index 00000000..3bbbfb2f --- /dev/null +++ b/test/utils/store_links_test.dart @@ -0,0 +1,98 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/store_links.dart'; + +void main() { + group('StoreLinks.resolve', () { + test('iOS TestFlight opens TestFlight', () { + final link = + StoreLinks.resolve(TargetPlatform.iOS, 'com.apple.testflight'); + expect(link.label, 'Update in TestFlight'); + expect(link.uri.toString(), + 'itms-beta://beta.itunes.apple.com/v1/app/6758073991'); + }); + + for (final installer in ['com.apple', 'com.apple.simulator', null]) { + test('iOS installer $installer opens the App Store', () { + final link = StoreLinks.resolve(TargetPlatform.iOS, installer); + expect(link.label, 'Update MeshMapper'); + expect(link.uri.toString(), 'https://apps.apple.com/app/id6758073991'); + }); + } + + for (final installer in [ + 'com.android.vending', + 'com.google.android.feedback', + ]) { + test('Android installer $installer opens Google Play', () { + for (final beta in [false, true]) { + final link = StoreLinks.resolve(TargetPlatform.android, installer, + isBetaBuild: beta); + expect(link.label, 'Update MeshMapper'); + expect(link.uri.toString(), + 'https://play.google.com/store/apps/details?id=net.meshmapper.app'); + } + }); + } + + for (final installer in [ + 'com.google.android.packageinstaller', + 'org.fdroid.fdroid', + null, + ]) { + test('Android installer $installer downloads the latest release', () { + final link = StoreLinks.resolve(TargetPlatform.android, installer); + expect(link.label, 'Download latest version'); + expect(link.uri.toString(), + 'https://github.com/MeshMapper/MeshMapper_Project/releases/latest'); + }); + + test('Android installer $installer on a beta build opens the releases ' + 'page, where the newest pre-release is listed first', () { + final link = StoreLinks.resolve(TargetPlatform.android, installer, + isBetaBuild: true); + expect(link.label, 'Download latest version'); + expect(link.uri.toString(), + 'https://github.com/MeshMapper/MeshMapper_Project/releases'); + }); + } + }); + + group('parseRequiredAppVersion', () { + test('reads a store minimum', () { + expect(parseRequiredAppVersion('App version outdated. Required: v1.4.0'), + '1.4.0'); + }); + + test('reads a TestFlight build minimum', () { + expect( + parseRequiredAppVersion('Dev version outdated. Required: 1791170991'), + '1791170991'); + }); + + test('drops a trailing full stop', () { + expect(parseRequiredAppVersion('Required: v1.4.0.'), '1.4.0'); + }); + + test('null when the message names no version', () { + expect(parseRequiredAppVersion('Please update'), isNull); + expect(parseRequiredAppVersion(null), isNull); + }); + }); + + group('appUpdateVersionLine', () { + test('store build shows versions', () { + expect(appUpdateVersionLine('APP-1.3.0', '1.4.0'), + 'Your version: 1.3.0 · Needed: 1.4.0'); + }); + + test('TestFlight build shows build numbers', () { + expect(appUpdateVersionLine('APP-1790996175', '1791170991'), + 'Your build: 1790996175 · Needed: 1791170991'); + }); + + test('unknown minimum shows only our own version', () { + expect(appUpdateVersionLine('APP-1.3.0', null), 'Your version: 1.3.0'); + }); + }); +} diff --git a/test/utils/zone_group_test.dart b/test/utils/zone_group_test.dart new file mode 100644 index 00000000..140e7613 --- /dev/null +++ b/test/utils/zone_group_test.dart @@ -0,0 +1,241 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/zone_group.dart'; + +void main() { + group('parseZoneGroup', () { + test('reads a full group', () { + final g = parseZoneGroup({ + 'code': 'YOW', + 'group': { + 'code': 'ONQC', + 'name': 'Ontario / Quebec', + 'members': ['YOW', 'YUL'] + }, + }); + expect(g, isNotNull); + expect(g!.code, 'ONQC'); + expect(g.name, 'Ontario / Quebec'); + expect(g.members, ['YOW', 'YUL']); + }); + + test('no group key, null group, non-map zone and non-map group are no group', + () { + expect(parseZoneGroup({'code': 'YOW'}), isNull); + expect(parseZoneGroup({'code': 'YOW', 'group': null}), isNull); + expect(parseZoneGroup(null), isNull); + expect(parseZoneGroup('YOW'), isNull); + expect(parseZoneGroup({'code': 'YOW', 'group': 'ONQC'}), isNull); + }); + + test('a missing, blank or unsafe code is no group', () { + expect( + parseZoneGroup({ + 'group': {'name': 'x'} + }), + isNull); + expect( + parseZoneGroup({ + 'group': {'code': ' '} + }), + isNull); + expect( + parseZoneGroup({ + 'group': {'code': 'ON/QC'} + }), + isNull); + expect( + parseZoneGroup({ + 'group': {'code': 42} + }), + isNull); + }); + + test('code is trimmed and upper-cased, a null or blank name is null', () { + final g = parseZoneGroup({ + 'group': {'code': ' finland ', 'name': ' '} + })!; + expect(g.code, 'FINLAND'); + expect(g.name, isNull); + expect( + parseZoneGroup({ + 'group': {'code': 'ONQC', 'name': null} + })! + .name, + isNull); + }); + + test('members keep only non-empty strings, upper-cased', () { + final g = parseZoneGroup({ + 'group': { + 'code': 'ONQC', + 'members': [' yow', '', 7, 'YUL'] + } + })!; + expect(g.members, ['YOW', 'YUL']); + expect( + parseZoneGroup({ + 'group': {'code': 'ONQC'} + })! + .members, + isEmpty); + }); + }); + + group('shortZoneLabel', () { + test('four or fewer characters stay whole', () { + expect(shortZoneLabel('YOW'), 'YOW'); + expect(shortZoneLabel('ONQC'), 'ONQC'); + }); + test('longer codes are cut to four plus an ellipsis', () { + expect(shortZoneLabel('FINLAND'), 'FINL…'); + expect(shortZoneLabel('ABCDE'), 'ABCD…'); + }); + }); + + group('classifyZoneMove', () { + test('same zone or no session is no move', () { + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: 'ONQC', + newZone: 'YOW', + newGroup: 'ONQC'), + ZoneMove.none); + expect( + classifyZoneMove( + sessionZone: null, + sessionGroup: null, + newZone: 'YOW', + newGroup: null), + ZoneMove.none); + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: null, + newZone: '', + newGroup: null), + ZoneMove.none); + }); + test('same group is a hidden handoff', () { + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: 'ONQC', + newZone: 'YUL', + newGroup: 'ONQC'), + ZoneMove.hiddenHandoff); + }); + test('no group on either side, or different groups, is a full transfer', + () { + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: null, + newZone: 'YUL', + newGroup: null), + ZoneMove.fullTransfer); + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: 'ONQC', + newZone: 'SEA', + newGroup: null), + ZoneMove.fullTransfer); + expect( + classifyZoneMove( + sessionZone: 'SEA', + sessionGroup: null, + newZone: 'YOW', + newGroup: 'ONQC'), + ZoneMove.fullTransfer); + expect( + classifyZoneMove( + sessionZone: 'YOW', + sessionGroup: 'ONQC', + newZone: 'SEA', + newGroup: 'PNW'), + ZoneMove.fullTransfer); + }); + }); + + group('groupHandoffFollowUp', () { + GroupHandoffFollowUp rule({ + bool failed = true, + bool connected = true, + bool offlineMode = false, + bool inZoneGracePeriod = false, + String? zoneCode = 'YUL', + }) => + groupHandoffFollowUp( + failed: failed, + connected: connected, + offlineMode: offlineMode, + inZoneGracePeriod: inZoneGracePeriod, + zoneCode: zoneCode, + ); + + test('a failed handoff on a live session re-mints in the current zone', + () { + expect(rule(), GroupHandoffFollowUp.transfer); + expect(rule(zoneCode: 'YQB'), GroupHandoffFollowUp.transfer, + reason: 'a third member a later tick moved into'); + expect(rule(zoneCode: 'YOW'), GroupHandoffFollowUp.transfer, + reason: 'the old member the phone moved back into'); + }); + + test('a failed handoff with no zone to re-join ends the session', () { + expect(rule(zoneCode: null), GroupHandoffFollowUp.disconnect); + expect(rule(zoneCode: ''), GroupHandoffFollowUp.disconnect); + }); + + test('a handoff that did not fail needs nothing', () { + expect(rule(failed: false), GroupHandoffFollowUp.none); + expect(rule(failed: false, zoneCode: null), GroupHandoffFollowUp.none); + }); + + test('a session that is gone, offline or in zone grace owns itself', () { + expect(rule(connected: false), GroupHandoffFollowUp.none); + expect(rule(offlineMode: true), GroupHandoffFollowUp.none); + expect(rule(inZoneGracePeriod: true), GroupHandoffFollowUp.none); + expect(rule(connected: false, zoneCode: null), GroupHandoffFollowUp.none); + }); + }); + + group('reconnectBackstopOutcome', () { + ReconnectBackstopOutcome rule({ + bool superseded = false, + bool minted = true, + bool linkUp = true, + }) => + reconnectBackstopOutcome( + superseded: superseded, + minted: minted, + linkUp: linkUp, + ); + + test('a minted session over a live link restores auto-ping', () { + expect(rule(), ReconnectBackstopOutcome.restore); + }); + + test('no session over a live link ends through the live-link path', () { + expect(rule(minted: false), ReconnectBackstopOutcome.abandonOnLiveLink, + reason: 'the dead-link abandon never closes the transport or ' + 'deletes the channel'); + }); + + test('a link lost during the mint goes back to auto-reconnect', () { + expect(rule(linkUp: false), ReconnectBackstopOutcome.handBackToReconnect, + reason: 'a session minted over a dead link is kept by the ' + 'reconnect, never restored on it'); + expect(rule(minted: false, linkUp: false), + ReconnectBackstopOutcome.handBackToReconnect, + reason: 'the next reconnect auths on its own'); + }); + + test('a superseding owner is honoured whatever the link did', () { + expect(rule(superseded: true), ReconnectBackstopOutcome.superseded); + expect(rule(superseded: true, minted: false, linkUp: false), + ReconnectBackstopOutcome.superseded); + }); + }); +} diff --git a/test/widgets/ping_controls_manage_deps_test.dart b/test/widgets/ping_controls_manage_deps_test.dart new file mode 100644 index 00000000..4617d7e8 --- /dev/null +++ b/test/widgets/ping_controls_manage_deps_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/models/user_preferences.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; +import 'package:mesh_mapper/widgets/ping_controls.dart'; +import 'package:provider/provider.dart'; + +/// The Trace row's Manage button reads [AppStateProvider.isScopeRadioBusy], +/// but the row only rebuilds when its Selector record changes. Without the +/// flag in that record, Manage stayed disabled after the radio freed up +/// until some unrelated control change happened to rebuild the row. +void main() { + testWidgets('the Trace row rebuilds when the scope radio frees up, and not ' + 'on a notify that changes nothing', (tester) async { + final state = _TraceRowState()..busy = true; + var builds = 0; + late bool seenBusy; + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: state, + child: Builder(builder: (context) { + context.select(targetedDepsOf); + builds++; + seenBusy = context.read().isScopeRadioBusy; + return const SizedBox(); + }), + ), + ); + expect(builds, 1); + expect(seenBusy, isTrue); + + // Unrelated notifies (GPS, noise floor, battery) must not rebuild. + for (var i = 0; i < 10; i++) { + state.notifyListeners(); + await tester.pump(); + } + expect(builds, 1); + + state + ..busy = false + ..notifyListeners(); + await tester.pump(); + expect(builds, 2); + expect(seenBusy, isFalse); + }); +} + +class _TraceRowState extends ChangeNotifier implements AppStateProvider { + bool busy = false; + + @override + bool get isScopeRadioBusy => busy; + @override + final preferences = const UserPreferences(powerLevelSet: true); + @override + bool get isTargetedModeRunning => false; + @override + int get traceHopBytes => 1; + @override + String? get targetRepeaterId => null; + @override + bool get isConnected => true; + @override + bool get isAutoPingStarting => false; + @override + bool get isRepeaterAdminActive => false; + @override + bool get isPingInProgress => false; + @override + bool get isPingSending => false; + @override + bool get isAutoReconnecting => false; + @override + int get repeaterCount => 0; + @override + int? get companionFirmwareVersionCode => 9; + + // The provider's own notifyListeners is protected; the test drives it. + @override + // ignore: unnecessary_overrides + void notifyListeners() => super.notifyListeners(); + + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.isGetter) return null; + return super.noSuchMethod(invocation); + } +} diff --git a/test/widgets/ping_controls_scope_badge_test.dart b/test/widgets/ping_controls_scope_badge_test.dart new file mode 100644 index 00000000..13bf42ae --- /dev/null +++ b/test/widgets/ping_controls_scope_badge_test.dart @@ -0,0 +1,381 @@ +import 'dart:ui' show SemanticsAction, Tristate; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart' show AutoMode; +import 'package:mesh_mapper/utils/ping_colors.dart'; +import 'package:mesh_mapper/widgets/ping_controls.dart'; + +/// The "Scopes" badge (owner ruling 15): a small pill at the corner of the +/// running mode's button while the app is asking a discovered repeater for +/// its scopes ([AppStateProvider.isScopeRequestActive]). +/// +/// `PingControls`, `CompactPingControls` and `LandscapePingControls` all read +/// a live `AppStateProvider`, which no test in this suite can build, so the +/// rendered tests below pump the exact button widgets those three layouts use +/// ([PingActionButton] for portrait, [LandscapePingIconButton] for +/// landscape, [CompactPingActionButton] for compact), each fed by +/// [showsScopesBadge] for its mode, the same decision every layout's call +/// site routes through. +void main() { + group('showsScopesBadge', () { + test('Passive: shows while running and a scope request is active', () { + expect( + showsScopesBadge(AutoMode.passive, + isModeRunning: true, isScopeRequestActive: true), + isTrue, + ); + }); + + test('Passive: hidden once the scope request ends', () { + expect( + showsScopesBadge(AutoMode.passive, + isModeRunning: true, isScopeRequestActive: false), + isFalse, + ); + }); + + test('Passive: hidden when Passive is not the running mode', () { + expect( + showsScopesBadge(AutoMode.passive, + isModeRunning: false, isScopeRequestActive: true), + isFalse, + ); + }); + + test('Hybrid: shows while running and a scope request is active', () { + expect( + showsScopesBadge(AutoMode.hybrid, + isModeRunning: true, isScopeRequestActive: true), + isTrue, + ); + }); + + test('Hybrid: hidden once the scope request ends', () { + expect( + showsScopesBadge(AutoMode.hybrid, + isModeRunning: true, isScopeRequestActive: false), + isFalse, + ); + }); + + test('Hybrid: hidden when Hybrid is not the running mode', () { + expect( + showsScopesBadge(AutoMode.hybrid, + isModeRunning: false, isScopeRequestActive: true), + isFalse, + ); + }); + + test('Active: never shows, even while "running" with a request active', + () { + expect( + showsScopesBadge(AutoMode.active, + isModeRunning: true, isScopeRequestActive: true), + isFalse, + ); + }); + + test('Trace: never shows, even while "running" with a request active', + () { + expect( + showsScopesBadge(AutoMode.targeted, + isModeRunning: true, isScopeRequestActive: true), + isFalse, + ); + }); + }); + + group('scopesBadgeSemanticsLabel', () { + test('leaves the label untouched while inactive', () { + expect(scopesBadgeSemanticsLabel('Passive Mode', false), 'Passive Mode'); + }); + + test('appends the exact phrase while active, keeping the base label', + () { + expect( + scopesBadgeSemanticsLabel('Passive Mode', true), + 'Passive Mode, asking repeaters for scopes', + ); + }); + + test( + 'a countdown baked into the label keeps its text and gains the same ' + 'suffix', () { + // Landscape's tooltip base and compact's expanded label can both carry + // a live countdown baked into the string; the composer must not touch + // that text, only append to it. + expect( + scopesBadgeSemanticsLabel('Listening 5s', true), + 'Listening 5s, asking repeaters for scopes', + ); + expect(scopesBadgeSemanticsLabel('Listening 5s', false), 'Listening 5s'); + }); + + test('suffix constant matches the phrase the review required', () { + expect(scopesBadgeSemanticsSuffix, ', asking repeaters for scopes'); + }); + }); + + group('ScopesBadge widget', () { + testWidgets('renders the pill text in the PingColors.scopes accent', + (tester) async { + await tester.pumpWidget(const MaterialApp( + home: Scaffold(body: ScopesBadge()), + )); + + expect(find.text('Scopes'), findsOneWidget); + + final container = tester.widget( + find.descendant( + of: find.byType(ScopesBadge), + matching: find.byType(Container), + ), + ); + final decoration = container.decoration as BoxDecoration; + expect(decoration.color, PingColors.scopes); + }); + }); + + group('rendered buttons (portrait, landscape, compact)', () { + for (final layout in _Layout.values) { + group(layout.name, () { + for (final mode in [AutoMode.passive, AutoMode.hybrid]) { + testWidgets('${mode.name}: the pill shows while asking, not after', + (tester) async { + await _pump(tester, layout, mode, requestActive: true); + expect(_badgeIn(layout), findsOneWidget); + expect( + find.descendant( + of: find.byType(layout.buttonType), + matching: find.text('Scopes')), + findsOneWidget, + ); + + await _pump(tester, layout, mode, requestActive: false); + expect(_badgeIn(layout), findsNothing); + expect(find.text('Scopes'), findsNothing); + }); + + testWidgets('${mode.name}: label and countdown text are unchanged', + (tester) async { + await _pump(tester, layout, mode, requestActive: false); + final off = _buttonTexts(tester, layout); + await _pump(tester, layout, mode, requestActive: true); + final on = _buttonTexts(tester, layout); + expect(off, isNotEmpty); + expect(on, off); + }); + + testWidgets('${mode.name}: semantics carry the phrase only while on', + (tester) async { + final handle = tester.ensureSemantics(); + final phrase = RegExp(RegExp.escape(scopesBadgeSemanticsSuffix)); + + await _pump(tester, layout, mode, requestActive: true); + final node = tester.getSemantics(find.bySemanticsLabel(phrase)); + expect( + node.label, + contains('${layout.baseLabel(mode)}$scopesBadgeSemanticsSuffix'), + ); + + await _pump(tester, layout, mode, requestActive: false); + expect(find.bySemanticsLabel(phrase), findsNothing); + // The button still announces its own label, first. + expect( + find.bySemanticsLabel( + RegExp('^${RegExp.escape(layout.baseLabel(mode))}')), + findsWidgets, + ); + handle.dispose(); + }); + + if (layout != _Layout.landscape) { + testWidgets('${mode.name}: the label is read once, badge on or off', + (tester) async { + final handle = tester.ensureSemantics(); + final base = layout.baseLabel(mode); + for (final requestActive in [false, true]) { + await _pump(tester, layout, mode, requestActive: requestActive); + final node = tester.getSemantics(find + .bySemanticsLabel(RegExp('^${RegExp.escape(base)}')) + .first); + final label = node.label; + expect(RegExp(RegExp.escape(base)).allMatches(label).length, 1, + reason: 'the base label must not repeat: "$label"'); + expect(label, isNot(contains('Scopes')), + reason: 'the pill text is read through the suffix only'); + expect( + label.startsWith( + scopesBadgeSemanticsLabel(base, requestActive)), + isTrue, + reason: label); + // Still a tappable, enabled button for TalkBack and VoiceOver. + final data = node.getSemanticsData(); + expect(data.flagsCollection.isButton, isTrue); + expect(data.flagsCollection.isEnabled, Tristate.isTrue); + expect(data.hasAction(SemanticsAction.tap), isTrue); + } + handle.dispose(); + }); + } + + testWidgets('${mode.name}: the overhanging pill is not clipped', + (tester) async { + await _pump(tester, layout, mode, requestActive: true); + final badge = _badgeIn(layout); + + // Every Stack between the pill and the button lets it overhang. + final stacks = find.ancestor( + of: badge, + matching: find.descendant( + of: find.byType(layout.buttonType), + matching: find.byType(Stack))); + expect(stacks, findsWidgets); + for (final stack in tester.widgetList(stacks)) { + expect(stack.clipBehavior, Clip.none); + } + // And no clip widget sits between them either. + for (final clip in [ClipRect, ClipRRect, ClipPath, ClipOval]) { + expect( + find.ancestor( + of: badge, + matching: find.descendant( + of: find.byType(layout.buttonType), + matching: find.byType(clip))), + findsNothing, + ); + } + + // The pill really does sit past its Stack's edge, so a clip on + // that Stack would cut it. + final stackRect = tester.getRect(stacks.first); + final badgeRect = tester.getRect(badge); + expect(stackRect.intersect(badgeRect), isNot(badgeRect)); + }); + } + + for (final mode in [AutoMode.active, AutoMode.targeted]) { + testWidgets('${mode.name}: never shows the pill', (tester) async { + final handle = tester.ensureSemantics(); + await _pump(tester, layout, mode, requestActive: true); + expect(_badgeIn(layout), findsNothing); + expect(find.text('Scopes'), findsNothing); + expect( + find.bySemanticsLabel( + RegExp(RegExp.escape(scopesBadgeSemanticsSuffix))), + findsNothing, + ); + handle.dispose(); + }); + } + }); + } + }); +} + +/// The three layouts and the button widget each one renders. +enum _Layout { + portrait(PingActionButton), + landscape(LandscapePingIconButton), + compact(CompactPingActionButton); + + const _Layout(this.buttonType); + + final Type buttonType; + + /// The button's own text: the running label in portrait and compact, the + /// tooltip in landscape (whose countdown rides a separate number badge). + String baseLabel(AutoMode mode) => switch (this) { + _Layout.landscape => '${_modeName(mode)} Mode', + _ => 'Next ping 12s', + }; +} + +String _modeName(AutoMode mode) => switch (mode) { + AutoMode.active => 'Active', + AutoMode.hybrid => 'Hybrid', + AutoMode.passive => 'Passive', + AutoMode.targeted => 'Trace', + }; + +IconData _iconFor(AutoMode mode) => switch (mode) { + AutoMode.active => Icons.sensors, + AutoMode.hybrid => Icons.compare_arrows, + AutoMode.passive => Icons.hearing, + AutoMode.targeted => Icons.route, + }; + +/// Pumps [layout]'s real button for a running [mode], with the badge decided +/// by [showsScopesBadge] exactly as the layouts' call sites decide it. +Future _pump( + WidgetTester tester, + _Layout layout, + AutoMode mode, { + required bool requestActive, +}) async { + final badge = showsScopesBadge(mode, + isModeRunning: true, isScopeRequestActive: requestActive); + const color = Color(0xFF22C55E); + final label = layout.baseLabel(mode); + final Widget button = switch (layout) { + _Layout.portrait => PingActionButton( + icon: _iconFor(mode), + label: label, + color: color, + enabled: true, + isActive: true, + onPressed: () {}, + showScopesBadge: badge, + ), + _Layout.landscape => LandscapePingIconButton( + icon: _iconFor(mode), + tooltip: label, + color: color, + enabled: true, + isActive: true, + countdown: 12, + onPressed: () {}, + showScopesBadge: badge, + ), + _Layout.compact => CompactPingActionButton( + icon: _iconFor(mode), + label: label, + color: color, + enabled: true, + isActive: true, + isExpanded: true, + progress: 0.5, + onPressed: () {}, + showScopesBadge: badge, + ), + }; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: SizedBox(width: 160, child: button), + ), + ), + ), + )); + await tester.pumpAndSettle(); +} + +Finder _badgeIn(_Layout layout) => find.descendant( + of: find.byType(layout.buttonType), matching: find.byType(ScopesBadge)); + +/// Every Text the button renders, minus the pill's own. +List _buttonTexts(WidgetTester tester, _Layout layout) { + final pillTexts = tester + .widgetList(find.descendant( + of: find.byType(ScopesBadge), matching: find.byType(Text))) + .toSet(); + return tester + .widgetList(find.descendant( + of: find.byType(layout.buttonType), matching: find.byType(Text))) + .where((t) => !pillTexts.contains(t)) + .map((t) => t.data) + .toList(); +} diff --git a/test/widgets/regional_config_card_test.dart b/test/widgets/regional_config_card_test.dart new file mode 100644 index 00000000..4b2b8e43 --- /dev/null +++ b/test/widgets/regional_config_card_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/widgets/regional_config_card.dart'; + +Widget _wrap(Widget child) => MaterialApp(home: Scaffold(body: child)); + +void main() { + testWidgets('a grouped zone shows the full group code and the member', + (tester) async { + await tester.pumpWidget(_wrap(const RegionalConfigCard( + zoneName: 'Ottawa', + zoneCode: 'YOW', + groupCode: 'FINLAND', + compact: true))); + expect(find.text('Region'), findsOneWidget); + expect(find.text('FINLAND'), findsOneWidget); + expect(find.text('YOW'), findsOneWidget); + }); + + testWidgets('no group shows no Region row', (tester) async { + await tester.pumpWidget(_wrap(const RegionalConfigCard( + zoneName: 'Ottawa', zoneCode: 'YOW', compact: true))); + expect(find.text('Region'), findsNothing); + }); + + testWidgets('offline hides the Region row', (tester) async { + await tester.pumpWidget(_wrap(const RegionalConfigCard( + zoneCode: 'YOW', + groupCode: 'ONQC', + isOfflineMode: true, + compact: true))); + expect(find.text('Region'), findsNothing); + }); +} diff --git a/test/widgets/repeater_nickname_dialog_test.dart b/test/widgets/repeater_nickname_dialog_test.dart new file mode 100644 index 00000000..55bd4a18 --- /dev/null +++ b/test/widgets/repeater_nickname_dialog_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/widgets/repeater_nickname_dialog.dart'; + +/// What the dialog handed back, once it has closed. +class _Outcome { + bool closed = false; + String? result; +} + +void main() { + /// Opens the dialog over a throwaway page. + Future<_Outcome> openDialog(WidgetTester tester, {String? current}) async { + final outcome = _Outcome(); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + outcome.result = await showRepeaterNicknameDialog( + context, + hex: '5007', + serverName: 'Mellionnec Repeater', + current: current, + ); + outcome.closed = true; + }, + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return outcome; + } + + testWidgets('shows the hex, the server name and the helper', (tester) async { + await openDialog(tester); + + expect(find.text('Repeater Nickname'), findsOneWidget); + expect(find.text('5007'), findsOneWidget); + expect(find.text('Mellionnec Repeater'), findsOneWidget); + expect( + find.text('Shows instead of 5007 in Top Heard, and as its name on the ' + 'Live Activity, CarPlay, Apple Watch and Siri. If another repeater ' + 'shares 5007, the ID shows instead.'), + findsOneWidget, + ); + }); + + testWidgets('saving a long name returns it capped at 8', (tester) async { + final outcome = await openDialog(tester); + + await tester.enterText(find.byType(TextField), 'Mellionnec'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(outcome.closed, isTrue); + expect(outcome.result, 'Mellionn'); + }); + + testWidgets('submitting the field saves', (tester) async { + final outcome = await openDialog(tester); + + await tester.enterText(find.byType(TextField), ' Goar '); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + + expect(outcome.result, 'Goar'); + }); + + testWidgets('cancel returns null', (tester) async { + final outcome = await openDialog(tester, current: 'Mell'); + + await tester.enterText(find.byType(TextField), 'Other'); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(outcome.closed, isTrue); + expect(outcome.result, isNull); + }); + + testWidgets('Remove is offered only for a current nickname', (tester) async { + await openDialog(tester); + expect(find.text('Remove'), findsNothing); + }); + + testWidgets('Remove returns an empty string', (tester) async { + final outcome = await openDialog(tester, current: 'Mell'); + + final field = tester.widget(find.byType(TextField)); + expect(field.controller!.text, 'Mell'); + await tester.tap(find.text('Remove')); + await tester.pumpAndSettle(); + + expect(outcome.closed, isTrue); + expect(outcome.result, ''); + }); + + testWidgets('a blank save returns an empty string', (tester) async { + final outcome = await openDialog(tester, current: 'Mell'); + + await tester.enterText(find.byType(TextField), ' '); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(outcome.result, ''); + }); + + group('nicknameResultChanges', () { + test('a cancel changes nothing', () { + expect(nicknameResultChanges(null, null), isFalse); + expect(nicknameResultChanges(null, 'Mell'), isFalse); + }); + + test('the same nickname again changes nothing', () { + expect(nicknameResultChanges('Mell', 'Mell'), isFalse); + }); + + test('removing a nickname that is not there changes nothing', () { + expect(nicknameResultChanges('', null), isFalse); + }); + + test('a new, different or removed nickname is a change', () { + expect(nicknameResultChanges('Mell', null), isTrue); + expect(nicknameResultChanges('Goar', 'Mell'), isTrue); + expect(nicknameResultChanges('', 'Mell'), isTrue); + }); + }); +} diff --git a/test/widgets/repeater_nickname_widgets_test.dart b/test/widgets/repeater_nickname_widgets_test.dart new file mode 100644 index 00000000..c3049f65 --- /dev/null +++ b/test/widgets/repeater_nickname_widgets_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/widgets/repeater_nickname_widgets.dart'; + +void main() { + Widget host(Widget child) => MaterialApp( + home: Scaffold(body: Center(child: child)), + ); + + testWidgets('a display tag with no nickname draws nothing', (tester) async { + await tester.pumpWidget(host(const RepeaterNicknameTag(nickname: null))); + + expect(find.byType(Text), findsNothing); + expect(tester.getSize(find.byType(RepeaterNicknameTag)), Size.zero); + }); + + testWidgets('a display tag shows the nickname', (tester) async { + await tester.pumpWidget(host(const RepeaterNicknameTag(nickname: 'Mell'))); + expect(find.text('Mell'), findsOneWidget); + }); + + testWidgets('the button reads Nickname until one is set, then the nickname', + (tester) async { + var presses = 0; + await tester.pumpWidget(host(Column( + mainAxisSize: MainAxisSize.min, + children: [ + RepeaterNicknameButton(nickname: null, onPressed: () => presses++), + RepeaterNicknameButton(nickname: 'Mell', onPressed: () => presses++), + ], + ))); + + expect(find.byIcon(Icons.add), findsOneWidget); + expect(find.byIcon(Icons.label_outline), findsOneWidget); + await tester.tap(find.text('Nickname')); + await tester.tap(find.text('Mell')); + expect(presses, 2); + }); + + testWidgets('the button reads as one named button', (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(host(Column( + mainAxisSize: MainAxisSize.min, + children: [ + RepeaterNicknameButton(nickname: null, onPressed: () {}), + RepeaterNicknameButton(nickname: 'Mell', onPressed: () {}), + ], + ))); + + for (final label in ['Add nickname', 'Edit nickname Mell']) { + expect( + tester.getSemantics(find.bySemanticsLabel(label)), + matchesSemantics( + label: label, + isButton: true, + hasTapAction: true, + ), + ); + } + semantics.dispose(); + }); + + testWidgets('the hex badge shows the hex', (tester) async { + await tester.pumpWidget(host(const RepeaterHexBadge('5007'))); + expect(find.text('5007'), findsOneWidget); + }); +} diff --git a/test/widgets/scope_discovery_firmware_note_test.dart b/test/widgets/scope_discovery_firmware_note_test.dart new file mode 100644 index 00000000..e81e3618 --- /dev/null +++ b/test/widgets/scope_discovery_firmware_note_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; +import 'package:mesh_mapper/widgets/scope_discovery_firmware_note.dart'; + +const _noteText = 'Your radio needs firmware v1.16.0 or newer for this.'; + +void main() { + Future pump(WidgetTester tester, bool show) => tester.pumpWidget( + MaterialApp( + home: Scaffold(body: ScopeDiscoveryFirmwareNote(show: show)), + ), + ); + + testWidgets('firmware code 11 while connected shows the line', + (tester) async { + await pump(tester, + scopeDiscoveryFirmwareTooOld(connected: true, firmwareCode: 11)); + expect(find.text(_noteText), findsOneWidget); + }); + + testWidgets('firmware code 13 while connected shows nothing', + (tester) async { + await pump(tester, + scopeDiscoveryFirmwareTooOld(connected: true, firmwareCode: 13)); + expect(find.text(_noteText), findsNothing); + }); + + testWidgets('disconnected shows nothing', (tester) async { + await pump(tester, + scopeDiscoveryFirmwareTooOld(connected: false, firmwareCode: 11)); + expect(find.text(_noteText), findsNothing); + }); +} diff --git a/test/widgets/status_bar_fit_test.dart b/test/widgets/status_bar_fit_test.dart new file mode 100644 index 00000000..c82a3459 --- /dev/null +++ b/test/widgets/status_bar_fit_test.dart @@ -0,0 +1,234 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +import 'package:mesh_mapper/models/connection_state.dart'; +import 'package:mesh_mapper/models/ping_data.dart'; +import 'package:mesh_mapper/providers/app_state_provider.dart'; +import 'package:mesh_mapper/widgets/status_bar.dart'; + +/// Renders the real [StatusBar] at real phone widths with the real Roboto and +/// Material Icons fonts from the Flutter SDK (the test font draws every glyph +/// as a square, so widths would be meaningless without them), and checks the +/// row never overflows. Skipped when the SDK fonts cannot be found. + +const _fontNames = { + 'Roboto': [ + 'Roboto-Regular.ttf', + 'Roboto-Medium.ttf', + 'Roboto-Bold.ttf', + ], + 'MaterialIcons': ['MaterialIcons-Regular.otf'], +}; + +String? _fontDir() { + final root = Platform.environment['FLUTTER_ROOT']; + if (root == null) return null; + final dir = '$root/bin/cache/artifacts/material_fonts'; + final ok = _fontNames.values + .expand((f) => f) + .every((f) => File('$dir/$f').existsSync()); + return ok ? dir : null; +} + +Future _loadFonts(String dir) async { + for (final entry in _fontNames.entries) { + final loader = FontLoader(entry.key); + for (final file in entry.value) { + final bytes = File('$dir/$file').readAsBytesSync(); + loader.addFont(Future.value(ByteData.sublistView(bytes))); + } + await loader.load(); + } +} + +/// Only the getters the status bar reads. +class _FakeAppState extends ChangeNotifier implements AppStateProvider { + _FakeAppState({ + required this.pingStats, + this.autoMode = AutoMode.passive, + this.scopeDiscoveryActive = false, + }); + + @override + final PingStats pingStats; + @override + final AutoMode autoMode; + @override + final bool scopeDiscoveryActive; + + @override + bool get offlineMode => false; + @override + GpsStatus get gpsStatus => GpsStatus.locked; + @override + bool? get inZone => true; + @override + String? get zoneCode => 'YOW'; + @override + String? get shortZoneCode => 'YOW'; + @override + bool get isConnected => true; + @override + bool get floodDisabled => false; + @override + bool get txAllowed => true; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +PingStats _stats(int tx, int rx, int disc, int trace, int scope, int up) => + PingStats( + txCount: tx, + rxCount: rx, + discCount: disc, + traceCount: trace, + scopeCount: scope, + successfulUploads: up, + ); + +/// Counts with the given number of digits, mixed like a real drive. +PingStats _digits(int n) => switch (n) { + 1 => _stats(9, 7, 8, 6, 5, 9), + 2 => _stats(42, 37, 88, 12, 23, 99), + 3 => _stats(142, 337, 210, 104, 151, 389), + 4 => _stats(9876, 8765, 7654, 6543, 5432, 9999), + _ => _stats(9876543, 8765432, 7654321, 6543210, 5432109, 9999999), + }; + +enum _Slot { trace, scope, hidden } + +/// [slot] picks the mode and switch that lead to it. Hidden also needs no +/// scope counted this session, since a count keeps the Scope chip up. +_FakeAppState _app(PingStats stats, _Slot slot) => _FakeAppState( + pingStats: slot == _Slot.hidden ? stats.copyWith(scopeCount: 0) : stats, + autoMode: slot == _Slot.trace ? AutoMode.targeted : AutoMode.passive, + scopeDiscoveryActive: slot == _Slot.scope, + ); + +/// Pumps the bar at [width] and returns the spare width: what is left of +/// the row after the region chip, the gap and the stats at their natural +/// (unscaled) size. Negative means the FittedBox had to shrink the stats. +Future _pumpBar(WidgetTester tester, double width, _FakeAppState app, + double textScale) async { + tester.view.devicePixelRatio = 3; + tester.view.physicalSize = Size(width * 3, 300 * 3); + addTearDown(tester.view.reset); + + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: app, + child: MaterialApp( + theme: ThemeData(fontFamily: 'Roboto'), + home: MediaQuery( + data: MediaQueryData( + size: Size(width, 300), + textScaler: TextScaler.linear(textScale), + ), + child: const Scaffold( + body: Align(alignment: Alignment.topCenter, child: StatusBar()), + ), + ), + ), + ), + ); + await tester.pump(); + + expect(tester.takeException(), isNull, + reason: 'overflow at $width px, scale $textScale'); + + final bar = tester.getRect(find.byType(StatusBar)); + final stats = find.byKey(const ValueKey('status-bar-stats')); + final statsRect = tester.getRect(stats); + // Every chip stays on screen. + expect(statsRect.right, lessThanOrEqualTo(bar.right + 0.01)); + expect(statsRect.left, greaterThanOrEqualTo(bar.left - 0.01)); + + final naturalStats = tester.getSize(stats).width; + final region = tester + .getSize(find + .ancestor(of: find.text('YOW'), matching: find.byType(Container)) + .first) + .width; + // Bar padding 10 each side, gap 5 between region and stats. + return bar.width - 20 - region - 5 - naturalStats; +} + +void main() { + final fontDir = _fontDir(); + final skip = fontDir == null ? 'Flutter SDK material fonts not found' : null; + + setUpAll(() async { + if (fontDir != null) await _loadFonts(fontDir); + }); + + for (final width in [320.0, 375.0, 393.0]) { + for (final digits in [1, 2, 3, 4, 7]) { + for (final slot in _Slot.values) { + for (final scale in [1.0, 1.3]) { + testWidgets( + 'no overflow at ${width.toInt()} px, $digits-digit counts, ' + '${slot.name}, text x$scale', (tester) async { + final spare = await _pumpBar( + tester, width, _app(_digits(digits), slot), scale); + // At normal text the counts this phone sees in a drive (up to + // 4 digits, shortened to "9.9k") fit on a 375 pt phone without + // any shrinking. + if (width >= 375 && scale == 1.0 && digits <= 4) { + expect(spare, greaterThanOrEqualTo(0), + reason: 'stats had to shrink at $width px'); + } + if (width == 375 && scale == 1.0) { + // ignore: avoid_print + print('[fit] 375 px $digits digits ${slot.name}: ' + 'spare ${spare.toStringAsFixed(1)} px'); + } + }, skip: skip != null); + } + } + } + } + + testWidgets('a swap between Trace and Scope keeps both counts', + (tester) async { + final stats = _stats(1, 2, 3, 44, 55, 6); + final route = find.byIcon(Icons.route); + final scope = find.byIcon(Icons.travel_explore); + + await _pumpBar(tester, 375, _app(stats, _Slot.trace), 1); + expect(route, findsOneWidget); + expect(scope, findsNothing); + expect(find.text('44'), findsOneWidget); + + // Trace mode left, scope discovery on: Scope takes the slot. + await _pumpBar(tester, 375, _app(stats, _Slot.scope), 1); + expect(scope, findsOneWidget); + expect(route, findsNothing); + expect(find.text('55'), findsOneWidget); + + // Scope discovery off again: the session's count keeps it up. + await _pumpBar(tester, 375, + _FakeAppState(pingStats: stats, scopeDiscoveryActive: false), 1); + expect(scope, findsOneWidget); + expect(find.text('55'), findsOneWidget); + + // Nothing counted and neither mode: the slot is gone. + await _pumpBar(tester, 375, _app(stats, _Slot.hidden), 1); + expect(scope, findsNothing); + expect(route, findsNothing); + }); + + testWidgets('counts from 1000 are shortened', (tester) async { + await _pumpBar(tester, 375, + _app(_stats(1400, 999, 12345, 0, 1234567, 1000), _Slot.scope), 1); + expect(find.text('1.4k'), findsOneWidget); + expect(find.text('999'), findsOneWidget); + expect(find.text('12k'), findsOneWidget); + expect(find.text('1.2M'), findsOneWidget); + expect(find.text('1.0k'), findsOneWidget); + }); +} diff --git a/test/widgets/status_bar_slot_test.dart b/test/widgets/status_bar_slot_test.dart new file mode 100644 index 00000000..b2489369 --- /dev/null +++ b/test/widgets/status_bar_slot_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/widgets/status_bar.dart'; + +void main() { + group('statusBarSharedSlot', () { + test('Trace mode shows Trace', () { + expect( + statusBarSharedSlot( + targetedMode: true, scopeDiscoveryOn: false, scopeCount: 0), + StatusBarSlot.trace); + }); + + test('Trace mode wins even with scope discovery on and scopes counted', () { + expect( + statusBarSharedSlot( + targetedMode: true, scopeDiscoveryOn: true, scopeCount: 12), + StatusBarSlot.trace); + }); + + test('scope discovery on shows Scope, even before the first answer', () { + expect( + statusBarSharedSlot( + targetedMode: false, scopeDiscoveryOn: true, scopeCount: 0), + StatusBarSlot.scope); + }); + + test('scopes counted this session keep Scope after it is turned off', () { + expect( + statusBarSharedSlot( + targetedMode: false, scopeDiscoveryOn: false, scopeCount: 3), + StatusBarSlot.scope); + }); + + test('neither hides the slot', () { + expect( + statusBarSharedSlot( + targetedMode: false, scopeDiscoveryOn: false, scopeCount: 0), + StatusBarSlot.hidden); + }); + }); +} diff --git a/test/widgets/update_required_panel_test.dart b/test/widgets/update_required_panel_test.dart new file mode 100644 index 00000000..184a86ef --- /dev/null +++ b/test/widgets/update_required_panel_test.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mesh_mapper/utils/store_links.dart'; +import 'package:mesh_mapper/widgets/update_required_panel.dart'; + +void main() { + testWidgets('shows the versions and opens the Play link', (tester) async { + // The installer source the provider would have read on a Play install. + final link = + StoreLinks.resolve(TargetPlatform.android, 'com.android.vending'); + StoreLink? opened; + var backTapped = false; + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: UpdateRequiredPanel( + requirement: AppUpdateRequirement( + errorMessage: 'out of date', + versionLine: appUpdateVersionLine('APP-1.3.0', '1.4.0'), + link: link, + ), + onUpdate: (l) => opened = l, + onBack: () => backTapped = true, + ), + ), + )); + + expect(find.text(UpdateRequiredPanel.title), findsOneWidget); + expect(find.text(UpdateRequiredPanel.body), findsOneWidget); + expect(find.text('Your version: 1.3.0 · Needed: 1.4.0'), findsOneWidget); + + await tester.tap(find.text('Update MeshMapper')); + expect(opened, StoreLinks.playStore); + + await tester.tap(find.text('Back')); + expect(backTapped, isTrue); + }); + + testWidgets('a sideloaded APK offers the release download', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: UpdateRequiredPanel( + requirement: AppUpdateRequirement( + errorMessage: 'out of date', + versionLine: appUpdateVersionLine('APP-1.3.0', null), + link: StoreLinks.resolve(TargetPlatform.android, null), + ), + onUpdate: (_) {}, + onBack: () {}, + ), + ), + )); + + expect(find.text('Download latest version'), findsOneWidget); + expect(find.text('Your version: 1.3.0'), findsOneWidget); + }); +} diff --git a/tool/__init__.py b/tool/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tool/store_screenshots/capture_android.sh b/tool/store_screenshots/capture_android.sh new file mode 100755 index 00000000..e1ee0847 --- /dev/null +++ b/tool/store_screenshots/capture_android.sh @@ -0,0 +1,346 @@ +#!/usr/bin/env bash +# Capture the Play Store phone screenshots from an Android emulator. +# +# Usage: tool/store_screenshots/capture_android.sh --version X.Y.Z [--out DIR] +# +# Writes android-phone/ under DIR (default +# ~/Documents/MeshMapper_Apps/store-screenshots/X.Y.Z), then contact_sheet.html. +# Exits non-zero if any image is missing or has the wrong size. +# +# Needs the Android command-line tools with the emulator and the +# system-images;android-36;google_apis;arm64-v8a image, and Homebrew openjdk@21. +# The meshmapper_store_api36 AVD (Pixel 2, 1080x1920) is created if it is +# missing. Secrets come from ~/.meshmapper_release.env and are never printed. +# +# For iterating (not used by the release flow): +# SKIP_BUILD=1 reuse build/app/outputs/flutter-apk/app-debug.apk +# EMULATOR_GPU=mode pass -gpu to the emulator (e.g. swiftshader_indirect) +# ANDROID_TAIL_START=N which of the 6 tail points the drive starts from +# +# The emulator is headless, runs on its own port and is addressed by serial, so +# real phones that are plugged in are never touched. It is killed, SystemUI demo +# mode is left, and the capture file is deleted when the script ends, also when +# it fails. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" + +# ---------------------------------------------------------------- constants +BUNDLE_ID="net.meshmapper.app" +ACTIVITY="$BUNDLE_ID/.MainActivity" +CAPTURE_FILE_NAME="store_capture.json" +ROUTE_FILE="$REPO_ROOT/lib/debug/store_capture_route.dart" +APK_PATH="$REPO_ROOT/build/app/outputs/flutter-apk/app-debug.apk" + +SDK="${ANDROID_SDK_ROOT:-/opt/homebrew/share/android-commandlinetools}" +AVD_NAME="meshmapper_store_api36" +AVD_IMAGE="system-images;android-36;google_apis;arm64-v8a" +AVD_DEVICE="pixel_2" +# An even port keeps clear of the 5554 that the other emulators use by default. +EMU_PORT="${EMU_PORT:-5584}" +SERIAL="emulator-$EMU_PORT" + +# maplibre_gl 0.27.1 needs JDK 21 to compile (same as Build.sh). +JDK21_HOME="/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home" + +PHONE_SIZE="1080x1920" +PHONE_SCREENS="map log history" +OUT_SET="android-phone" + +# Seconds. The map follows the GPS once it has a fix, so the app gets +# LAUNCH_WAIT to load the sample drive, then the fixes are fed in FIX_INTERVAL +# apart and the picture settles for SETTLE_WAIT before the shot. +LAUNCH_WAIT="${LAUNCH_WAIT:-14}" +FIX_INTERVAL="${FIX_INTERVAL:-3}" +SETTLE_WAIT="${SETTLE_WAIT:-8}" +BOOT_TIMEOUT="${BOOT_TIMEOUT:-900}" + +# Which of the 6 tail points the drive starts from. The map does not follow the +# GPS, so the camera stays centred on the first fix and the arrow ends up +# (distance from that point) away from the centre. Starting at point 0 puts it +# 175 m out, which on a narrow phone lands the arrow under the map-controls +# rail; starting later keeps it clear of the rail. +ANDROID_TAIL_START="${ANDROID_TAIL_START:-2}" + +# ---------------------------------------------------------------- helpers +log() { printf '[capture] %s\n' "$*" >&2; } +die() { printf '[capture] ERROR: %s\n' "$*" >&2; exit 1; } + +usage() { + echo "Usage: $0 --version X.Y.Z [--out DIR]" >&2 + exit 2 +} + +VERSION="" +OUT="" +while [ $# -gt 0 ]; do + case "$1" in + --version) [ $# -ge 2 ] || usage; VERSION="$2"; shift 2 ;; + --out) [ $# -ge 2 ] || usage; OUT="$2"; shift 2 ;; + -h|--help) usage ;; + *) usage ;; + esac +done +[ -n "$VERSION" ] || usage +case "$VERSION" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) die "--version must look like X.Y.Z, got '$VERSION'" ;; +esac +[ -n "$OUT" ] || OUT="$HOME/Documents/MeshMapper_Apps/store-screenshots/$VERSION" + +# Use the adb that is already on PATH: a different adb version restarts the +# server and drops the adb-over-wifi devices that may be connected. +if command -v adb >/dev/null 2>&1; then + ADB="$(command -v adb)" +else + ADB="$SDK/platform-tools/adb" +fi +[ -x "$ADB" ] || die "adb not found" +EMULATOR="$SDK/emulator/emulator" +AVDMANAGER="$SDK/cmdline-tools/latest/bin/avdmanager" +[ -x "$EMULATOR" ] || die "no emulator at $EMULATOR" + +# Every call goes to the emulator by serial, never to another attached device. +adb_() { "$ADB" -s "$SERIAL" "$@"; } + +# ---------------------------------------------------------------- cleanup +EMU_PID="" +EMU_LOG="" +EMU_UP=0 + +# Best-effort cleanup, run on every exit. Never fails the script by itself. +cleanup() { + local status=$? + set +e + trap - EXIT INT TERM + if [ "$EMU_UP" = "1" ]; then + adb_ shell run-as "$BUNDLE_ID" rm -f "app_flutter/$CAPTURE_FILE_NAME" >/dev/null 2>&1 + adb_ shell am broadcast -a com.android.systemui.demo -e command exit >/dev/null 2>&1 + adb_ shell settings put global sysui_demo_allowed 0 >/dev/null 2>&1 + adb_ shell svc data enable >/dev/null 2>&1 + # The settings provider writes lazily; without this the AVD keeps the + # values from before the cleanup. + sleep 2 + adb_ shell sync >/dev/null 2>&1 + adb_ emu kill >/dev/null 2>&1 + fi + if [ -n "$EMU_PID" ]; then + local waited=0 + while kill -0 "$EMU_PID" 2>/dev/null && [ "$waited" -lt 15 ]; do + sleep 1 + waited=$((waited + 1)) + done + kill "$EMU_PID" >/dev/null 2>&1 + sleep 1 + kill -9 "$EMU_PID" >/dev/null 2>&1 + wait "$EMU_PID" >/dev/null 2>&1 + fi + if [ "$status" -eq 0 ] && [ -n "$EMU_LOG" ]; then + rm -f "$EMU_LOG" + elif [ -n "$EMU_LOG" ]; then + log "emulator log kept at $EMU_LOG" + fi + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT TERM + +# ---------------------------------------------------------------- preflight +[ -d "$JDK21_HOME" ] || die "JDK 21 not found at $JDK21_HOME (brew install openjdk@21)" +export JAVA_HOME="$JDK21_HOME" +export PATH="$JAVA_HOME/bin:$PATH" +export ANDROID_SDK_ROOT="$SDK" +export ANDROID_HOME="$SDK" + +# The last 6 points of the sample drive; the GPS arrow sits on the final one. +TAIL=() +while IFS= read -r point; do + TAIL+=("$point") +done < <(grep -oE '\(4[0-9.]+, -7[0-9.]+\)' "$ROUTE_FILE" | tail -6 | tr -d '() ' ) +[ "${#TAIL[@]}" -eq 6 ] || die "expected 6 route points in $ROUTE_FILE, found ${#TAIL[@]}" +log "drive tail: ${TAIL[*]}" +case "$ANDROID_TAIL_START" in + [0-4]) ;; + *) die "ANDROID_TAIL_START must be 0-4, got '$ANDROID_TAIL_START'" ;; +esac +DRIVE=("${TAIL[@]:$ANDROID_TAIL_START}") + +# Secrets: loaded into the environment, never echoed. +[ -f "$HOME/.meshmapper_release.env" ] || die "missing ~/.meshmapper_release.env" +set -a +# shellcheck disable=SC1091 +source "$HOME/.meshmapper_release.env" +set +a +: "${MESHMAPPER_API_KEY:?MESHMAPPER_API_KEY is not set in ~/.meshmapper_release.env}" + +# ---------------------------------------------------------------- build +cd "$REPO_ROOT" +if [ "${SKIP_BUILD:-0}" = "1" ]; then + log "SKIP_BUILD=1: reusing $APK_PATH" +else + log "building the debug APK" + flutter build apk --debug --target-platform android-arm64 \ + --dart-define="API_KEY=$MESHMAPPER_API_KEY" \ + --dart-define="APP_VERSION=APP-$VERSION" >&2 +fi +[ -f "$APK_PATH" ] || die "no APK at $APK_PATH" + +# ---------------------------------------------------------------- emulator +if ! "$EMULATOR" -list-avds | grep -qx "$AVD_NAME"; then + [ -x "$AVDMANAGER" ] || die "no avdmanager at $AVDMANAGER" + log "creating the $AVD_NAME AVD" + # "no" declines the custom hardware profile prompt. + echo no | "$AVDMANAGER" create avd -n "$AVD_NAME" -k "$AVD_IMAGE" -d "$AVD_DEVICE" >&2 +fi + +if "$ADB" devices | grep -q "^$SERIAL"; then + die "$SERIAL is already running; stop it or set EMU_PORT" +fi + +EMU_LOG="$(mktemp -t meshmapper_emulator)" +EMU_ARGS=(-avd "$AVD_NAME" -port "$EMU_PORT" -no-window -no-audio -no-snapshot-save -no-boot-anim) +if [ -n "${EMULATOR_GPU:-}" ]; then + EMU_ARGS+=(-gpu "$EMULATOR_GPU") +fi +log "starting the emulator ($AVD_NAME on $SERIAL${EMULATOR_GPU:+, gpu $EMULATOR_GPU})" +"$EMULATOR" "${EMU_ARGS[@]}" >"$EMU_LOG" 2>&1 & +EMU_PID=$! +EMU_UP=1 + +log "waiting for the emulator to boot" +adb_ wait-for-device +boot_start=$SECONDS +until [ "$(adb_ shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do + kill -0 "$EMU_PID" 2>/dev/null || die "the emulator exited while booting" + [ $((SECONDS - boot_start)) -lt "$BOOT_TIMEOUT" ] || die "the emulator did not boot within ${BOOT_TIMEOUT}s" + sleep 3 +done +log "booted after $((SECONDS - boot_start))s" +sleep 5 +# Keep the screen lit and unlocked for the whole run. +adb_ shell svc power stayon true >/dev/null +adb_ shell input keyevent 82 >/dev/null +adb_ shell wm dismiss-keyguard >/dev/null 2>&1 || true + +# ---------------------------------------------------------------- location +# Google Play Services asks for "Location Accuracy" the first time the app asks +# for a position, and its dialog sits over the map. The answer lives in the AVD, +# so this only taps anything on a fresh emulator. The switch is read from the +# UI because assisted_gps_enabled can be set without changing it. +location_accuracy_state() { # prints true or false, nothing if the switch is not found + adb_ shell uiautomator dump /data/local/tmp/store_ui.xml >/dev/null 2>&1 || return 0 + adb_ exec-out cat /data/local/tmp/store_ui.xml \ + | grep -o 'resource-id="android:id/switch_widget"[^>]*' \ + | grep -o 'checked="[a-z]*"' | head -1 | cut -d'"' -f2 || true +} + +ensure_location_accuracy() { + local state + adb_ shell am start -a com.google.android.gms.location.settings.LOCATION_ACCURACY >/dev/null 2>&1 + sleep 3 + state="$(location_accuracy_state)" + case "$state" in + true) ;; + false) + log "turning on Google Location Accuracy" + adb_ shell input tap 540 676 + sleep 2 + [ "$(location_accuracy_state)" = "true" ] || die "could not turn on Google Location Accuracy" + ;; + *) die "could not read the Google Location Accuracy switch" ;; + esac + adb_ shell input keyevent KEYCODE_HOME + sleep 1 +} +ensure_location_accuracy + +# ---------------------------------------------------------------- app +# Fresh install so no earlier run can leak into the shots. +adb_ uninstall "$BUNDLE_ID" >/dev/null 2>&1 || true +adb_ install -r "$APK_PATH" >/dev/null +# Without these the OS permission prompts cover the map. BLUETOOTH_SCAN and +# BLUETOOTH_CONNECT are the "nearby devices" prompt the app raises at launch. +for perm in ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION ACCESS_BACKGROUND_LOCATION \ + POST_NOTIFICATIONS BLUETOOTH_SCAN BLUETOOTH_CONNECT; do + adb_ shell pm grant "$BUNDLE_ID" "android.permission.$perm" >&2 \ + || die "could not grant $perm" +done + +# ---------------------------------------------------------------- status bar +# Mobile data off drops the "3G" label next to the signal bars (the demo +# datatype extra does not hide it); the console call sets the bars to full. +adb_ shell svc data disable +adb_ emu gsm signal-profile 4 >/dev/null +demo() { # command [extras...] + adb_ shell am broadcast -a com.android.systemui.demo -e command "$@" >/dev/null +} +adb_ shell settings put global sysui_demo_allowed 1 +demo enter +demo clock -e hhmm 0941 +demo battery -e level 100 -e plugged false +demo network -e mobile show -e level 4 -e wifi show -e level 4 -e fully true -e datatype none -e sims 1 +demo notifications -e visible false + +# ---------------------------------------------------------------- shots +# The console wants longitude first. Without an altitude the accuracy chip on +# the map reads "0m"; downtown Ottawa is about 70 m up. +geo_fix() { # "lat,lon" + local point="$1" + adb_ emu geo fix "${point#*,}" "${point%,*}" 70 >/dev/null +} + +write_capture_file() { # screen + printf '{"screen":"%s"}' "$1" \ + | adb_ shell "run-as $BUNDLE_ID sh -c 'mkdir -p app_flutter && cat > app_flutter/$CAPTURE_FILE_NAME'" +} + +DIR="$OUT/$OUT_SET" +mkdir -p "$DIR" +n=0 +for screen in $PHONE_SCREENS; do + n=$((n + 1)) + log "phone: $screen" + write_capture_file "$screen" + geo_fix "${DRIVE[0]}" + adb_ shell am force-stop "$BUNDLE_ID" + adb_ shell am start -n "$ACTIVITY" >/dev/null + sleep "$LAUNCH_WAIT" + for point in "${DRIVE[@]}"; do + geo_fix "$point" + sleep "$FIX_INTERVAL" + done + sleep "$SETTLE_WAIT" + adb_ exec-out screencap -p > "$DIR/0${n}_${screen}.png" +done + +adb_ shell am force-stop "$BUNDLE_ID" +# The trap removes the capture file, leaves demo mode and kills the emulator. + +# ---------------------------------------------------------------- size check +BAD=0 +check_size() { # file WxH + local file="$1" want="$2" got + if [ ! -s "$file" ]; then + log "MISSING $file" + BAD=1 + return + fi + got="$(sips -g pixelWidth -g pixelHeight "$file" 2>/dev/null \ + | awk '/pixelWidth/ {w=$2} /pixelHeight/ {h=$2} END {print w "x" h}')" + if [ "$got" = "$want" ]; then + log "ok $got ${file#"$OUT"/}" + else + log "WRONG SIZE $got (want $want) $file" + BAD=1 + fi +} + +for f in 01_map 02_log 03_history; do check_size "$DIR/$f.png" "$PHONE_SIZE"; done + +/usr/bin/python3 "$SCRIPT_DIR/contact_sheet.py" "$OUT" + +if [ "$BAD" -ne 0 ]; then + die "one or more screenshots are missing or have the wrong size" +fi +log "done" diff --git a/tool/store_screenshots/capture_ios.sh b/tool/store_screenshots/capture_ios.sh new file mode 100755 index 00000000..2f72fc38 --- /dev/null +++ b/tool/store_screenshots/capture_ios.sh @@ -0,0 +1,305 @@ +#!/usr/bin/env bash +# Capture the App Store screenshots from the iOS simulators. +# +# Usage: tool/store_screenshots/capture_ios.sh --version X.Y.Z [--out DIR] +# +# Writes ios-iphone-69/, ios-ipad-13/ and watch-46/ under DIR (default +# ~/Documents/MeshMapper_Apps/store-screenshots/X.Y.Z), then contact_sheet.html. +# Exits non-zero if any image is missing or has the wrong size. +# +# Needs Xcode 26.x and the iOS 26.5 / watchOS 26.5 simulators. Xcode 27 builds +# crash at launch on iOS 27, so the iOS 27 simulators are never used here. +# Secrets come from ~/.meshmapper_release.env and are never printed. +# +# For iterating on one set (not used by the release flow): +# CAPTURE_SETS="ipad" which sets to capture: iphone ipad watch (default: all) +# SKIP_BUILD=1 reuse build/ios/iphonesimulator/Runner.app as it is +# +# Every simulator is shut down and the capture file is deleted when the script +# ends, also when it fails. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" + +# ---------------------------------------------------------------- constants +BUNDLE_ID="net.meshmapper.app" +CAPTURE_FILE_NAME="store_capture.json" +ROUTE_FILE="$REPO_ROOT/lib/debug/store_capture_route.dart" +APP_PATH="$REPO_ROOT/build/ios/iphonesimulator/Runner.app" +WATCH_APP_PATH="$APP_PATH/Watch/MeshMapperWatch.app" + +IOS_RUNTIME="com.apple.CoreSimulator.SimRuntime.iOS-26-5" +IPHONE_NAME="iPhone 17 Pro Max" +IPAD_NAME="iPad Pro 13-inch (M5)" +WATCH_NAME="Apple Watch Series 11 (46mm)" + +IPHONE_SIZE="1320x2868" +IPAD_SIZE="2064x2752" +WATCH_SIZE="416x496" + +# Seconds. The map follows the GPS once it has a fix, so the app gets +# LAUNCH_WAIT to load the sample drive, then the simulated drive runs for +# DRIVE_WAIT before the shot. +LAUNCH_WAIT="${LAUNCH_WAIT:-14}" +DRIVE_WAIT="${DRIVE_WAIT:-22}" +WATCH_WAIT="${WATCH_WAIT:-12}" + +PHONE_SCREENS="map log history" + +# Which of the 6 tail points the drive starts from. The map does not follow the +# GPS, so the camera stays centred on the first fix and the arrow ends up +# (distance from that point) away from the centre. Starting at point 0 puts it +# 175 m out: fine on the iPad, but on the narrow iPhone the arrow lands under +# the map-controls rail. Starting at point 2 (105 m) keeps it clear of the rail. +IPHONE_TAIL_START="${IPHONE_TAIL_START:-2}" +IPAD_TAIL_START="${IPAD_TAIL_START:-0}" +CAPTURE_SETS="${CAPTURE_SETS:-iphone ipad watch}" + +# ---------------------------------------------------------------- helpers +log() { printf '[capture] %s\n' "$*" >&2; } +die() { printf '[capture] ERROR: %s\n' "$*" >&2; exit 1; } + +usage() { + echo "Usage: $0 --version X.Y.Z [--out DIR]" >&2 + exit 2 +} + +VERSION="" +OUT="" +while [ $# -gt 0 ]; do + case "$1" in + --version) [ $# -ge 2 ] || usage; VERSION="$2"; shift 2 ;; + --out) [ $# -ge 2 ] || usage; OUT="$2"; shift 2 ;; + -h|--help) usage ;; + *) usage ;; + esac +done +[ -n "$VERSION" ] || usage +case "$VERSION" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) die "--version must look like X.Y.Z, got '$VERSION'" ;; +esac +[ -n "$OUT" ] || OUT="$HOME/Documents/MeshMapper_Apps/store-screenshots/$VERSION" + +wants() { case " $CAPTURE_SETS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } + +# ---------------------------------------------------------------- simulators +IPHONE="" +IPAD="" +WATCH="" + +resolve_device() { # name -> udid on the pinned iOS runtime + xcrun simctl list devices available -j | /usr/bin/python3 -c ' +import json, sys +name, runtime = sys.argv[1], sys.argv[2] +for dev in json.load(sys.stdin)["devices"].get(runtime, []): + if dev["name"] == name: + print(dev["udid"]) + break +' "$1" "$IOS_RUNTIME" +} + +resolve_watch() { # phone udid, watch name -> udid of the watch paired with it + xcrun simctl list pairs -j | /usr/bin/python3 -c ' +import json, sys +phone, name = sys.argv[1], sys.argv[2] +for pair in json.load(sys.stdin)["pairs"].values(): + if pair["phone"]["udid"] == phone and pair["watch"]["name"] == name: + print(pair["watch"]["udid"]) + break +' "$1" "$2" +} + +# Best-effort cleanup, run on every exit. Never fails the script by itself. +cleanup() { + local status=$? + set +e + trap - EXIT INT TERM + local dev container + for dev in "$IPHONE" "$IPAD" "$WATCH"; do + [ -n "$dev" ] || continue + container="$(xcrun simctl get_app_container "$dev" "$BUNDLE_ID" data 2>/dev/null)" + [ -z "$container" ] || rm -f "$container/Documents/$CAPTURE_FILE_NAME" + # simctl cannot look up a container once the device is shut down, so + # also sweep the files on disk. + rm -f "$HOME/Library/Developer/CoreSimulator/Devices/$dev/data/Containers/Data/Application"/*/Documents/"$CAPTURE_FILE_NAME" + xcrun simctl location "$dev" clear >/dev/null 2>&1 + xcrun simctl status_bar "$dev" clear >/dev/null 2>&1 + xcrun simctl shutdown "$dev" >/dev/null 2>&1 + done + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT TERM + +boot_device() { + local out + if ! out="$(xcrun simctl boot "$1" 2>&1)"; then + case "$out" in + *"current state: Booted"*) ;; + *) die "could not boot $1: $out" ;; + esac + fi + xcrun simctl bootstatus "$1" -b >/dev/null +} + +# ---------------------------------------------------------------- preflight +XCODE_VERSION="$(xcodebuild -version | sed -n '1p')" +case "$XCODE_VERSION" in + "Xcode 26."*) ;; + *) die "the active Xcode must be 26.x (found: $XCODE_VERSION); run xcode-select" ;; +esac + +IPHONE="$(resolve_device "$IPHONE_NAME")" +[ -n "$IPHONE" ] || die "no '$IPHONE_NAME' simulator on $IOS_RUNTIME" +IPAD="$(resolve_device "$IPAD_NAME")" +[ -n "$IPAD" ] || die "no '$IPAD_NAME' simulator on $IOS_RUNTIME" +WATCH="$(resolve_watch "$IPHONE" "$WATCH_NAME")" +[ -n "$WATCH" ] || die "'$WATCH_NAME' is not paired with the '$IPHONE_NAME' simulator" +log "iPhone $IPHONE, iPad $IPAD, Watch $WATCH" + +# The last 6 points of the sample drive; the GPS arrow sits on the final one. +TAIL=() +while IFS= read -r point; do + TAIL+=("$point") +done < <(grep -oE '\(4[0-9.]+, -7[0-9.]+\)' "$ROUTE_FILE" | tail -6 | tr -d '() ' ) +[ "${#TAIL[@]}" -eq 6 ] || die "expected 6 route points in $ROUTE_FILE, found ${#TAIL[@]}" +log "drive tail: ${TAIL[*]}" + +# Secrets: loaded into the environment, never echoed. +[ -f "$HOME/.meshmapper_release.env" ] || die "missing ~/.meshmapper_release.env" +set -a +# shellcheck disable=SC1091 +source "$HOME/.meshmapper_release.env" +set +a +: "${MESHMAPPER_API_KEY:?MESHMAPPER_API_KEY is not set in ~/.meshmapper_release.env}" + +# ---------------------------------------------------------------- build +cd "$REPO_ROOT" +if [ "${SKIP_BUILD:-0}" = "1" ]; then + log "SKIP_BUILD=1: reusing $APP_PATH" +else + log "building the simulator app (debug, $XCODE_VERSION)" + flutter build ios --simulator --debug -d "$IPHONE" \ + --dart-define="API_KEY=$MESHMAPPER_API_KEY" \ + --dart-define="APP_VERSION=APP-$VERSION" +fi +[ -d "$APP_PATH" ] || die "no simulator app at $APP_PATH" + +# ---------------------------------------------------------------- phone shots +capture_phone() { # label udid outdir tail-start-index + local label="$1" dev="$2" dir="$3" start="$4" container capture_file screen n=0 + local drive=("${TAIL[@]:$start}") + log "$label: boot" + mkdir -p "$dir" + boot_device "$dev" + xcrun simctl status_bar "$dev" override --time 9:41 --dataNetwork wifi \ + --wifiMode active --wifiBars 3 --cellularMode active --cellularBars 4 \ + --batteryState charged --batteryLevel 100 + + # Fresh install so no earlier run can leak into the shots. + xcrun simctl uninstall "$dev" "$BUNDLE_ID" >/dev/null 2>&1 || true + xcrun simctl install "$dev" "$APP_PATH" + # Without these the OS location prompt covers the map. + xcrun simctl privacy "$dev" grant location-always "$BUNDLE_ID" + xcrun simctl privacy "$dev" grant location "$BUNDLE_ID" + + container="$(xcrun simctl get_app_container "$dev" "$BUNDLE_ID" data)" + mkdir -p "$container/Documents" + capture_file="$container/Documents/$CAPTURE_FILE_NAME" + + for screen in $PHONE_SCREENS; do + n=$((n + 1)) + log "$label: $screen" + printf '{"screen":"%s"}' "$screen" > "$capture_file" + xcrun simctl location "$dev" set "${drive[0]}" + xcrun simctl terminate "$dev" "$BUNDLE_ID" >/dev/null 2>&1 || true + xcrun simctl launch "$dev" "$BUNDLE_ID" >/dev/null + sleep "$LAUNCH_WAIT" + xcrun simctl location "$dev" start --speed=12 --interval=1 "${drive[@]}" + sleep "$DRIVE_WAIT" + xcrun simctl io "$dev" screenshot --type=png "$dir/0${n}_${screen}.png" >/dev/null 2>&1 + done + + xcrun simctl terminate "$dev" "$BUNDLE_ID" >/dev/null 2>&1 || true + xcrun simctl location "$dev" clear + rm -f "$capture_file" + xcrun simctl status_bar "$dev" clear + xcrun simctl shutdown "$dev" +} + +# ---------------------------------------------------------------- watch shots +capture_watch() { # outdir + local dir="$1" watch_bundle + log "watch: boot" + mkdir -p "$dir" + [ -d "$WATCH_APP_PATH" ] || die "no Watch app at $WATCH_APP_PATH" + watch_bundle="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$WATCH_APP_PATH/Info.plist")" + boot_device "$WATCH" + # status_bar override is not supported on the watch; the clock stays real. + xcrun simctl status_bar "$WATCH" override --time 9:41 >/dev/null 2>&1 || true + + xcrun simctl uninstall "$WATCH" "$watch_bundle" >/dev/null 2>&1 || true + xcrun simctl install "$WATCH" "$WATCH_APP_PATH" + + watch_shot "$WATCH" "$watch_bundle" "$dir/01_map.png" \ + -MeshMapperSampleData YES -MeshMapperInitialPage 0 + watch_shot "$WATCH" "$watch_bundle" "$dir/02_readout.png" \ + -MeshMapperSampleData YES -MeshMapperInitialPage 0 -layout.mainPageContent readout + watch_shot "$WATCH" "$watch_bundle" "$dir/03_heard.png" \ + -MeshMapperSampleData YES -MeshMapperInitialPage 2 + + xcrun simctl terminate "$WATCH" "$watch_bundle" >/dev/null 2>&1 || true + xcrun simctl shutdown "$WATCH" +} + +watch_shot() { # dev bundle file launch-args... + local dev="$1" bundle="$2" file="$3" + shift 3 + log "watch: $(basename "$file")" + xcrun simctl terminate "$dev" "$bundle" >/dev/null 2>&1 || true + xcrun simctl launch "$dev" "$bundle" "$@" >/dev/null + sleep "$WATCH_WAIT" + xcrun simctl io "$dev" screenshot --type=png "$file" >/dev/null 2>&1 +} + +if wants iphone; then capture_phone "iphone" "$IPHONE" "$OUT/ios-iphone-69" "$IPHONE_TAIL_START"; fi +if wants ipad; then capture_phone "ipad" "$IPAD" "$OUT/ios-ipad-13" "$IPAD_TAIL_START"; fi +if wants watch; then capture_watch "$OUT/watch-46"; fi + +# ---------------------------------------------------------------- size check +BAD=0 +check_size() { # file WxH + local file="$1" want="$2" got + if [ ! -f "$file" ]; then + log "MISSING $file" + BAD=1 + return + fi + got="$(sips -g pixelWidth -g pixelHeight "$file" \ + | awk '/pixelWidth/ {w=$2} /pixelHeight/ {h=$2} END {print w "x" h}')" + if [ "$got" = "$want" ]; then + log "ok $got ${file#"$OUT"/}" + else + log "WRONG SIZE $got (want $want) $file" + BAD=1 + fi +} + +if wants iphone; then + for f in 01_map 02_log 03_history; do check_size "$OUT/ios-iphone-69/$f.png" "$IPHONE_SIZE"; done +fi +if wants ipad; then + for f in 01_map 02_log 03_history; do check_size "$OUT/ios-ipad-13/$f.png" "$IPAD_SIZE"; done +fi +if wants watch; then + for f in 01_map 02_readout 03_heard; do check_size "$OUT/watch-46/$f.png" "$WATCH_SIZE"; done +fi + +/usr/bin/python3 "$SCRIPT_DIR/contact_sheet.py" "$OUT" + +if [ "$BAD" -ne 0 ]; then + die "one or more screenshots are missing or have the wrong size" +fi +log "done" diff --git a/tool/store_screenshots/contact_sheet.py b/tool/store_screenshots/contact_sheet.py new file mode 100755 index 00000000..1bc0b8c3 --- /dev/null +++ b/tool/store_screenshots/contact_sheet.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Build contact_sheet.html for a store-screenshots folder. + +Usage: contact_sheet.py DIR + +DIR holds one sub-folder per screenshot set (see SET_ORDER). The page lists +each set with a row of its PNGs, in file-name order, using paths relative to +the page so the folder can be moved or zipped. A set with no PNGs says +"missing". Standard library only; runs on the system python3 (3.9). +""" +from __future__ import annotations + +import argparse +import html +import sys +from pathlib import Path +from typing import List, Optional + +SET_ORDER = ["ios-iphone-69", "ios-ipad-13", "watch-46", "android-phone"] + +_STYLE = """ +body { font-family: -apple-system, Helvetica, Arial, sans-serif; margin: 24px; + background: #f4f4f6; color: #1c1c1e; } +h1 { font-size: 20px; } +h2 { font-size: 16px; margin: 28px 0 8px; } +.row { display: flex; flex-wrap: wrap; gap: 16px; align-items: flex-start; } +figure { margin: 0; } +figure img { height: 560px; width: auto; border: 1px solid #c7c7cc; + background: #fff; } +figcaption { font-size: 12px; color: #636366; margin-top: 4px; } +.empty { color: #b00020; font-weight: 600; } +""" + + +def _images(set_dir: Path) -> List[Path]: + if not set_dir.is_dir(): + return [] + return sorted( + (p for p in set_dir.iterdir() if p.is_file() and p.suffix.lower() == ".png"), + key=lambda p: p.name, + ) + + +def build_html(root: Path) -> str: + root = Path(root) + parts = [ + "", + '', + "MeshMapper store screenshots", + f"", + f"

MeshMapper store screenshots: {html.escape(root.name)}

", + ] + for name in SET_ORDER: + parts.append(f"

{html.escape(name)}

") + images = _images(root / name) + if not images: + parts.append('

missing

') + continue + parts.append('
') + for image in images: + rel = html.escape(f"{name}/{image.name}", quote=True) + parts.append( + f'
{rel}' + f"
{html.escape(image.name)}
" + ) + parts.append("
") + parts.append("") + return "\n".join(parts) + "\n" + + +def write_contact_sheet(root: Path) -> Path: + root = Path(root) + out = root / "contact_sheet.html" + out.write_text(build_html(root), encoding="utf-8") + return out + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("dir", type=Path, help="store-screenshots folder") + args = parser.parse_args(argv) + if not args.dir.is_dir(): + print(f"not a directory: {args.dir}", file=sys.stderr) + return 2 + print(write_contact_sheet(args.dir)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tool/tests/__init__.py b/tool/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tool/tests/test_asc_store.py b/tool/tests/test_asc_store.py new file mode 100644 index 00000000..10f8777b --- /dev/null +++ b/tool/tests/test_asc_store.py @@ -0,0 +1,721 @@ +from __future__ import annotations + +import contextlib +import io +import os +import struct +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +# asc_store.py lives in the repo root, next to Build.sh. +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +import asc_store # noqa: E402 + +Fail = asc_store.Fail + + +def _version(version_string: str, state: str, vid: str = 'v1') -> dict: + return {'id': vid, 'type': 'appStoreVersions', + 'attributes': {'versionString': version_string, 'appStoreState': state, + 'releaseType': 'AFTER_APPROVAL'}} + + +class CheckStoreTextTest(unittest.TestCase): + def test_accepts_accented_letters(self) -> None: + asc_store.check_store_text('whats_new', 'Fixed the map. Café menu.') + + def test_rejects_emoji(self) -> None: + with self.assertRaises(Fail): + asc_store.check_store_text('whats_new', 'New \U0001F680') + + def test_rejects_dingbats_and_variation_selector(self) -> None: + for text in ('Done ✔', 'Heart ❤️', 'Sun ☀'): + with self.subTest(text=text), self.assertRaises(Fail): + asc_store.check_store_text('whats_new', text) + + def test_rejects_empty(self) -> None: + for text in ('', ' \n'): + with self.subTest(text=text), self.assertRaises(Fail): + asc_store.check_store_text('whats_new', text) + + def test_length_limit(self) -> None: + asc_store.check_store_text('whats_new', 'x' * 4000) + with self.assertRaises(Fail): + asc_store.check_store_text('whats_new', 'x' * 4001) + + +class CheckLocalesTest(unittest.TestCase): + def test_accepts_english(self) -> None: + asc_store.check_locales(['en-CA']) + asc_store.check_locales(['en-CA', 'en-US']) + + def test_names_the_first_non_english_locale(self) -> None: + with self.assertRaises(Fail) as ctx: + asc_store.check_locales(['en-CA', 'fr-CA', 'de-DE']) + self.assertIn('fr-CA', str(ctx.exception)) + self.assertNotIn('de-DE', str(ctx.exception)) + + +class ChooseVersionTest(unittest.TestCase): + def test_creates_when_nothing_is_editable(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE') + self.assertEqual(asc_store.choose_version([live], '1.4.1'), ('create', None)) + + def test_reuses_the_matching_editable_version(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE', 'v0') + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'v1') + self.assertEqual(asc_store.choose_version([live, editable], '1.4.1'), + ('reuse', editable)) + + def test_refuses_a_different_editable_version(self) -> None: + editable = _version('1.4.2', 'PREPARE_FOR_SUBMISSION') + with self.assertRaises(Fail): + asc_store.choose_version([editable], '1.4.1') + + +class AlreadySubmittedTest(unittest.TestCase): + def test_submitted_states(self) -> None: + for state in ('WAITING_FOR_REVIEW', 'IN_REVIEW', 'PENDING_DEVELOPER_RELEASE', + 'PROCESSING_FOR_DISTRIBUTION', 'READY_FOR_DISTRIBUTION', + 'READY_FOR_SALE'): + with self.subTest(state=state): + self.assertTrue(asc_store.already_submitted( + {'attributes': {'appStoreState': state}})) + + def test_editable_states_are_not_submitted(self) -> None: + for state in ('PREPARE_FOR_SUBMISSION', 'REJECTED', 'DEVELOPER_REJECTED'): + with self.subTest(state=state): + self.assertFalse(asc_store.already_submitted( + {'attributes': {'appStoreState': state}})) + + def test_reads_the_newer_state_field_too(self) -> None: + self.assertTrue(asc_store.already_submitted( + {'attributes': {'appVersionState': 'WAITING_FOR_REVIEW'}})) + + +class ScreenshotSetsTest(unittest.TestCase): + def test_watch_set(self) -> None: + spec = asc_store.SCREENSHOT_SETS['watch-46'] + self.assertEqual(spec['displayType'], 'APP_WATCH_SERIES_10') + self.assertEqual(spec['sizes'], {(416, 496)}) + + def test_phone_and_tablet_sets_keep_their_display_types(self) -> None: + self.assertEqual(asc_store.SCREENSHOT_SETS['ios-iphone-69']['displayType'], + 'APP_IPHONE_67') + self.assertEqual(asc_store.SCREENSHOT_SETS['ios-ipad-13']['displayType'], + 'APP_IPAD_PRO_3GEN_129') + + +class ReleaseEnvTest(unittest.TestCase): + def test_parses_exports_quotes_and_comments(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'env') + Path(path).write_text( + '# comment\n\nASC_KEY_ID=ABC123\nexport ASC_ISSUER_ID="issuer-1"\n' + "OTHER='x y'\nPLAIN=value # trailing\n", encoding='utf-8') + with mock.patch.object(asc_store, 'RELEASE_ENV', path), \ + mock.patch.dict(os.environ, {}, clear=True): + values = asc_store.load_release_env() + self.assertEqual(values['ASC_KEY_ID'], 'ABC123') + self.assertEqual(values['ASC_ISSUER_ID'], 'issuer-1') + self.assertEqual(values['OTHER'], 'x y') + self.assertEqual(values['PLAIN'], 'value') + + def test_defaults(self) -> None: + self.assertTrue(asc_store.RELEASE_ENV.endswith('.meshmapper_release.env')) + self.assertEqual(asc_store.BUNDLE_ID, 'net.meshmapper.app') + self.assertEqual(asc_store.DEFAULT_APP_ID, '6758073991') + + +class DerToRawTest(unittest.TestCase): + def test_pads_r_and_s_to_32_bytes(self) -> None: + r = bytes([0x01] * 31) + s = bytes([0x00, 0x80] + [0x02] * 30) # leading zero keeps the INTEGER positive + der = bytes([0x30, 2 + len(r) + 2 + len(s), 0x02, len(r)]) + r + \ + bytes([0x02, len(s)]) + s + raw = asc_store._der_to_raw(der) + self.assertEqual(len(raw), 64) + self.assertEqual(raw[:32], b'\x00' + r) + self.assertEqual(raw[32:], b'\x00' + s[1:]) + + +# --------------------------------------------------------------------------- +# Flows against a fake App Store Connect +# --------------------------------------------------------------------------- + +APP = asc_store.DEFAULT_APP_ID + + +class FakeASC: + """Stands in for asc_store.api. Routes are keyed (method, path); a value is a + response body, an exception to raise, or a callable taking the body.""" + + def __init__(self, routes: dict) -> None: + self.routes = routes + self.calls: list[tuple] = [] + + def __call__(self, method, path, body=None, params=None, ok=(200, 201, 204)): + self.calls.append((method, path, body, params)) + if (method, path) not in self.routes: + raise AssertionError('unexpected call %s %s' % (method, path)) + res = self.routes[(method, path)] + if isinstance(res, Exception): + raise res + return res(body) if callable(res) else res + + def writes(self) -> list[tuple]: + return [(m, p, b) for m, p, b, _ in self.calls if m != 'GET'] + + +def _data(items): + return {'data': items} + + +def _run(fn, args) -> tuple: + out = io.StringIO() + with contextlib.redirect_stdout(out): + result = fn(args) + return result, out.getvalue() + + +class SubmitFlowTest(unittest.TestCase): + VER = 'ver1' + LOC = 'loc1' + + def routes(self, **overrides) -> dict: + routes = { + ('GET', '/v1/apps/%s/appStoreVersions' % APP): + _data([_version('1.4.0', 'READY_FOR_SALE', 'ver0'), + _version('1.4.1', 'PREPARE_FOR_SUBMISSION', self.VER)]), + ('GET', '/v1/appStoreVersions/%s/build' % self.VER): + _data({'id': 'b1', 'type': 'builds', 'attributes': {'version': '1'}}), + ('GET', '/v1/appStoreVersions/%s/appStoreVersionLocalizations' % self.VER): + _data([{'id': self.LOC, 'attributes': {'locale': 'en-CA', + 'whatsNew': 'Fixes.'}}]), + ('GET', '/v1/appStoreVersionLocalizations/%s/appScreenshotSets' % self.LOC): + _data([{'id': 's-phone', 'attributes': { + 'screenshotDisplayType': 'APP_IPHONE_67'}}, + {'id': 's-pad', 'attributes': { + 'screenshotDisplayType': 'APP_IPAD_PRO_3GEN_129'}}, + {'id': 's-watch', 'attributes': { + 'screenshotDisplayType': 'APP_WATCH_SERIES_10'}}]), + ('GET', '/v1/reviewSubmissions'): _data([]), + ('POST', '/v1/reviewSubmissions'): + {'data': {'id': 'sub1', 'type': 'reviewSubmissions', + 'attributes': {'state': 'READY_FOR_REVIEW'}}}, + ('POST', '/v1/reviewSubmissionItems'): + {'data': {'id': 'item1', 'type': 'reviewSubmissionItems'}}, + ('PATCH', '/v1/reviewSubmissions/sub1'): + {'data': {'id': 'sub1', 'type': 'reviewSubmissions', + 'attributes': {'state': 'WAITING_FOR_REVIEW'}}}, + } + for set_id in ('s-phone', 's-pad', 's-watch'): + routes[('GET', '/v1/appScreenshotSets/%s/appScreenshots' % set_id)] = _data( + [{'id': set_id + '-1', 'attributes': { + 'assetDeliveryState': {'state': 'COMPLETE'}}}]) + routes.update(overrides) + return routes + + def submit(self, fake: FakeASC, apply: bool, version: str = '1.4.1'): + args = mock.Mock(version=version, apply=apply) + with mock.patch.object(asc_store, 'api', fake): + return _run(asc_store.cmd_submit, args) + + def test_dry_run_checks_everything_and_writes_nothing(self) -> None: + fake = FakeASC(self.routes()) + _, out = self.submit(fake, apply=False) + self.assertEqual(fake.writes(), []) + self.assertIn('DRY RUN', out) + + def test_apply_creates_submission_adds_the_version_then_submits(self) -> None: + fake = FakeASC(self.routes()) + self.submit(fake, apply=True) + self.assertEqual(fake.writes(), [ + ('POST', '/v1/reviewSubmissions', {'data': { + 'type': 'reviewSubmissions', 'attributes': {'platform': 'IOS'}, + 'relationships': {'app': {'data': {'type': 'apps', 'id': APP}}}}}), + ('POST', '/v1/reviewSubmissionItems', {'data': { + 'type': 'reviewSubmissionItems', 'relationships': { + 'reviewSubmission': {'data': {'type': 'reviewSubmissions', + 'id': 'sub1'}}, + 'appStoreVersion': {'data': {'type': 'appStoreVersions', + 'id': self.VER}}}}}), + ('PATCH', '/v1/reviewSubmissions/sub1', {'data': { + 'type': 'reviewSubmissions', 'id': 'sub1', + 'attributes': {'submitted': True}}}), + ]) + + def test_looks_for_an_open_ios_submission(self) -> None: + fake = FakeASC(self.routes()) + self.submit(fake, apply=False) + params = [p for m, path, _, p in fake.calls + if (m, path) == ('GET', '/v1/reviewSubmissions')][0] + self.assertEqual(params['filter[app]'], APP) + self.assertEqual(params['filter[platform]'], 'IOS') + self.assertEqual(params['filter[state]'], 'READY_FOR_REVIEW') + + @staticmethod + def items_of(*version_ids: str) -> dict: + return _data([{'id': 'item-' + vid, 'type': 'reviewSubmissionItems', 'relationships': { + 'appStoreVersion': {'data': {'type': 'appStoreVersions', 'id': vid}}}} + for vid in version_ids]) + + @staticmethod + def conflict() -> asc_store.APIError: + return asc_store.APIError( + 'POST', '/v1/reviewSubmissionItems', 409, + {'errors': [{'status': '409', 'code': 'ENTITY_ERROR', 'title': 'conflict'}]}) + + def open_submission_routes(self, items: dict, state: str | None = None) -> dict: + routes = self.routes() + routes[('GET', '/v1/reviewSubmissions')] = _data( + [{'id': 'sub1', 'attributes': {'state': 'READY_FOR_REVIEW'}}]) + routes[('POST', '/v1/reviewSubmissionItems')] = self.conflict() + routes[('GET', '/v1/reviewSubmissions/sub1/items')] = items + if state: + routes[('GET', '/v1/apps/%s/appStoreVersions' % APP)] = _data( + [_version('1.4.1', state, self.VER)]) + return routes + + def test_reuses_an_open_submission_and_continues_on_409_when_the_version_is_in_it(self) -> None: + fake = FakeASC(self.open_submission_routes(self.items_of(self.VER))) + _, out = self.submit(fake, apply=True) + kinds = [(m, p) for m, p, _ in fake.writes()] + self.assertEqual(kinds, [('POST', '/v1/reviewSubmissionItems'), + ('PATCH', '/v1/reviewSubmissions/sub1')]) + self.assertIn('WAITING_FOR_REVIEW', out) + + def test_409_is_also_verified_through_the_included_version(self) -> None: + items = _data([{'id': 'item1', 'type': 'reviewSubmissionItems'}]) + items['included'] = [{'id': self.VER, 'type': 'appStoreVersions'}] + fake = FakeASC(self.open_submission_routes(items)) + self.submit(fake, apply=True) + self.assertEqual(fake.writes()[-1][:2], ('PATCH', '/v1/reviewSubmissions/sub1')) + + def test_409_when_the_version_is_not_in_the_submission_is_raised(self) -> None: + for items in (self.items_of(), self.items_of('some-other-version')): + with self.subTest(items=items): + fake = FakeASC(self.open_submission_routes(items)) + with self.assertRaises(asc_store.APIError) as ctx: + self.submit(fake, apply=True) + self.assertEqual(ctx.exception.status, 409) + self.assertIn('conflict', str(ctx.exception)) + self.assertEqual([(m, p) for m, p, _ in fake.writes()], + [('POST', '/v1/reviewSubmissionItems')]) + + def test_other_item_errors_are_not_swallowed(self) -> None: + routes = self.routes() + routes[('POST', '/v1/reviewSubmissionItems')] = asc_store.APIError( + 'POST', '/v1/reviewSubmissionItems', 422, {'errors': []}) + fake = FakeASC(routes) + with self.assertRaises(asc_store.APIError): + self.submit(fake, apply=True) + self.assertNotIn('PATCH', [m for m, _, _ in fake.writes()]) + + def test_a_half_finished_submit_can_be_resumed(self) -> None: + # The item was added, then `submitted: true` failed. The version now + # reads READY_FOR_REVIEW (on either state field) and is no longer editable. + for field in ('appStoreState', 'appVersionState'): + with self.subTest(field=field): + routes = self.open_submission_routes(self.items_of(self.VER)) + version = _version('1.4.1', 'x', self.VER) + version['attributes'] = {'versionString': '1.4.1', field: 'READY_FOR_REVIEW'} + routes[('GET', '/v1/apps/%s/appStoreVersions' % APP)] = _data([version]) + fake = FakeASC(routes) + _, out = self.submit(fake, apply=True) + self.assertEqual(fake.writes()[-1], ( + 'PATCH', '/v1/reviewSubmissions/sub1', {'data': { + 'type': 'reviewSubmissions', 'id': 'sub1', + 'attributes': {'submitted': True}}})) + self.assertIn('resuming', out) + + def test_a_resumed_submit_still_checks_the_preconditions(self) -> None: + routes = self.open_submission_routes(self.items_of(self.VER), 'READY_FOR_REVIEW') + routes[('GET', '/v1/appScreenshotSets/s-watch/appScreenshots')] = _data([]) + fake = FakeASC(routes) + with self.assertRaises(Fail): + self.submit(fake, apply=True) + self.assertEqual(fake.writes(), []) + + def test_a_version_in_a_state_that_cannot_be_submitted_is_refused(self) -> None: + for state in ('REPLACED_WITH_NEW_VERSION', 'DEVELOPER_REMOVED_FROM_SALE'): + with self.subTest(state=state): + routes = self.routes() + routes[('GET', '/v1/apps/%s/appStoreVersions' % APP)] = _data( + [_version('1.4.1', state, self.VER)]) + fake = FakeASC(routes) + with self.assertRaises(Fail) as ctx: + self.submit(fake, apply=True) + self.assertIn('cannot be submitted', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_already_submitted_exits_cleanly_without_writes(self) -> None: + routes = self.routes() + routes[('GET', '/v1/apps/%s/appStoreVersions' % APP)] = _data( + [_version('1.4.1', 'WAITING_FOR_REVIEW', self.VER)]) + fake = FakeASC(routes) + _, out = self.submit(fake, apply=True) + self.assertIn('already submitted (WAITING_FOR_REVIEW)', out) + self.assertEqual(fake.writes(), []) + + def test_no_build_attached(self) -> None: + fake = FakeASC(self.routes(**{})) + fake.routes[('GET', '/v1/appStoreVersions/%s/build' % self.VER)] = {'data': None} + with self.assertRaises(Fail) as ctx: + self.submit(fake, apply=True) + self.assertIn('build', str(ctx.exception).lower()) + self.assertEqual(fake.writes(), []) + + def test_missing_whats_new(self) -> None: + fake = FakeASC(self.routes()) + fake.routes[('GET', '/v1/appStoreVersions/%s/appStoreVersionLocalizations' + % self.VER)] = _data( + [{'id': self.LOC, 'attributes': {'locale': 'en-CA', 'whatsNew': ''}}]) + with self.assertRaises(Fail) as ctx: + self.submit(fake, apply=True) + self.assertIn('en-CA', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_missing_watch_screenshots(self) -> None: + fake = FakeASC(self.routes()) + fake.routes[('GET', '/v1/appScreenshotSets/s-watch/appScreenshots')] = _data([]) + with self.assertRaises(Fail) as ctx: + self.submit(fake, apply=True) + self.assertIn('APP_WATCH_SERIES_10', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_missing_screenshot_set(self) -> None: + fake = FakeASC(self.routes()) + fake.routes[('GET', '/v1/appStoreVersionLocalizations/%s/appScreenshotSets' + % self.LOC)] = _data([]) + with self.assertRaises(Fail) as ctx: + self.submit(fake, apply=True) + self.assertIn('APP_IPHONE_67', str(ctx.exception)) + + def test_unknown_version(self) -> None: + fake = FakeASC(self.routes()) + with self.assertRaises(Fail): + self.submit(fake, apply=True, version='9.9.9') + + +class PrepareFlowTest(unittest.TestCase): + NOTES = 'Fixed the map. Café menu.' + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.notes_file = os.path.join(self._tmp.name, 'wn.txt') + Path(self.notes_file).write_text(self.NOTES + '\n', encoding='utf-8') + + def routes(self, existing: list[dict]) -> dict: + routes = { + ('GET', '/v1/apps/%s/appStoreVersions' % APP): _data(existing), + ('GET', '/v1/builds'): _data([{ + 'id': 'b1', 'type': 'builds', 'attributes': { + 'version': '1777777777', 'processingState': 'VALID', + 'usesNonExemptEncryption': False, 'expired': False}}]), + } + for v in existing: + routes[('GET', '/v1/appStoreVersions/%s/appStoreVersionLocalizations' + % v['id'])] = _data([{'id': 'loc-' + v['id'], 'attributes': { + 'locale': 'en-CA', 'whatsNew': 'old'}}]) + routes[('GET', '/v1/appStoreVersions/%s/build' % v['id'])] = {'data': None} + routes[('GET', '/v1/appStoreVersions/%s/appStoreVersionPhasedRelease' + % v['id'])] = {'data': {'id': 'ph1', 'type': + 'appStoreVersionPhasedReleases'}} + return routes + + def prepare(self, fake: FakeASC, apply: bool, version: str = '1.4.1', + notes_file: str | None = None, wait: int = 0): + args = mock.Mock(version=version, build='1777777777', apply=apply, wait=wait, + whats_new_file=notes_file or self.notes_file) + with mock.patch.object(asc_store, 'api', fake), \ + mock.patch.object(asc_store.time, 'sleep'): + return _run(asc_store.cmd_prepare, args) + + def test_dry_run_on_an_editable_version_plans_every_write(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + editable['attributes']['releaseType'] = 'MANUAL' + fake = FakeASC(self.routes([editable])) + _, out = self.prepare(fake, apply=False) + self.assertEqual(fake.writes(), []) + for planned in ('build', 'releaseType', 'phased', 'whatsNew', 'DRY RUN'): + self.assertIn(planned, out) + + def test_dry_run_with_no_editable_version_plans_the_create(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE', 'ver0') + fake = FakeASC(self.routes([live])) + _, out = self.prepare(fake, apply=False) + self.assertEqual(fake.writes(), []) + self.assertIn('1.4.1', out) + self.assertIn('create', out) + + def test_apply_on_an_editable_version(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + editable['attributes']['releaseType'] = 'MANUAL' + routes = self.routes([editable]) + routes[('PATCH', '/v1/appStoreVersions/ver1/relationships/build')] = {} + routes[('PATCH', '/v1/appStoreVersions/ver1')] = {} + routes[('DELETE', '/v1/appStoreVersionPhasedReleases/ph1')] = None + routes[('PATCH', '/v1/appStoreVersionLocalizations/loc-ver1')] = {} + fake = FakeASC(routes) + self.prepare(fake, apply=True) + self.assertEqual(fake.writes(), [ + ('PATCH', '/v1/appStoreVersions/ver1/relationships/build', + {'data': {'type': 'builds', 'id': 'b1'}}), + ('PATCH', '/v1/appStoreVersions/ver1', {'data': { + 'type': 'appStoreVersions', 'id': 'ver1', + 'attributes': {'releaseType': 'AFTER_APPROVAL'}}}), + ('DELETE', '/v1/appStoreVersionPhasedReleases/ph1', None), + ('PATCH', '/v1/appStoreVersionLocalizations/loc-ver1', {'data': { + 'type': 'appStoreVersionLocalizations', 'id': 'loc-ver1', + 'attributes': {'whatsNew': self.NOTES}}}), + ]) + + def test_apply_creates_the_version_first(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE', 'ver0') + new = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([live]) + routes.update(self.routes([new])) # the new version's own reads + routes[('GET', '/v1/apps/%s/appStoreVersions' % APP)] = _data([live]) + routes[('POST', '/v1/appStoreVersions')] = {'data': new} + routes[('PATCH', '/v1/appStoreVersions/ver1/relationships/build')] = {} + routes[('DELETE', '/v1/appStoreVersionPhasedReleases/ph1')] = None + routes[('PATCH', '/v1/appStoreVersionLocalizations/loc-ver1')] = {} + fake = FakeASC(routes) + self.prepare(fake, apply=True) + first = fake.writes()[0] + self.assertEqual(first[:2], ('POST', '/v1/appStoreVersions')) + self.assertEqual(first[2], {'data': { + 'type': 'appStoreVersions', + 'attributes': {'platform': 'IOS', 'versionString': '1.4.1', + 'releaseType': 'AFTER_APPROVAL'}, + 'relationships': {'app': {'data': {'type': 'apps', 'id': APP}}}}}) + + def test_second_run_after_apply_has_nothing_to_do(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([editable]) + routes[('GET', '/v1/appStoreVersions/ver1/build')] = { + 'data': {'id': 'b1', 'type': 'builds'}} + routes[('GET', '/v1/appStoreVersions/ver1/appStoreVersionPhasedRelease')] = { + 'data': None} + routes[('GET', '/v1/appStoreVersions/ver1/appStoreVersionLocalizations')] = _data( + [{'id': 'loc-ver1', 'attributes': {'locale': 'en-CA', + 'whatsNew': self.NOTES}}]) + fake = FakeASC(routes) + _, out = self.prepare(fake, apply=True) + self.assertEqual(fake.writes(), []) + self.assertIn('No changes', out) + + def test_refuses_an_emoji_before_any_write(self) -> None: + Path(self.notes_file).write_text('Shiny \U0001F680\n', encoding='utf-8') + fake = FakeASC(self.routes([_version('1.4.0', 'READY_FOR_SALE', 'ver0')])) + with self.assertRaises(Fail): + self.prepare(fake, apply=True) + self.assertEqual(fake.writes(), []) + + def test_refuses_a_non_english_locale_before_any_write(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([editable]) + routes[('GET', '/v1/appStoreVersions/ver1/appStoreVersionLocalizations')] = _data( + [{'id': 'a', 'attributes': {'locale': 'en-CA', 'whatsNew': ''}}, + {'id': 'b', 'attributes': {'locale': 'fr-CA', 'whatsNew': ''}}]) + fake = FakeASC(routes) + with self.assertRaises(Fail) as ctx: + self.prepare(fake, apply=True) + self.assertIn('fr-CA', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_refuses_a_version_that_already_exists_and_is_not_editable(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE', 'ver0') + fake = FakeASC(self.routes([live])) + with self.assertRaises(Fail): + self.prepare(fake, apply=False, version='1.4.0') + + def test_prepare_still_refuses_a_version_waiting_in_an_unsubmitted_submission(self) -> None: + pending = _version('1.4.1', 'READY_FOR_REVIEW', 'ver1') + fake = FakeASC(self.routes([pending])) + with self.assertRaises(Fail) as ctx: + self.prepare(fake, apply=True) + self.assertIn('READY_FOR_REVIEW', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_waits_for_the_build_to_become_valid(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([editable]) + states = iter(['PROCESSING', 'PROCESSING', 'VALID']) + + def builds(_body): + return _data([{'id': 'b1', 'type': 'builds', 'attributes': { + 'version': '1777777777', 'processingState': next(states), + 'usesNonExemptEncryption': False}}]) + + routes[('GET', '/v1/builds')] = builds + fake = FakeASC(routes) + _, out = self.prepare(fake, apply=False, wait=120) + self.assertEqual(fake.writes(), []) + self.assertIn('VALID', out) + + def test_gives_up_when_the_build_never_becomes_valid(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([editable]) + routes[('GET', '/v1/builds')] = _data([{'id': 'b1', 'type': 'builds', 'attributes': { + 'version': '1777777777', 'processingState': 'PROCESSING'}}]) + fake = FakeASC(routes) + fake_now = iter(range(0, 10000, 31)) + with mock.patch.object(asc_store.time, 'time', lambda: next(fake_now)), \ + self.assertRaises(Fail) as ctx: + self.prepare(fake, apply=False, wait=60) + self.assertIn('PROCESSING', str(ctx.exception)) + + def test_a_failed_build_stops_at_once(self) -> None: + editable = _version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1') + routes = self.routes([editable]) + routes[('GET', '/v1/builds')] = _data([{'id': 'b1', 'type': 'builds', 'attributes': { + 'version': '1777777777', 'processingState': 'INVALID'}}]) + fake = FakeASC(routes) + with self.assertRaises(Fail) as ctx: + self.prepare(fake, apply=False, wait=1800) + self.assertIn('INVALID', str(ctx.exception)) + + +def _png(path: Path, width: int, height: int) -> None: + """Just enough of a PNG for asc_store.png_size: signature and IHDR.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'\x89PNG\r\n\x1a\n' + struct.pack('>I', 13) + b'IHDR' + + struct.pack('>II', width, height) + b'\x08\x06\x00\x00\x00') + + +class ScreenshotsFlowTest(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + _png(self.root / 'watch-46' / '01_map.png', 416, 496) + _png(self.root / 'ios-iphone-69' / '01_map.png', 1320, 2868) + + def routes(self, versions: list[dict], locales: list[str] = ['en-CA']) -> dict: + return { + ('GET', '/v1/apps/%s/appStoreVersions' % APP): _data(versions), + ('GET', '/v1/appStoreVersions/%s/appStoreVersionLocalizations' + % versions[0]['id']): _data( + [{'id': 'loc-' + l, 'attributes': {'locale': l}} for l in locales]), + ('GET', '/v1/appStoreVersionLocalizations/loc-en-CA/appScreenshotSets'): _data([]), + } + + def run_screenshots(self, fake: FakeASC, apply: bool = False): + args = mock.Mock(dir=str(self.root), apply=apply, replace=False) + with mock.patch.object(asc_store, 'api', fake): + return _run(asc_store.cmd_screenshots, args) + + def test_dry_run_plans_the_watch_set(self) -> None: + fake = FakeASC(self.routes([_version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1')])) + _, out = self.run_screenshots(fake) + self.assertEqual(fake.writes(), []) + self.assertIn('create APP_WATCH_SERIES_10', out) + self.assertIn('upload 416x496', out) + self.assertIn('upload 1320x2868', out) + + def test_refuses_more_than_one_locale(self) -> None: + fake = FakeASC(self.routes([_version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1')], + ['en-CA', 'en-US'])) + with self.assertRaises(Fail) as ctx: + self.run_screenshots(fake) + self.assertIn('exactly one', str(ctx.exception)) + + def test_refuses_a_non_english_locale(self) -> None: + fake = FakeASC(self.routes([_version('1.4.1', 'PREPARE_FOR_SUBMISSION', 'ver1')], + ['fr-CA'])) + with self.assertRaises(Fail) as ctx: + self.run_screenshots(fake) + self.assertIn('fr-CA', str(ctx.exception)) + + def test_wrong_size_is_refused_before_any_request(self) -> None: + _png(self.root / 'watch-46' / '02_bad.png', 400, 400) + fake = FakeASC({}) + with self.assertRaises(Fail) as ctx: + self.run_screenshots(fake) + self.assertIn('02_bad.png', str(ctx.exception)) + self.assertEqual(fake.calls, []) + + def test_without_an_editable_version_dry_run_previews_and_apply_refuses(self) -> None: + live = _version('1.4.0', 'READY_FOR_SALE', 'ver0') + _, out = self.run_screenshots(FakeASC(self.routes([live]))) + self.assertIn('previewing against 1.4.0', out) + fake = FakeASC(self.routes([live])) + with self.assertRaises(Fail) as ctx: + self.run_screenshots(fake, apply=True) + self.assertIn('No editable App Store version', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + +class StateLabelTest(unittest.TestCase): + def test_shows_both_names_when_they_differ(self) -> None: + v = {'attributes': {'appVersionState': 'READY_FOR_DISTRIBUTION', + 'appStoreState': 'READY_FOR_SALE'}} + self.assertEqual(asc_store.state_label(v), + 'READY_FOR_DISTRIBUTION / READY_FOR_SALE') + self.assertEqual(asc_store.state_label(_version('1.4.1', 'REJECTED')), 'REJECTED') + + +class UploadScreenshotPollTest(unittest.TestCase): + """Apple sometimes answers HTTP 500 for a screenshot it has only just received. + The wait for processing must ride that out instead of stopping the release.""" + + SHOT = '/v1/appScreenshots/shot1' + + def _shot(self, state: str) -> dict: + return {'data': {'id': 'shot1', 'type': 'appScreenshots', + 'attributes': {'assetDeliveryState': {'state': state}}}} + + def _run_upload(self, reads: list) -> tuple: + seq = list(reads) + + def read(_body): + nxt = seq.pop(0) + if isinstance(nxt, Exception): + raise nxt + return nxt + + fake = FakeASC({ + ('POST', '/v1/appScreenshots'): + {'data': {'id': 'shot1', 'type': 'appScreenshots', + 'attributes': {'uploadOperations': []}}}, + ('PATCH', self.SHOT): self._shot('UPLOAD_COMPLETE'), + ('GET', self.SHOT): read, + }) + with tempfile.TemporaryDirectory() as tmp: + png = Path(tmp) / '01_map.png' + png.write_bytes(b'png') + with mock.patch.object(asc_store, 'api', fake), \ + mock.patch.object(asc_store.time, 'sleep'): + cur, out = _run(lambda a: asc_store.upload_screenshot('set1', str(png), 'md5'), + None) + return cur, out, fake + + def test_a_server_error_while_waiting_is_retried(self) -> None: + err = asc_store.APIError('GET', self.SHOT, 500, None) + cur, out, fake = self._run_upload([err, err, self._shot('COMPLETE')]) + self.assertEqual(asc_store.shot_state(cur), 'COMPLETE') + self.assertEqual(len([c for c in fake.calls if c[0] == 'GET']), 3) + self.assertIn('HTTP 500', out) + + def test_a_client_error_while_waiting_still_stops(self) -> None: + err = asc_store.APIError('GET', self.SHOT, 404, None) + with self.assertRaises(asc_store.APIError): + self._run_upload([err]) + + def test_server_errors_past_the_deadline_stop(self) -> None: + err = asc_store.APIError('GET', self.SHOT, 500, None) + clock = iter([0, 0] + [1000] * 10) + with mock.patch.object(asc_store.time, 'time', lambda: next(clock)): + with self.assertRaises(asc_store.APIError): + self._run_upload([err, err, err]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/tests/test_contact_sheet.py b/tool/tests/test_contact_sheet.py new file mode 100644 index 00000000..a71823c8 --- /dev/null +++ b/tool/tests/test_contact_sheet.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from tool.store_screenshots import contact_sheet + + +def _touch(root: Path, rel: str) -> None: + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"png") + + +class BuildHtmlTest(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + # Created out of name order on purpose. + _touch(self.root, "ios-iphone-69/02_log.png") + _touch(self.root, "ios-iphone-69/01_map.png") + _touch(self.root, "android-phone/01_map.png") + self.html = contact_sheet.build_html(self.root) + + def test_set_order_is_fixed(self) -> None: + self.assertEqual( + contact_sheet.SET_ORDER, + ["ios-iphone-69", "ios-ipad-13", "watch-46", "android-phone"], + ) + + def test_names_every_set_in_order(self) -> None: + positions = [self.html.index(name) for name in contact_sheet.SET_ORDER] + self.assertEqual(positions, sorted(positions)) + + def test_lists_iphone_files_in_name_order_with_relative_src(self) -> None: + first = self.html.index('src="ios-iphone-69/01_map.png"') + second = self.html.index('src="ios-iphone-69/02_log.png"') + self.assertLess(first, second) + self.assertNotIn(str(self.root), self.html) + + def test_marks_empty_sets_missing(self) -> None: + self.assertEqual(self.html.count("missing"), 2) + ipad = self.html.index("ios-ipad-13") + watch = self.html.index("watch-46") + android = self.html.index("android-phone") + self.assertIn("missing", self.html[ipad:watch]) + self.assertIn("missing", self.html[watch:android]) + + def test_present_sets_are_not_marked_missing(self) -> None: + iphone = self.html.index("ios-iphone-69") + ipad = self.html.index("ios-ipad-13") + self.assertNotIn("missing", self.html[iphone:ipad]) + self.assertNotIn("missing", self.html[self.html.index("android-phone"):]) + + +class MainTest(unittest.TestCase): + def test_writes_contact_sheet_html(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _touch(root, "watch-46/01_map.png") + out = contact_sheet.write_contact_sheet(root) + self.assertEqual(out, root / "contact_sheet.html") + self.assertIn('src="watch-46/01_map.png"', out.read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tool/tests/test_play_store.py b/tool/tests/test_play_store.py new file mode 100644 index 00000000..d60f2e25 --- /dev/null +++ b/tool/tests/test_play_store.py @@ -0,0 +1,751 @@ +from __future__ import annotations + +import contextlib +import io +import os +import struct +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +# play_store.py lives in the repo root, next to Build.sh. +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +import play_store # noqa: E402 + +PlayError = play_store.PlayError +EDIT = 'E1' + + +def _parse(*argv: str): + return play_store.build_parser().parse_args(list(argv)) + + +def _run(fn, args) -> tuple: + out = io.StringIO() + with contextlib.redirect_stdout(out): + result = fn(args) + return result, out.getvalue() + + +def _png(path: Path, width: int, height: int, extra: bytes = b'') -> None: + """Just enough of a PNG for play_store.png_info: signature and IHDR.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'\x89PNG\r\n\x1a\n' + struct.pack('>I', 13) + b'IHDR' + + struct.pack('>II', width, height) + b'\x08\x06\x00\x00\x00' + extra) + + + +def _varint(n: int) -> bytes: + out = b'' + while True: + b = n & 0x7F + n >>= 7 + if n: + out += bytes([b | 0x80]) + else: + return out + bytes([b]) + + +def _ld(field: int, payload: bytes) -> bytes: + """A length-delimited protobuf field.""" + return _varint((field << 3) | 2) + _varint(len(payload)) + payload + + +def _make_aab(path: Path, package: str, version_code: int, version_name: str) -> None: + """A tiny AAB: just base/manifest/AndroidManifest.xml in aapt2's proto form, + with the package and versionName as strings and versionCode as a compiled int.""" + def attr(name: str, value: str | None = None, number: int | None = None) -> bytes: + body = _ld(2, name.encode()) + if value is not None: + body += _ld(3, value.encode()) + if number is not None: + body += _ld(6, _ld(7, _varint((6 << 3) | 0) + _varint(number))) + return _ld(4, body) + + element = (attr('package', package) + attr('versionName', version_name) + + attr('versionCode', number=version_code)) + path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, 'w') as z: + z.writestr('base/manifest/AndroidManifest.xml', _ld(1, element)) + + +class DefaultLanguageTest(unittest.TestCase): + def test_uses_the_default_language_of_the_app(self) -> None: + self.assertEqual(play_store.default_language({'defaultLanguage': 'en-US'}, None), + 'en-US') + + def test_override_wins(self) -> None: + self.assertEqual(play_store.default_language({'defaultLanguage': 'en-US'}, 'fr-CA'), + 'fr-CA') + + def test_missing_default_language_is_an_error(self) -> None: + with self.assertRaises(PlayError): + play_store.default_language({}, None) + + +class CheckScreenshotSizeTest(unittest.TestCase): + def test_accepts_a_1080x1920_phone_screenshot(self) -> None: + play_store.check_screenshot_size(1080, 1920) + + def test_accepts_the_limits_and_landscape(self) -> None: + for w, h in ((320, 640), (3840, 1920), (1920, 1080), (320, 320)): + with self.subTest(size=(w, h)): + play_store.check_screenshot_size(w, h) + + def test_rejects_a_ratio_over_two(self) -> None: + with self.assertRaises(PlayError): + play_store.check_screenshot_size(1080, 2400) + + def test_rejects_a_side_under_320(self) -> None: + with self.assertRaises(PlayError): + play_store.check_screenshot_size(300, 600) + + def test_rejects_a_side_over_3840(self) -> None: + with self.assertRaises(PlayError): + play_store.check_screenshot_size(4000, 2000) + + +class ReadNotesTest(unittest.TestCase): + def write(self, text: str) -> str: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = os.path.join(tmp.name, 'notes.txt') + Path(path).write_text(text, encoding='utf-8') + return path + + def test_501_characters_are_refused(self) -> None: + with self.assertRaises(PlayError) as ctx: + play_store.read_notes(self.write('x' * 501), 'en-US') + self.assertIn('501', str(ctx.exception)) + + def test_exactly_500_characters_pass(self) -> None: + notes = play_store.read_notes(self.write('x' * 500), 'en-US') + self.assertEqual(notes, [{'language': 'en-US', 'text': 'x' * 500}]) + + def test_surrounding_whitespace_is_not_counted(self) -> None: + notes = play_store.read_notes(self.write('\n' + 'x' * 500 + '\n\n'), 'en-US') + self.assertEqual(len(notes[0]['text']), 500) + + def test_empty_file_is_refused(self) -> None: + with self.assertRaises(PlayError): + play_store.read_notes(self.write(' \n'), 'en-US') + + def test_missing_file_is_refused(self) -> None: + with self.assertRaises(PlayError): + play_store.read_notes('/nonexistent/notes.txt', 'en-US') + + def test_no_notes_file_means_no_notes(self) -> None: + self.assertIsNone(play_store.read_notes(None, 'en-US')) + + +class CheckLanguagesTest(unittest.TestCase): + def test_accepts_english(self) -> None: + play_store.check_languages(['en-US']) + play_store.check_languages(['en-US', 'en-GB']) + play_store.check_languages([]) + + def test_names_the_first_non_english_language(self) -> None: + with self.assertRaises(PlayError) as ctx: + play_store.check_languages(['en-US', 'fr-CA', 'de-DE']) + self.assertIn('fr-CA', str(ctx.exception)) + self.assertNotIn('de-DE', str(ctx.exception)) + + +class ReleaseEnvTest(unittest.TestCase): + def test_parses_exports_quotes_and_comments(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'env') + Path(path).write_text( + '# comment\n\nPLAY_SERVICE_ACCOUNT_JSON=/k/key.json\n' + 'export PLAY_PACKAGE_NAME="x.y.z"\nOTHER=\'x y\'\nPLAIN=value # trailing\n', + encoding='utf-8') + with mock.patch.object(play_store, 'RELEASE_ENV', path), \ + mock.patch.dict(os.environ, {}, clear=True): + values = play_store.load_release_env() + self.assertEqual(values['PLAY_SERVICE_ACCOUNT_JSON'], '/k/key.json') + self.assertEqual(values['PLAY_PACKAGE_NAME'], 'x.y.z') + self.assertEqual(values['OTHER'], 'x y') + self.assertEqual(values['PLAIN'], 'value') + + def test_environment_wins(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'env') + Path(path).write_text('PLAY_PACKAGE_NAME=from.file\n', encoding='utf-8') + with mock.patch.object(play_store, 'RELEASE_ENV', path), \ + mock.patch.dict(os.environ, {'PLAY_PACKAGE_NAME': 'from.env'}, clear=True): + values = play_store.load_release_env() + self.assertEqual(values['PLAY_PACKAGE_NAME'], 'from.env') + + def test_defaults(self) -> None: + self.assertTrue(play_store.RELEASE_ENV.endswith('.meshmapper_release.env')) + self.assertEqual(play_store.DEFAULT_PACKAGE, 'net.meshmapper.app') + with mock.patch.object(play_store, 'ENV', {}): + self.assertEqual(play_store.package_name(), 'net.meshmapper.app') + + +class ParserTest(unittest.TestCase): + def test_listing_is_gone(self) -> None: + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + _parse('listing') + + def test_apply_and_validate_exclude_each_other(self) -> None: + for argv in (('upload', '--track', 'production', '--apply', '--validate'), + ('screenshots', '--dir', '/x', '--apply', '--validate')): + with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()), \ + self.assertRaises(SystemExit): + _parse(*argv) + + def test_upload_language_defaults_to_the_app_default(self) -> None: + self.assertIsNone(_parse('upload', '--track', 'production').lang) + self.assertEqual(_parse('upload', '--track', 'production', '--lang', 'en-GB').lang, + 'en-GB') + + +class FakePlay: + """Stands in for play_store.PlayApi. Routes are keyed (method, path) with the + full path (edit id included); a value is a response body, an exception to + raise, or a callable taking the body.""" + + client_email = 'play-publisher@example.test' + package = 'net.meshmapper.app' + + def __init__(self, routes: dict | None = None) -> None: + self.routes = { + ('POST', '/edits'): {'id': EDIT}, + ('DELETE', '/edits/' + EDIT): {}, + ('GET', '/edits/%s/details' % EDIT): {'defaultLanguage': 'en-US'}, + ('GET', '/edits/%s/listings' % EDIT): {'listings': [ + {'language': 'en-US', 'title': 'MeshMapper'}]}, + ('GET', '/edits/%s/tracks' % EDIT): {'tracks': [ + {'track': 'production', 'releases': [ + {'name': '1.4.0 (1789991039)', 'status': 'completed', + 'versionCodes': ['1789991039']}]}]}, + } + self.routes.update(routes or {}) + self.calls: list[tuple] = [] + + def __call__(self, creds, package): + return self + + def call(self, method, path, body=None, **kw): + self.calls.append((method, path, body, kw)) + if (method, path) not in self.routes: + raise AssertionError('unexpected call %s %s' % (method, path)) + res = self.routes[(method, path)] + if isinstance(res, Exception): + raise res + return res(body) if callable(res) else res + + def paths(self) -> list[tuple]: + return [(m, p) for m, p, _, _ in self.calls] + + def writes(self) -> list[tuple]: + """Calls that change something, not counting opening and deleting the edit.""" + skip = {('POST', '/edits'), ('DELETE', '/edits/' + EDIT)} + return [(m, p, b) for m, p, b, _ in self.calls if m != 'GET' and (m, p) not in skip] + + def committed(self) -> bool: + return ('POST', '/edits/%s:commit' % EDIT) in self.paths() + + +class _Patched: + """Swaps the API client and the credentials loader for FakePlay.""" + + def __init__(self, fake: FakePlay) -> None: + self.stack = contextlib.ExitStack() + self.fake = fake + + def __enter__(self): + self.stack.enter_context(mock.patch.object(play_store, 'PlayApi', self.fake)) + self.stack.enter_context(mock.patch.object( + play_store, 'load_credentials', + lambda: {'client_email': FakePlay.client_email})) + return self + + def __exit__(self, *exc): + return self.stack.__exit__(*exc) + + +class UploadFlowTest(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.notes = os.path.join(self._tmp.name, 'notes.txt') + Path(self.notes).write_text('Faster map.\nFixes.', encoding='utf-8') + + def routes(self, extra: dict | None = None) -> dict: + routes = { + ('PUT', '/edits/%s/tracks/production' % EDIT): {}, + ('POST', '/edits/%s:validate' % EDIT): {'id': EDIT}, + ('POST', '/edits/%s:commit' % EDIT): {}, + } + routes.update(extra or {}) + return routes + + def upload(self, fake: FakePlay, *flags: str, version_code: str = '1789991039'): + args = _parse('upload', '--track', 'production', '--status', 'completed', + '--notes-file', self.notes, '--version-code', version_code, *flags) + with _Patched(fake): + return _run(play_store.cmd_upload, args) + + RELEASE = {'track': 'production', 'releases': [{ + 'versionCodes': ['1789991039'], 'status': 'completed', + 'releaseNotes': [{'language': 'en-US', 'text': 'Faster map.\nFixes.'}]}]} + + def test_dry_run_writes_nothing_and_does_not_commit(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.upload(fake) + self.assertEqual(fake.writes(), []) + self.assertIn('Dry run', out) + self.assertIn(('DELETE', '/edits/' + EDIT), fake.paths()) + + def test_validate_stages_the_release_validates_and_never_commits(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.upload(fake, '--validate') + self.assertEqual(fake.writes(), [ + ('PUT', '/edits/%s/tracks/production' % EDIT, self.RELEASE), + ('POST', '/edits/%s:validate' % EDIT, None), + ]) + self.assertFalse(fake.committed()) + self.assertEqual(fake.paths()[-1], ('DELETE', '/edits/' + EDIT)) + self.assertIn('validate: OK', out) + self.assertIn('edit deleted', out) + + def test_apply_commits_and_does_not_validate(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.upload(fake, '--apply') + self.assertEqual(fake.writes(), [ + ('PUT', '/edits/%s/tracks/production' % EDIT, self.RELEASE), + ('POST', '/edits/%s:commit' % EDIT, None), + ]) + self.assertNotIn(('DELETE', '/edits/' + EDIT), fake.paths()) + self.assertIn('Committed', out) + + def test_no_review_commits_without_sending_for_review(self) -> None: + fake = FakePlay(self.routes()) + self.upload(fake, '--apply', '--no-review') + commit = [kw for m, p, _, kw in fake.calls if p.endswith(':commit')][0] + self.assertEqual(commit['query'], {'changesNotSentForReview': 'true'}) + + def test_release_notes_use_the_default_language(self) -> None: + fake = FakePlay(self.routes({ + ('GET', '/edits/%s/details' % EDIT): {'defaultLanguage': 'en-GB'}, + ('GET', '/edits/%s/listings' % EDIT): {'listings': [{'language': 'en-GB'}]}})) + self.upload(fake, '--validate') + put = [b for m, p, b, _ in fake.calls if m == 'PUT'][0] + self.assertEqual(put['releases'][0]['releaseNotes'][0]['language'], 'en-GB') + + def test_lang_flag_overrides_the_default_language(self) -> None: + fake = FakePlay(self.routes()) + self.upload(fake, '--validate', '--lang', 'en-CA') + put = [b for m, p, b, _ in fake.calls if m == 'PUT'][0] + self.assertEqual(put['releases'][0]['releaseNotes'][0]['language'], 'en-CA') + + def test_a_non_english_listing_stops_everything_before_any_write(self) -> None: + fake = FakePlay(self.routes({ + ('GET', '/edits/%s/listings' % EDIT): {'listings': [ + {'language': 'en-US'}, {'language': 'fr-CA'}]}})) + with self.assertRaises(PlayError) as ctx: + self.upload(fake, '--apply') + self.assertIn('fr-CA', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + self.assertIn(('DELETE', '/edits/' + EDIT), fake.paths()) + + def test_a_validate_failure_leaves_nothing_behind(self) -> None: + err = play_store.ApiError(400, 'bad release', 'Validating') + fake = FakePlay(self.routes({('POST', '/edits/%s:validate' % EDIT): err})) + with self.assertRaises(play_store.ApiError): + self.upload(fake, '--validate') + self.assertFalse(fake.committed()) + self.assertEqual(fake.paths()[-1], ('DELETE', '/edits/' + EDIT)) + + def test_notes_over_the_limit_are_refused_before_any_request(self) -> None: + Path(self.notes).write_text('x' * 501, encoding='utf-8') + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError): + self.upload(fake, '--apply') + self.assertEqual(fake.calls, []) + + def test_a_fraction_needs_in_progress(self) -> None: + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError): + self.upload(fake, '--fraction', '0.2') + self.assertEqual(fake.calls, []) + + +class ScreenshotsFlowTest(unittest.TestCase): + PHONE = '/edits/%s/listings/en-US/phoneScreenshots' % EDIT + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + self.shots = self.root / 'android-phone' + # Written out of order on purpose: uploads must follow the file names. + for name in ('03_history.png', '01_map.png', '02_log.png'): + _png(self.shots / name, 1080, 1920, extra=name.encode()) + + def routes(self, extra: dict | None = None) -> dict: + routes = { + ('GET', self.PHONE): {'images': []}, + ('DELETE', self.PHONE): {}, + ('POST', self.PHONE): {}, + ('POST', '/edits/%s:validate' % EDIT): {'id': EDIT}, + ('POST', '/edits/%s:commit' % EDIT): {}, + } + routes.update(extra or {}) + return routes + + def screenshots(self, fake: FakePlay, *flags: str): + args = _parse('screenshots', '--dir', str(self.root), *flags) + with _Patched(fake): + return _run(play_store.cmd_screenshots, args) + + def uploaded(self, fake: FakePlay) -> list[str]: + return [os.path.basename(kw['upload_path']) for m, p, _, kw in fake.calls + if (m, p) == ('POST', self.PHONE)] + + def test_dry_run_plans_the_replacement_and_writes_nothing(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.screenshots(fake) + self.assertEqual(fake.writes(), []) + self.assertIn('Dry run', out) + self.assertIn('01_map.png', out) + + def test_validate_replaces_in_name_order_validates_and_never_commits(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.screenshots(fake, '--validate') + self.assertEqual([(m, p) for m, p, _ in fake.writes()], [ + ('DELETE', self.PHONE), + ('POST', self.PHONE), ('POST', self.PHONE), ('POST', self.PHONE), + ('POST', '/edits/%s:validate' % EDIT), + ]) + self.assertEqual(self.uploaded(fake), ['01_map.png', '02_log.png', '03_history.png']) + self.assertFalse(fake.committed()) + self.assertEqual(fake.paths()[-1], ('DELETE', '/edits/' + EDIT)) + self.assertIn('validate: OK', out) + self.assertIn('edit deleted', out) + + def test_uploads_are_png(self) -> None: + fake = FakePlay(self.routes()) + self.screenshots(fake, '--validate') + kw = [kw for m, p, _, kw in fake.calls if (m, p) == ('POST', self.PHONE)][0] + self.assertEqual(kw['content_type'], 'image/png') + + def test_apply_replaces_and_commits(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.screenshots(fake, '--apply') + self.assertEqual(fake.writes()[0][:2], ('DELETE', self.PHONE)) + self.assertEqual(self.uploaded(fake), ['01_map.png', '02_log.png', '03_history.png']) + self.assertTrue(fake.committed()) + self.assertNotIn(('POST', '/edits/%s:validate' % EDIT), fake.paths()) + self.assertIn('Committed', out) + + def test_apply_does_nothing_when_play_already_matches(self) -> None: + remote = [{'sha1': play_store.sha1_file(str(self.shots / n))} + for n in ('01_map.png', '02_log.png', '03_history.png')] + fake = FakePlay(self.routes({('GET', self.PHONE): {'images': remote}})) + _, out = self.screenshots(fake, '--apply') + self.assertEqual(fake.writes(), []) + self.assertFalse(fake.committed()) + self.assertIn('already matches', out) + + def test_validate_still_stages_when_play_already_matches(self) -> None: + remote = [{'sha1': play_store.sha1_file(str(self.shots / n))} + for n in ('01_map.png', '02_log.png', '03_history.png')] + fake = FakePlay(self.routes({('GET', self.PHONE): {'images': remote}})) + _, out = self.screenshots(fake, '--validate') + self.assertIn(('POST', '/edits/%s:validate' % EDIT), fake.paths()) + self.assertIn('validate: OK', out) + + def test_a_non_english_listing_stops_everything_before_any_write(self) -> None: + fake = FakePlay(self.routes({ + ('GET', '/edits/%s/listings' % EDIT): {'listings': [ + {'language': 'en-US'}, {'language': 'fr-CA'}]}})) + with self.assertRaises(PlayError) as ctx: + self.screenshots(fake, '--apply') + self.assertIn('fr-CA', str(ctx.exception)) + self.assertEqual(fake.writes(), []) + + def test_fewer_than_two_files_is_refused_before_any_request(self) -> None: + (self.shots / '03_history.png').unlink() + (self.shots / '02_log.png').unlink() + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError) as ctx: + self.screenshots(fake, '--apply') + self.assertIn('2-8', str(ctx.exception)) + self.assertEqual(fake.calls, []) + + def test_more_than_eight_files_is_refused(self) -> None: + for i in range(4, 10): + _png(self.shots / ('%02d_x.png' % i), 1080, 1920) + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError): + self.screenshots(fake, '--apply') + self.assertEqual(fake.calls, []) + + def test_a_wrong_size_is_refused_before_any_request(self) -> None: + _png(self.shots / '04_bad.png', 1080, 2400) + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError) as ctx: + self.screenshots(fake, '--apply') + self.assertIn('04_bad.png', str(ctx.exception)) + self.assertEqual(fake.calls, []) + + def test_a_file_that_is_not_a_png_is_refused(self) -> None: + (self.shots / '04_junk.png').write_bytes(b'not a png at all, just text') + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError) as ctx: + self.screenshots(fake, '--apply') + self.assertIn('04_junk.png', str(ctx.exception)) + + def test_a_missing_android_phone_folder_is_refused(self) -> None: + args = _parse('screenshots', '--dir', str(self.root / 'nope')) + with self.assertRaises(PlayError) as ctx: + with _Patched(FakePlay()): + _run(play_store.cmd_screenshots, args) + self.assertIn('android-phone', str(ctx.exception)) + + +class AabManifestTest(unittest.TestCase): + def test_reads_package_version_code_and_name(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'app.aab' + _make_aab(path, 'net.meshmapper.app', 1790000001, '1.4.1') + info = play_store.read_aab_manifest(str(path)) + self.assertEqual(info, {'package': 'net.meshmapper.app', + 'versionCode': 1790000001, 'versionName': '1.4.1'}) + + +class TrackAlreadyHasTest(unittest.TestCase): + NOTES = [{'language': 'en-US', 'text': 'Faster map.'}] + + def release(self, **over) -> dict: + have = {'versionCodes': ['1790000001'], 'status': 'completed', + 'releaseNotes': list(self.NOTES)} + have.update(over) + return have + + def wanted(self, **over) -> dict: + return play_store.build_release( + None, [1790000001], over.get('notes', self.NOTES), over.get('status', 'completed'), + over.get('fraction')) + + def test_same_release_matches(self) -> None: + self.assertTrue(play_store.track_already_has({'releases': [self.release()]}, self.wanted())) + + def test_different_notes_status_or_codes_do_not_match(self) -> None: + track = {'releases': [self.release()]} + for label, wanted in ( + ('notes', self.wanted(notes=[{'language': 'en-US', 'text': 'Other.'}])), + ('no notes', self.wanted(notes=None)), + ('status', self.wanted(status='draft')), + ('fraction', self.wanted(status='inProgress', fraction=0.2)), + ('codes', play_store.build_release(None, [1790000002], self.NOTES, 'completed', None))): + with self.subTest(label): + self.assertFalse(play_store.track_already_has(track, wanted)) + + def test_another_release_on_the_track_is_a_change(self) -> None: + other = self.release(versionCodes=['1789991039']) + self.assertFalse(play_store.track_already_has( + {'releases': [self.release(), other]}, self.wanted())) + + def test_an_empty_or_missing_track_is_a_change(self) -> None: + self.assertFalse(play_store.track_already_has({'releases': []}, self.wanted())) + self.assertFalse(play_store.track_already_has(None, self.wanted())) + + +class UploadAabFlowTest(unittest.TestCase): + CODE = 1790000001 + TRACKS = '/edits/%s/tracks/production' % EDIT + BUNDLES = '/edits/%s/bundles' % EDIT + NOTES = 'Faster map.\nFixes.' + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.tmp = Path(self._tmp.name) + self.aab = self.tmp / 'MeshMapper.aab' + _make_aab(self.aab, 'net.meshmapper.app', self.CODE, '1.4.1') + self.notes = str(self.tmp / 'notes.txt') + Path(self.notes).write_text(self.NOTES, encoding='utf-8') + + def routes(self, on_play: bool = False, track: list | None = None, extra: dict | None = None) -> dict: + routes = { + ('GET', self.BUNDLES): {'bundles': [{'versionCode': 1789991039}] + + ([{'versionCode': self.CODE}] if on_play else [])}, + ('POST', self.BUNDLES): {'versionCode': self.CODE, 'sha1': 'abc'}, + ('PUT', self.TRACKS): {}, + ('POST', '/edits/%s:validate' % EDIT): {'id': EDIT}, + ('POST', '/edits/%s:commit' % EDIT): {}, + } + if track is not None: + routes[('GET', '/edits/%s/tracks' % EDIT)] = { + 'tracks': [{'track': 'production', 'releases': track}]} + routes.update(extra or {}) + return routes + + def upload(self, fake: FakePlay, *flags: str): + args = _parse('upload', '--track', 'production', '--status', 'completed', + '--notes-file', self.notes, '--aab', str(self.aab), *flags) + with _Patched(fake): + return _run(play_store.cmd_upload, args) + + def bundle_posts(self, fake: FakePlay) -> list: + return [kw for m, p, _, kw in fake.calls if (m, p) == ('POST', self.BUNDLES)] + + def put_release(self, fake: FakePlay) -> dict: + return [b for m, p, b, _ in fake.calls if m == 'PUT'][0]['releases'][0] + + def live_release(self, **over) -> dict: + release = {'name': '1.4.1 (%d)' % self.CODE, 'versionCodes': [str(self.CODE)], + 'status': 'completed', + 'releaseNotes': [{'language': 'en-US', 'text': self.NOTES}]} + release.update(over) + return release + + def test_a_new_version_code_uploads_the_bundle_then_puts_and_commits(self) -> None: + fake = FakePlay(self.routes()) + _, out = self.upload(fake, '--apply') + posts = self.bundle_posts(fake) + self.assertEqual([kw['upload_path'] for kw in posts], [str(self.aab)]) + self.assertEqual([(m, p) for m, p, _ in fake.writes()], [ + ('POST', self.BUNDLES), ('PUT', self.TRACKS), + ('POST', '/edits/%s:commit' % EDIT)]) + release = self.put_release(fake) + self.assertEqual(release['versionCodes'], [str(self.CODE)]) + self.assertEqual(release['name'], '1.4.1 (%d)' % self.CODE) + self.assertEqual(release['releaseNotes'], [{'language': 'en-US', 'text': self.NOTES}]) + self.assertNotIn('already on Play', out) + self.assertIn('Committed', out) + + def test_a_version_code_play_already_has_is_assigned_not_uploaded(self) -> None: + fake = FakePlay(self.routes(on_play=True)) + _, out = self.upload(fake, '--apply') + self.assertEqual(self.bundle_posts(fake), []) + self.assertEqual([(m, p) for m, p, _ in fake.writes()], [ + ('PUT', self.TRACKS), ('POST', '/edits/%s:commit' % EDIT)]) + self.assertEqual(self.put_release(fake)['versionCodes'], [str(self.CODE)]) + self.assertIn('already on Play, assigning instead of uploading', out) + + def test_validate_does_not_upload_a_bundle_play_already_has(self) -> None: + fake = FakePlay(self.routes(on_play=True)) + _, out = self.upload(fake, '--validate') + self.assertEqual(self.bundle_posts(fake), []) + self.assertFalse(fake.committed()) + self.assertIn('validate: OK', out) + + def test_dry_run_says_so_and_writes_nothing(self) -> None: + fake = FakePlay(self.routes(on_play=True)) + _, out = self.upload(fake) + self.assertEqual(fake.writes(), []) + self.assertIn('already on Play, assigning instead of uploading', out) + fake = FakePlay(self.routes(on_play=False)) + _, out = self.upload(fake) + self.assertEqual(fake.writes(), []) + self.assertNotIn('already on Play', out) + + def test_the_identical_release_already_on_the_track_is_not_committed(self) -> None: + fake = FakePlay(self.routes(on_play=True, track=[self.live_release()])) + for flags in (('--apply',), ()): + with self.subTest(flags=flags): + fake = FakePlay(self.routes(on_play=True, track=[self.live_release()])) + _, out = self.upload(fake, *flags) + self.assertEqual(fake.writes(), []) + self.assertFalse(fake.committed()) + self.assertIn('Already on production; nothing to change', out) + + def test_validate_still_stages_an_identical_release(self) -> None: + fake = FakePlay(self.routes(on_play=True, track=[self.live_release()])) + _, out = self.upload(fake, '--validate') + self.assertIn(('PUT', self.TRACKS), fake.paths()) + self.assertIn(('POST', '/edits/%s:validate' % EDIT), fake.paths()) + self.assertFalse(fake.committed()) + self.assertIn('validate: OK', out) + + def test_same_build_with_different_notes_is_still_committed(self) -> None: + old = self.live_release(releaseNotes=[{'language': 'en-US', 'text': 'Old notes.'}]) + fake = FakePlay(self.routes(on_play=True, track=[old])) + _, out = self.upload(fake, '--apply') + self.assertTrue(fake.committed()) + self.assertNotIn('nothing to change', out) + + def test_a_rerun_after_a_commit_changes_nothing(self) -> None: + """First run uploads and commits; the second sees the build and the + release on Play and does nothing.""" + first = FakePlay(self.routes()) + self.upload(first, '--apply') + self.assertTrue(first.committed()) + second = FakePlay(self.routes(on_play=True, track=[self.put_release(first)])) + _, out = self.upload(second, '--apply') + self.assertEqual(second.writes(), []) + self.assertIn('nothing to change', out) + + def test_an_aab_of_another_package_is_refused_before_any_request(self) -> None: + _make_aab(self.aab, 'com.example.other', self.CODE, '1.4.1') + fake = FakePlay(self.routes()) + with self.assertRaises(PlayError): + self.upload(fake, '--apply') + self.assertEqual(fake.calls, []) + + def test_the_already_used_hint_keeps_status_notes_and_language(self) -> None: + err = play_store.ApiError(403, 'Version code 1790000001 has already been used.', 'Uploading') + fake = FakePlay(self.routes(extra={('POST', self.BUNDLES): err})) + with self.assertRaises(play_store.ApiError) as ctx: + self.upload(fake, '--apply', '--lang', 'en-GB') + hint = play_store.explain_api_error(ctx.exception) + self.assertIn('--version-code %d' % self.CODE, hint) + self.assertIn('--status completed', hint) + self.assertIn('--notes-file %s' % self.notes, hint) + self.assertIn('--lang en-GB', hint) + self.assertIn('--apply', hint) + + +class StatusAndPromoteTest(unittest.TestCase): + def test_status_is_read_only(self) -> None: + fake = FakePlay({ + ('GET', '/tracks/production/releases'): {'releases': []}, + ('GET', '/edits/%s/bundles' % EDIT): {'bundles': [{'versionCode': 1789991039}]}, + }) + with _Patched(fake): + _, out = _run(play_store.cmd_status, _parse('status')) + self.assertEqual(fake.writes(), []) + self.assertFalse(fake.committed()) + self.assertIn('defaultLanguage: en-US', out) + self.assertIn('1.4.0 (1789991039)', out) + self.assertIn('en-US', out) + + def test_promote_dry_run_writes_nothing_and_apply_commits(self) -> None: + tracks = {'tracks': [ + {'track': 'beta', 'releases': [{'name': '1.4.1 (1790000000)', 'status': 'completed', + 'versionCodes': ['1790000000']}]}, + {'track': 'production', 'releases': []}]} + routes = {('GET', '/edits/%s/tracks' % EDIT): tracks, + ('PUT', '/edits/%s/tracks/production' % EDIT): {}, + ('POST', '/edits/%s:commit' % EDIT): {}} + fake = FakePlay(routes) + with _Patched(fake): + _run(play_store.cmd_promote, _parse('promote', '--from', 'beta', '--to', 'production')) + self.assertEqual(fake.writes(), []) + fake = FakePlay(routes) + with _Patched(fake): + _run(play_store.cmd_promote, + _parse('promote', '--from', 'beta', '--to', 'production', '--apply')) + self.assertTrue(fake.committed()) + put = [b for m, p, b, _ in fake.calls if m == 'PUT'][0] + self.assertEqual(put['releases'][0]['versionCodes'], ['1790000000']) + + +class ExplainApiErrorTest(unittest.TestCase): + def test_permission_hint_names_the_production_permissions(self) -> None: + hint = play_store.explain_api_error(play_store.ApiError(403, 'forbidden', 'x')) + self.assertIn('Release to production', hint) + self.assertIn('Manage store presence', hint) + + +if __name__ == '__main__': + unittest.main()