Compare commits

...

63 Commits

Author SHA1 Message Date
Janez T
30cac1bcbf Remove 100ms BLE command delay 2026-03-07 09:30:10 +01:00
Janez T
95e6aa35e2 Remove 100ms BLE command delay 2026-03-07 09:26:13 +01:00
Janez T
2bc0e21cf0 Remove 100ms BLE command delay 2026-03-07 09:23:29 +01:00
Janez T
f6c5a3a4ca Add transmission timing details 2026-03-07 09:05:55 +01:00
Janez T
810897d348 Refactor message header pill 2026-03-07 08:39:32 +01:00
Janez T
bb1c1f455d Refine message composer layout 2026-03-07 08:31:09 +01:00
Janez T
b0eded3780 Fix message bubble layout 2026-03-07 08:28:22 +01:00
Janez T
f1d56e2000 Refactor messages tab UI 2026-03-07 08:16:28 +01:00
Janez T
70a6156e8a Update iOS project version 2026-03-06 21:22:51 +01:00
Janez T
1856dce27a Update iOS project version 2026-03-06 21:05:02 +01:00
Janez T
485ae995c3 Commit client and rerun pub get 2026-03-06 20:51:49 +01:00
Janez T
0e1a56d765 Log contact data without revealing 2026-03-06 20:47:02 +01:00
Janez T
ca8e8e6ecb Increase cache for public repeaters 2026-03-06 20:29:30 +01:00
Janez T
43f5702666 Add conservative ACK timeout 2026-03-06 20:27:05 +01:00
Janez T
85d0b26c67 Add retransmission handling 2026-03-06 20:12:12 +01:00
Janez T
7cd5351921 Improve message input layout 2026-03-06 20:01:56 +01:00
Janez T
96feb75712 feat: save all pending work
ref:
2026-03-06 20:01:56 +01:00
Janez T
f6779e8776 fix: clean up messages composer bar
ref:
2026-03-06 20:01:56 +01:00
Janez Troha
a9d062dc34 Merge pull request #11 from MGJ520/main
Fix the Chinese translation switching issue
2026-03-06 16:23:51 +01:00
MGJ
3680b38302 Fix the Chinese translation switching issue 2026-03-06 20:10:26 +08:00
Janez T
e3902cea1e fix: bump client lock
ref:
2026-03-05 20:58:58 +01:00
Janez T
2482f94cd0 Push meshcore_client and refresh pub 2026-03-05 20:58:29 +01:00
Janez T
2b34bc4162 fix: stop lpp zero tail
ref:
2026-03-05 20:12:09 +01:00
Janez T
03c0c7ad38 fix: safe scan notifications
ref:
2026-03-05 20:10:08 +01:00
Janez T
42fc1f9cd2 fix: defer dialog scan start
ref:
2026-03-05 20:08:36 +01:00
Janez T
7807ad7471 Compare meshcore repos for bugs 2026-03-05 19:54:49 +01:00
Janez T
310eee1ff5 Compare meshcore sar against open 2026-03-05 19:48:16 +01:00
Janez T
b8f03079e7 Fix channel data sending bug 2026-03-05 19:39:03 +01:00
Janez T
ab0c531a4b Add toast for image fetch failures 2026-03-05 13:07:53 +01:00
Janez T
9709511e90 Fix image bubble contact lookup 2026-03-05 11:56:34 +01:00
Janez T
162d5333ce Hide tab bar when single tab 2026-03-05 11:51:23 +01:00
Janez T
0cb1d49804 Fix null check crash in TabBar 2026-03-05 11:41:15 +01:00
Janez T
234edf5bb0 Add message clear option 2026-03-05 11:04:41 +01:00
Janez T
2d9cb0ddb9 Add tic tac toe DM game 2026-03-05 09:57:14 +01:00
Janez T
76b093685e Add fragment transfer estimate 2026-03-05 09:38:39 +01:00
Janez T
55a85659d3 Add tic tac toe DM game 2026-03-05 09:05:18 +01:00
Janez T
972a9ba944 Document raw binary routing 2026-03-05 08:51:18 +01:00
Janez T
f4e3f2e834 Limit media fetch hops and warn user 2026-03-05 08:39:58 +01:00
Janez T
50a4322f44 Limit media fetch hops to three 2026-03-05 08:31:34 +01:00
Janez T
c83eaa4d98 Limit direct payload hops 2026-03-05 08:30:06 +01:00
Janez T
5beac70644 Add auto contact toggle 2026-03-05 08:16:48 +01:00
Janez T
99cd378e6a Add stats pills and RFC3339 date 2026-03-05 08:13:18 +01:00
Janez T
6a52e7cfa1 Add stats pills and RFC009 date 2026-03-05 08:12:48 +01:00
Janez T
af2e969640 Update release checker to GitHub API 2026-03-05 08:05:55 +01:00
Janez T
b12567f613 Add trace button and raw packets 2026-03-05 08:02:39 +01:00
Janez T
13b91e3cc9 Add packet trace storage flow 2026-03-05 07:50:42 +01:00
Janez T
40d786eb25 Add trace button to message bubble 2026-03-05 07:45:16 +01:00
Janez T
b6aa0bcfaa Bump iOS project version 2026-03-05 07:36:21 +01:00
Janez T
f31083694f Fix DM private media sending 2026-03-04 19:55:53 +01:00
Janez T
1460bdb51f fix: remove all auto-retry image fetch, user-initiated only
- No automatic IR1 requests; fragments arrive only when user taps load
- Bubble sends IR1 with missing indices only if partial session exists
  (partial resume: only missing fragments requested, not the whole image)
- 30s timeout resets the loading spinner so user can tap retry again
- Saves LoRa airtime by never transmitting IR1 without explicit user action
2026-03-04 19:47:01 +01:00
Janez T
537d98e2d4 fix: image transfer 10s idle timeout with partial resume
- Replace 1.2s fixed retry with 10s idle debounce timer
- Timer resets on every received fragment (debounce)
- Timer also starts on IE1 envelope receipt (handles pull-only senders)
- IR1 always requests only missing indices (partial resume)
- Attempt counter no longer resets per fragment; bounded to 5 retries
- Max attempts raised to 5 (was 4)
2026-03-04 19:42:18 +01:00
Janez T
7ffc46438f fix: disable voice recording on web via kIsWeb guard 2026-03-04 19:21:43 +01:00
Janez T
efab2cd057 fix: stub codec2 FFI for web build using conditional exports 2026-03-04 19:19:40 +01:00
Janez T
d6077d1588 ci: add web build and GitHub Pages deployment 2026-03-04 19:16:15 +01:00
Janez T
84a6f81c26 feat: replace SSE client with direct TCP/WiFi connection
- Remove SseClientService and ConnectionMode.sseClient
- Add ConnectionMode.tcp with MeshCoreTcpService (port 5000)
- NetworkScannerService: scan TCP port 5000 via raw Socket.connect
- mDNS service type changed to _meshcore._tcp
- connection_dialog: connect via connectTcp() instead of connectToSseServer()
- home_screen: show WiFi icon and label for TCP mode
- Bump meshcore_client to pick up TCP transport support
2026-03-04 19:11:16 +01:00
Janez T
c6b3b86c2f feat: add iOS TestFlight link README
ref:
2026-03-04 13:30:59 +01:00
Janez T
d1e6aaafbe feat: update README protocol media details
ref:
2026-03-04 13:27:25 +01:00
Janez T
3036ba620c Add codec2 avif meshcore details 2026-03-04 13:25:54 +01:00
Janez Troha
9854dd2034 Add Chinese translation
Add new Chinese translation
2026-03-04 12:48:37 +01:00
MGJ
e9a08fab4d Add new Chinese translation 2026-03-04 15:02:39 +08:00
Janez Troha
9814c95cee Update demo video section in README
Updated demo video link and thumbnail in README.
2026-03-02 10:46:53 +01:00
Janez T
85ebf51bcb Add MeshCore SAR demo link 2026-03-02 10:44:52 +01:00
Janez T
e85e290265 Update MeshCoreBleService calls 2026-03-02 10:33:49 +01:00
94 changed files with 19302 additions and 5203 deletions

View File

@@ -8,6 +8,8 @@ on:
permissions:
contents: write
pages: write
id-token: write
env:
FLUTTER_VERSION: "3.35.6"
@@ -256,6 +258,49 @@ jobs:
${{ env.IOS_RUNNER_ZIP }}
if-no-files-found: error
build-web:
name: Build Web App
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
channel: stable
cache: true
- name: Enable web
run: flutter config --enable-web
- name: Install dependencies
run: flutter pub get
- name: Build web release
run: flutter build web --release --base-href /meshcore_sar_app/
- name: Upload pages artifact
uses: actions/upload-pages-artifact@v3
with:
path: build/web
deploy-pages:
name: Deploy to GitHub Pages
runs-on: ubuntu-latest
needs: build-web
if: github.ref == 'refs/heads/main'
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
upload-release-assets:
name: Upload Assets To Release
if: github.event_name == 'release'

View File

@@ -34,8 +34,9 @@ DAILY_BUILD := $(shell \
# Version format: YYYY.MMDD.DAILY+BUILD
# DAILY resets each day (for readability), BUILD always increments (for Android)
NEW_VERSION := $(YEAR).$(MMDD).$(DAILY_BUILD)+$(NEW_BUILD_NUMBER)
NEW_BUILD_NAME := $(shell echo $(NEW_VERSION) | cut -d'+' -f1)
.PHONY: help version bump build release release-android release-ios clean deps analyze test icon bundle bundle-no-bump
.PHONY: help version bump make-bump sync-ios-version build release release-android release-ios clean deps analyze test icon bundle bundle-no-bump
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'
@@ -49,8 +50,19 @@ version: ## Show current and next version
bump: ## Bump version in pubspec.yaml
@echo "Bumping version to $(NEW_VERSION)..."
@sed -i '' 's/^version: .*/version: $(NEW_VERSION)/' $(PUBSPEC)
@$(MAKE) sync-ios-version BUILD_NAME=$(NEW_BUILD_NAME) BUILD_NUMBER=$(NEW_BUILD_NUMBER)
@echo "Version bumped to $(NEW_VERSION)"
make-bump: bump ## Alias for bump
sync-ios-version: ## Sync iOS FLUTTER_BUILD_NAME/NUMBER from pubspec or provided BUILD_NAME/BUILD_NUMBER
@$(eval IOS_VERSION := $(shell grep '^version:' $(PUBSPEC) | sed 's/version: //'))
@$(eval IOS_BUILD_NAME := $(if $(BUILD_NAME),$(BUILD_NAME),$(shell echo $(IOS_VERSION) | cut -d'+' -f1)))
@$(eval IOS_BUILD_NUMBER := $(if $(BUILD_NUMBER),$(BUILD_NUMBER),$(shell echo $(IOS_VERSION) | cut -d'+' -f2)))
@echo "Syncing iOS version to $(IOS_BUILD_NAME)+$(IOS_BUILD_NUMBER)..."
@flutter build ios --config-only --build-name "$(IOS_BUILD_NAME)" --build-number "$(IOS_BUILD_NUMBER)" > /dev/null
@echo "iOS version synced"
deps: ## Install dependencies
flutter pub get
@@ -115,6 +127,7 @@ release-android: build ## Build APK and create GitHub release (Android only)
release-ios: ## Build iOS and upload to TestFlight
@echo "Building iOS and uploading to TestFlight..."
@$(MAKE) sync-ios-version
cd ios && fastlane release
@echo "iOS release uploaded!"

View File

@@ -15,13 +15,19 @@
</p>
MeshCore SAR helps teams coordinate in low-connectivity or no-connectivity environments with messaging, voice, images, maps, and live location context in one app.
It uses the MeshCore protocol over LoRa for long-range, infrastructure-free communication.
`iOS TestFlight:` https://testflight.apple.com/join/HhzerdHp
## Highlights
- Fast mesh messaging for direct and group coordination
- On-demand voice and image transfer optimized for constrained links
- Offline-first mapping with tactical overlays and SAR markers
- Live team tracking, trails, and shareable map drawings
- Rapid mesh chat for both 1:1 and group coordination
- On-demand voice (Codec2) and image (AVIF) transfer tuned for low-bandwidth links
- Offline-first mapping with tactical overlays and SAR incident markers
- Live team location, movement trails, and shareable tactical drawings
## Demo Video
[<img width="1280" height="720" alt="MeshCore SAR demo preview" src="https://github.com/user-attachments/assets/13ccacee-7306-4976-a408-f31f3336828a" />](https://youtu.be/rLsKeLJBpFg)
## Screenshots
@@ -38,8 +44,8 @@ MeshCore SAR helps teams coordinate in low-connectivity or no-connectivity envir
| Area | What you get |
|---|---|
| Messaging | Direct and group chat over mesh, with contact/room awareness from live telemetry |
| Voice | Push-to-talk voice clips, fetched on demand when play is pressed, auto-play on completion |
| Images | Camera/gallery image sending, auto-compression, tap-to-load receiving, full-screen viewer |
| Voice | Push-to-talk voice clips (Codec2), fetched on demand when play is pressed, auto-play on completion |
| Images | Camera/gallery image sending (AVIF), auto-compression, tap-to-load receiving, full-screen viewer |
| Maps | Street/topo/satellite/terrain layers, offline tile downloads, optional MBTiles import |
| SAR Operations | Team markers with freshness indicators, SAR markers for incidents and staging points |
| Tracking | Continuous GPS updates, personal trails, distance/duration trail stats |

View File

@@ -23,6 +23,7 @@
<!-- Microphone for voice messages -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- Notifications -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

View File

@@ -5,8 +5,9 @@
Image mode mirrors the voice on-demand architecture exactly:
- **Control plane (text messages):**
- `IE1:` image envelope announces image availability in chat.
- `IR1:` direct fetch request asks sender to stream image fragments.
- `IE2:` image envelope announces image availability in chat.
- **Control plane (raw binary request):**
- Binary image fetch request (same raw route as image fragments).
- **Data plane (raw binary packets):**
- `ImagePacket` binary payload streamed via `cmdSendRawData` / `pushRawData`.
@@ -17,8 +18,8 @@ pixels are fetched on demand when the user taps the image bubble.
- `lib/utils/image_message_parser.dart`
- `ImagePacket` (binary fragment format)
- `ImageEnvelope` (`IE1`)
- `ImageFetchRequest` (`IR1`)
- `ImageEnvelope` (`IE2`)
- `ImageFetchRequest` (binary)
- `fragmentImage()` — split compressed bytes into packets
- `reassembleImage()` — join received fragments into bytes
- `lib/screens/messages_tab.dart`
@@ -27,7 +28,7 @@ pixels are fetched on demand when the user taps the image bubble.
- Reassembly sessions, outgoing cache, deferred serving
- Outgoing sessions also registered as complete incoming sessions for immediate local display
- `lib/providers/app_provider.dart`
- Incoming routing for `IE1`, `IR1`, binary `0x49` packets
- Incoming routing for `IE2`, binary image fetch requests, binary `0x49` packets
- `lib/widgets/messages/image_message_bubble.dart`
- Square cover thumbnail (up to 256 px); tap-to-load for received images;
progress ring during fetch; full-screen `InteractiveViewer` on tap
@@ -39,52 +40,52 @@ pixels are fetched on demand when the user taps the image bubble.
## 3. Wire Formats
### 3.1 Image Envelope (`IE1`)
### 3.1 Image Envelope (`IE2`)
Prefix: `IE1:` + colon-delimited payload
Prefix: `IE2:` + colon-delimited compact payload (base36 numeric fields)
Fields:
| Field | Type | Description |
|--------------|--------|------------------------------------------------|
| `sid` | string | 8 hex chars (4 bytes), session ID |
| `fmt` | int | `ImageFormat.id` (0 = AVIF, 1 = JPEG) |
| `total` | int | Fragment count (1..255) |
| `w` | int | Actual image width after compression (pixels) |
| `h` | int | Actual image height after compression (pixels) |
| `bytes` | int | Total compressed size in bytes |
| `sid` | string | base36 token for 32-bit session ID |
| `fmt` | base36 | `ImageFormat.id` (0 = AVIF, 1 = JPEG) |
| `total` | base36 | Fragment count (1..255) |
| `w` | base36 | Actual image width after compression (pixels) |
| `h` | base36 | Actual image height after compression (pixels) |
| `bytes` | base36 | Total compressed size in bytes |
| `senderKey6` | string | 12 hex chars (6 bytes sender prefix) |
| `ts` | int | Unix timestamp (seconds) |
| `ver` | int | Protocol version (currently `1`) |
| `ts` | base36 | Unix timestamp (seconds) |
Compact format:
```text
IE1:{sid}:{fmt}:{total}:{w}:{h}:{bytes}:{senderKey6}:{ts}:{ver}
IE2:{sid}:{fmt}:{total}:{w}:{h}:{bytes}:{senderKey6}:{ts}
```
Example (256×171 landscape image, 14 fragments):
```text
IE1:deadbeef:0:14:256:171:2100:aabbccddeeff:1700000000:1
IE2:a:0:e:74:4r:1mc:aabbccddeeff:s44we8
```
Note: `w` and `h` reflect the actual post-compression dimensions, which preserve
Note: `sid` is base36 on wire and expands to 8-hex internally.
`w` and `h` reflect the actual post-compression dimensions, which preserve
the source aspect ratio (contain within the configured max size).
### 3.2 Image Fetch Request (`IR1`)
### 3.2 Image Fetch Request (binary)
Same structure as `VR1`:
Binary payload format:
```text
IR1:{sid}:{want}:{requesterKey6}:{ts}:{ver}
[magic=0x69][sid:4B][flags:1B][requesterKey6:6B][ts:4B][missingCount:1B][missingIndices...]
```
| Field | Value |
|------------------|--------------------------|
| `want` | `a` (= "all fragments") |
| `requesterKey6` | 12 hex chars |
| `ver` | `1` |
| `flags` | bit0=1 => request missing indices, else all |
| `requesterKey6` | 6-byte requester key prefix |
| `ts` | unix timestamp seconds (u32) |
### 3.3 Raw Image Packet (data plane)
@@ -151,16 +152,16 @@ only the shorter axis is padded — no cropping occurs.
7. Envelope sent via normal message path:
- Channel: `sendChannelMessage`
- Direct: `sendTextMessage`
8. Local placeholder message added (`IE1:` text, `deliveryStatus.sending`).
8. Local placeholder message added (`IE2:` text, `deliveryStatus.sending`).
## 6. Incoming Flow (Receive)
### 6.1 `IE1` envelope received
### 6.1 `IE2` envelope received
`AppProvider` calls `imageProvider.registerEnvelope()` and adds the message to
chat. The bubble shows a grey square placeholder with a download icon.
### 6.2 `IR1` request received
### 6.2 Binary image fetch request received
`AppProvider` treats it as control-plane only (not added to chat):
@@ -194,7 +195,7 @@ When `cacheOutgoingSession()` is called it also writes all fragments into
- **Complete session**: `AspectRatio(1.0)``AvifImage.memory(fit: cover)`
square thumbnail; tap → full-screen `InteractiveViewer` with fade transition.
- **Incomplete/missing**: grey square placeholder with download icon;
tap → sends `IR1` fetch request.
tap → sends binary fetch request.
- **Loading**: circular progress indicator showing `received/total` count.
- **Error**: broken-image icon.
@@ -212,7 +213,8 @@ Image bubbles and Message Technical Details show an **estimated transmit time**
The estimate is airtime-based (LoRa packet model), not just compressed image size:
- Source inputs:
- `total` fragments and `bytes` from `IE1` envelope
- `total` fragments and `bytes` from `IE2` envelope
- all numeric envelope values are decoded from base36
- `pathLen` from message metadata
- current radio params from `deviceInfo`: `radioBw`, `radioSf`, `radioCr`
- Per-fragment payload model:
@@ -248,6 +250,16 @@ Fallback defaults are used when radio params are unavailable: `SF10`, `BW250kHz`
- Raw return path requires a valid direct route to requester.
- Available on iOS and Android (`image_picker` + `flutter_avif`).
### 11.1 Raw Binary Routing Semantics
- Image fragment payloads use companion command `CMD_SEND_RAW_DATA` (`25` / `0x19`).
- Companion push back to the app is `PUSH_CODE_RAW_DATA` (`0x84`).
- Over-the-air packet type for this flow is `PAYLOAD_TYPE_RAW_CUSTOM` (`0x0F`).
- This flow is direct-route only, not flood/broadcast:
- it is sent to one destination path;
- only nodes on that path relay it;
- it is **not** received by everyone in the mesh.
## 12. High-Level Sequence
```mermaid
@@ -260,10 +272,10 @@ sequenceDiagram
A->>A: Compress: contain resize → grayscale → PNG → AVIF
A->>A: Fragment into ≤152B packets
A->>A: Cache outgoing + populate local session (immediate display)
A->>M: Send IE1 envelope (actual w×h, fragment count)
M->>B: Deliver IE1
A->>M: Send IE2 envelope (actual w×h, fragment count)
M->>B: Deliver IE2
B->>B: Render grey placeholder bubble
B->>A: Tap → send IR1 fetch request
B->>A: Tap → send binary fetch request
A->>B: Stream binary ImagePackets
B->>B: Reassemble fragments
B->>B: Display AVIF image (cover thumbnail)

View File

@@ -5,8 +5,9 @@
Voice mode uses a **two-plane architecture**:
- **Control plane (text messages):**
- `VE1:` voice envelope announces voice availability in chat.
- `VR1:` direct fetch request asks sender to stream voice payload.
- `VE2:` voice envelope announces voice availability in chat.
- **Control plane (raw binary request):**
- Binary voice fetch request (same raw route as voice packets).
- **Data plane (raw binary packets):**
- `VoicePacket` payload streamed via `cmdSendRawData` and received through `pushRawData`.
@@ -16,73 +17,58 @@ This design avoids broadcasting full voice payloads to channels/rooms. Chat carr
- `lib/utils/voice_message_parser.dart`
- `VoicePacket` (legacy text + binary packet format)
- `VoiceEnvelope` (`VE1`)
- `VoiceFetchRequest` (`VR1`)
- `VoiceEnvelope` (`VE2`)
- `VoiceFetchRequest` (binary)
- `lib/screens/messages_tab.dart`
- Capture/encode voice, cache encoded packets, send envelope only
- `lib/providers/voice_provider.dart`
- Reassembly/playback sessions
- Outgoing session cache + deferred serving
- `lib/providers/app_provider.dart`
- Incoming routing for `VE1` and `VR1`
- Incoming routing for `VE2` and binary voice fetch requests
- Handles raw packet ingestion
- `lib/widgets/messages/voice_message_bubble.dart`
- Play behavior (immediate play if complete, otherwise fetch + auto-play)
- `lib/providers/messages_provider.dart`
- Message-level voice detection (`VE1` + legacy `V:`)
- Message-level voice detection (`VE2` + legacy `V:`)
- `lib/services/message_storage_service.dart`
- Persists `isVoice` and `voiceId`
## 3. Wire Formats
### 3.1 Voice Envelope (`VE1`)
### 3.1 Voice Envelope (`VE2`)
Prefix: `VE1:` + colon-delimited compact payload
Prefix: `VE2:` + colon-delimited compact payload (base36 numeric fields)
Fields:
- `sid` (string, 8 hex chars): session ID
- `mode` (int): codec mode ID (`VoicePacketMode.id`)
- `total` (int): packet count (1..255)
- `durMs` (int): estimated duration in ms
- `sid` (string): base36 token for 32-bit session ID
- `mode` (base36): codec mode ID (`VoicePacketMode.id`)
- `total` (base36): packet count (1..255)
- `durS` (base36): estimated duration in seconds
- `senderKey6` (string, 12 hex chars): sender public-key prefix (6 bytes)
- `ts` (int): unix timestamp seconds
- `ver` (int): protocol version (currently `1`)
- `ts` (base36): unix timestamp seconds
`sid` is base36 on wire and expands to 8-hex internally.
Compact format:
```text
VE1:{sid}:{mode}:{total}:{durMs}:{senderKey6}:{ts}:{ver}
VE2:{sid}:{mode}:{total}:{durS}:{senderKey6}:{ts}
```
Example:
```text
VE1:deadbeef:1:4:3200:aabbccddeeff:1700000000:1
VE2:a:1:4:4:aabbccddeeff:s44we8
```
### 3.2 Voice Fetch Request (`VR1`)
### 3.2 Voice Fetch Request (binary)
Prefix: `VR1:` + colon-delimited compact payload
Fields:
- `sid` (string, 8 hex chars): requested session
- `want` (string): currently `a` (compact token for `all`)
- `requesterKey6` (string, 12 hex chars): requester key prefix
- `ts` (int): unix timestamp seconds
- `ver` (int): protocol version (`1`)
Compact format:
Binary payload format:
```text
VR1:{sid}:{want}:{requesterKey6}:{ts}:{ver}
```
Example:
```text
VR1:deadbeef:a:112233445566:1700000010:1
[magic=0x72][sid:4B][flags:1B][requesterKey6:6B][ts:4B][missingCount:1B][missingIndices...]
```
### 3.3 Raw Voice Packet (data plane)
@@ -102,18 +88,18 @@ Binary payload structure:
2. Each chunk is codec2-encoded into `VoicePacket` objects.
3. Packets are cached in `VoiceProvider` outgoing cache (TTL 15 min).
4. Sender inserts local voice placeholder message (`isVoice=true`, `voiceId=sessionId`).
5. Sender sends one envelope (`VE1`) through normal message path:
5. Sender sends one envelope (`VE2`) through normal message path:
- channel/room: `sendChannelMessage`
- direct: `sendTextMessage`
6. **No raw audio packets are sent during initial send.**
## 5. Incoming Routing
### 5.1 `VE1` envelope received
### 5.1 `VE2` envelope received
`AppProvider` marks message as voice (`isVoice`, `voiceId`) and adds it to chat.
### 5.2 `VR1` request received
### 5.2 Binary voice fetch request received
`AppProvider` treats it as control-plane only:
@@ -132,8 +118,8 @@ In `VoiceMessageBubble`:
- If session already complete: play immediately.
- If incomplete/missing:
1. Resolve sender contact (message sender prefix or `VE1.senderKey6` fallback)
2. Send direct `VR1` fetch request
1. Resolve sender contact (message sender prefix or `VE2.senderKey6` fallback)
2. Send direct binary fetch request
3. Show requesting state in UI
4. Auto-play when session becomes complete
@@ -170,10 +156,9 @@ Parser validation enforces:
- strict hex lengths for IDs and key prefixes
- valid mode range
- valid packet counts and duration bounds
- fixed protocol version (`ver == 1`)
- `VR1.want` token `a` (internally normalized to `all`)
`VR1` handling verifies sender prefix matches `requesterKey6` to reduce spoofing risk.
- compact base36 numeric fields in envelope/request
- Binary request flags specify `all` or `missing` indices.
- Request payload includes `requesterKey6` to resolve return route.
## 10. Transmit Time Estimate (UI)
@@ -182,7 +167,8 @@ Voice bubbles and Message Technical Details show an **estimated transmit time**
The estimate is airtime-based (LoRa packet model), not file-duration-only:
- Source inputs:
- `packetCount` and `durationMs` from `VE1` envelope, or
- `packetCount` and `durationMs` from `VE2` envelope, or
- numeric envelope values decoded from base36
- actual received `VoicePacket.codec2Data.length` bytes when local session packets exist
- `pathLen` from message metadata
- current radio params from `deviceInfo`: `radioBw`, `radioSf`, `radioCr`
@@ -210,10 +196,20 @@ Fallback defaults are used when radio params are unavailable: `SF10`, `BW250kHz`
- Raw return path needs a currently valid direct route to requester.
- Voice capture is available on iOS and Android (`Platform.isIOS || Platform.isAndroid`).
### 11.1 Raw Binary Routing Semantics
- Voice payload packets use companion command `CMD_SEND_RAW_DATA` (`25` / `0x19`).
- Companion push back to the app is `PUSH_CODE_RAW_DATA` (`0x84`).
- Over-the-air packet type for this flow is `PAYLOAD_TYPE_RAW_CUSTOM` (`0x0F`).
- This flow is direct-route only, not flood/broadcast:
- it is sent to one destination path;
- only nodes on that path relay it;
- it is **not** received by everyone in the mesh.
## 12. Backward Compatibility
- Legacy `V:` text packet parsing is still supported.
- Message voice detection accepts both new `VE1` and legacy `V:` formats.
- Message voice detection accepts `VE2` and legacy `V:` formats.
## 13. High-Level Sequence
@@ -225,10 +221,10 @@ sequenceDiagram
A->>A: Record + encode voice packets
A->>A: Cache session packets (TTL 15m)
A->>M: Send VE1 envelope
M->>B: Deliver VE1
A->>M: Send VE2 envelope
M->>B: Deliver VE2
B->>B: Render voice bubble (metadata only)
B->>A: Send VR1 request on Play
B->>A: Send binary fetch request on Play
A->>B: Stream raw VoicePacket packets
B->>B: Reassemble session
B->>B: Auto-play when complete

View File

@@ -39,5 +39,13 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
# codec2_flutter uses ARM-specific register asm("sp") in debug_alloc.h that
# fails to compile for iOS simulators. Voice codec support is only required
# on real iOS devices, so skip the native Codec2 sources for simulator SDKs.
if target.name == 'codec2_flutter'
target.build_configurations.each do |config|
config.build_settings['EXCLUDED_SOURCE_FILE_NAMES[sdk=iphonesimulator*]'] = '*.c *.cpp'
end
end
end
end

View File

@@ -65,6 +65,9 @@ PODS:
- ObjectBox (= 4.4.1)
- package_info_plus (0.4.5):
- Flutter
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
- permission_handler_apple (9.3.0):
- Flutter
- record_ios (1.2.0):
@@ -102,6 +105,7 @@ DEPENDENCIES:
- nsd_ios (from `.symlinks/plugins/nsd_ios/ios`)
- objectbox_flutter_libs (from `.symlinks/plugins/objectbox_flutter_libs/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
- record_ios (from `.symlinks/plugins/record_ios/ios`)
- share_plus (from `.symlinks/plugins/share_plus/ios`)
@@ -149,6 +153,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/objectbox_flutter_libs/ios"
package_info_plus:
:path: ".symlinks/plugins/package_info_plus/ios"
path_provider_foundation:
:path: ".symlinks/plugins/path_provider_foundation/darwin"
permission_handler_apple:
:path: ".symlinks/plugins/permission_handler_apple/ios"
record_ios:
@@ -183,6 +189,7 @@ SPEC CHECKSUMS:
ObjectBox: 7da4aceb5013d041bfafdbc6d744a26918b09757
objectbox_flutter_libs: 09b1dec1b4cd27bf1a5f9bae7ccaa7e43588bf31
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
record_ios: 412daca2350b228e698fffcd08f1f94ceb1e3844
SDWebImage: e9fc87c1aab89a8ab1bbd74eba378c6f53be8abf
@@ -193,6 +200,6 @@ SPEC CHECKSUMS:
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
vibration: ca8104a8875b9c493e15b21b04e456befd0ff6eb
PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e
PODFILE CHECKSUM: 2d56c9747241a29800bf539d978b210bda037878
COCOAPODS: 1.16.2

View File

@@ -489,7 +489,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -511,7 +511,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -530,7 +530,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -547,7 +547,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -679,7 +679,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -702,7 +702,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 68;
CURRENT_PROJECT_VERSION = 95;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;

View File

@@ -43,7 +43,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>68</string>
<string>95</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSBluetoothAlwaysUsageDescription</key>
@@ -68,8 +68,12 @@
<string>MeshCore SAR needs access to the compass to show your heading direction on the map</string>
<key>NSMicrophoneUsageDescription</key>
<string>MeshCore SAR needs microphone access to send voice messages over the mesh radio network during SAR operations</string>
<key>NSCameraUsageDescription</key>
<string>MeshCore SAR needs camera access to take photos and attach them to SAR messages</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>MeshCore SAR may need access to your photo library to attach images to messages or save map screenshots for documentation during SAR operations</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>MeshCore SAR needs permission to save exported screenshots and SAR documentation images to your photo library</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>

View File

@@ -5,22 +5,22 @@
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000238">
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000239">
</testcase>
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.34961">
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.427601">
</testcase>
<testcase classname="fastlane.lanes" name="2: build_app" time="83.968525">
<testcase classname="fastlane.lanes" name="2: build_app" time="110.117264">
</testcase>
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="186.029813">
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="269.473315">
</testcase>

View File

@@ -13,6 +13,7 @@ import 'app_localizations_fr.dart';
import 'app_localizations_hr.dart';
import 'app_localizations_it.dart';
import 'app_localizations_sl.dart';
import 'app_localizations_zh.dart';
// ignore_for_file: type=lint
@@ -108,6 +109,7 @@ abstract class AppLocalizations {
Locale('hr'),
Locale('it'),
Locale('sl'),
Locale('zh'),
];
/// The application title
@@ -4225,6 +4227,7 @@ class _AppLocalizationsDelegate
'hr',
'it',
'sl',
'zh',
].contains(locale.languageCode);
@override
@@ -4250,6 +4253,8 @@ AppLocalizations lookupAppLocalizations(Locale locale) {
return AppLocalizationsIt();
case 'sl':
return AppLocalizationsSl();
case 'zh':
return AppLocalizationsZh();
}
throw FlutterError(

File diff suppressed because it is too large Load Diff

3848
lib/l10n/app_zh.arb Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -17,8 +17,8 @@ enum ConnectionMode {
/// Act as SSE server - share BLE device with multiple clients
sseServer,
/// Connect to remote SSE server - no direct BLE connection
sseClient,
/// Direct TCP/WiFi connection to MeshCore device (port 5000)
tcp,
}
extension ConnectionModeExtension on ConnectionMode {
@@ -28,8 +28,8 @@ extension ConnectionModeExtension on ConnectionMode {
return 'Direct (BLE)';
case ConnectionMode.sseServer:
return 'Share Device (Server)';
case ConnectionMode.sseClient:
return 'Connect to Server';
case ConnectionMode.tcp:
return 'Direct (WiFi)';
}
}
@@ -39,8 +39,8 @@ extension ConnectionModeExtension on ConnectionMode {
return 'Direct BLE connection to MeshCore device';
case ConnectionMode.sseServer:
return 'Share BLE device with multiple clients over network';
case ConnectionMode.sseClient:
return 'Connect to remote server without BLE';
case ConnectionMode.tcp:
return 'Direct WiFi/TCP connection to MeshCore device';
}
}
}
@@ -73,12 +73,14 @@ class DeviceInfo {
final String? selfName;
// Additional device capabilities (from RESP_CODE_DEVICE_INFO)
final int? maxContacts; // Max contacts device supports
final int? maxChannels; // Max channels device supports
final int? telemetryModes; // Telemetry permission modes (bits 0-1: Base, bits 2-3: Location)
final int? blePin; // BLE PIN code
final int? multiAcks; // Extra ACK mode (0=no, 1=yes)
final int? advertLocPolicy; // Location sharing policy (0=don't share, 1=share)
final int? maxContacts; // Max contacts device supports
final int? maxChannels; // Max channels device supports
final int?
telemetryModes; // Telemetry permission modes (bits 0-1: Base, bits 2-3: Location)
final int? blePin; // BLE PIN code
final int? multiAcks; // Extra ACK mode (0=no, 1=yes)
final int?
advertLocPolicy; // Location sharing policy (0=don't share, 1=share)
// Firmware info
final int? firmwareVersion;
@@ -88,6 +90,9 @@ class DeviceInfo {
// Repeat mode (firmware v9+)
final bool? clientRepeat;
final bool? supportsSpectrumScan;
final int? spectrumScanMinKhz;
final int? spectrumScanMaxKhz;
final List<({int lower, int upper})>? allowedRepeatFreqRanges;
DeviceInfo({
@@ -124,6 +129,9 @@ class DeviceInfo {
this.manufacturerModel,
this.semanticVersion,
this.clientRepeat,
this.supportsSpectrumScan,
this.spectrumScanMinKhz,
this.spectrumScanMaxKhz,
this.allowedRepeatFreqRanges,
});
@@ -160,7 +168,9 @@ class DeviceInfo {
/// Get storage usage percentage (0-100)
double? get storageUsedPercent {
if (storageUsedKb == null || storageTotalKb == null || storageTotalKb == 0) {
if (storageUsedKb == null ||
storageTotalKb == null ||
storageTotalKb == 0) {
return null;
}
return (storageUsedKb! / storageTotalKb!) * 100.0;
@@ -245,6 +255,9 @@ class DeviceInfo {
String? manufacturerModel,
String? semanticVersion,
bool? clientRepeat,
bool? supportsSpectrumScan,
int? spectrumScanMinKhz,
int? spectrumScanMaxKhz,
List<({int lower, int upper})>? allowedRepeatFreqRanges,
}) {
return DeviceInfo(
@@ -281,7 +294,11 @@ class DeviceInfo {
manufacturerModel: manufacturerModel ?? this.manufacturerModel,
semanticVersion: semanticVersion ?? this.semanticVersion,
clientRepeat: clientRepeat ?? this.clientRepeat,
allowedRepeatFreqRanges: allowedRepeatFreqRanges ?? this.allowedRepeatFreqRanges,
supportsSpectrumScan: supportsSpectrumScan ?? this.supportsSpectrumScan,
spectrumScanMinKhz: spectrumScanMinKhz ?? this.spectrumScanMinKhz,
spectrumScanMaxKhz: spectrumScanMaxKhz ?? this.spectrumScanMaxKhz,
allowedRepeatFreqRanges:
allowedRepeatFreqRanges ?? this.allowedRepeatFreqRanges,
);
}

View File

@@ -0,0 +1,63 @@
import 'package:latlong2/latlong.dart';
class MessageContactLocation {
final LatLng location;
final String source;
final DateTime capturedAt;
final DateTime? sourceTimestamp;
const MessageContactLocation({
required this.location,
required this.source,
required this.capturedAt,
this.sourceTimestamp,
});
String get technicalSourceLabel {
switch (source) {
case 'telemetry':
return 'telemetry';
case 'advert':
return 'advert';
default:
return source;
}
}
String get formattedCoordinates =>
'${location.latitude.toStringAsFixed(6)}, ${location.longitude.toStringAsFixed(6)}';
Map<String, dynamic> toJson() {
return {
'latitude': location.latitude,
'longitude': location.longitude,
'source': source,
'capturedAtMillis': capturedAt.millisecondsSinceEpoch,
'sourceTimestampMillis': sourceTimestamp?.millisecondsSinceEpoch,
};
}
static MessageContactLocation? fromJson(Map<String, dynamic> json) {
final latitude = json['latitude'];
final longitude = json['longitude'];
final source = json['source'];
final capturedAtMillis = json['capturedAtMillis'];
if (latitude is! num ||
longitude is! num ||
source is! String ||
capturedAtMillis is! int) {
return null;
}
return MessageContactLocation(
location: LatLng(latitude.toDouble(), longitude.toDouble()),
source: source,
capturedAt: DateTime.fromMillisecondsSinceEpoch(capturedAtMillis),
sourceTimestamp: json['sourceTimestampMillis'] is int
? DateTime.fromMillisecondsSinceEpoch(
json['sourceTimestampMillis'] as int,
)
: null,
);
}
}

View File

@@ -0,0 +1,86 @@
const int _transmitEstimateToleranceMs = 1500;
int? sanitizeEstimatedTransmitMs({
required int? estimatedTransmitMs,
required int? senderToReceiptMs,
}) {
if (estimatedTransmitMs == null || estimatedTransmitMs <= 0) {
return null;
}
if (senderToReceiptMs == null || senderToReceiptMs <= 0) {
return estimatedTransmitMs;
}
// Sender timestamps are second-granularity, so allow a small cushion before
// treating the estimate as impossible for the observed delivery time.
if (estimatedTransmitMs > senderToReceiptMs + _transmitEstimateToleranceMs) {
return null;
}
return estimatedTransmitMs;
}
class MessageReceptionDetails {
final DateTime capturedAt;
final DateTime? packetLoggedAt;
final int? rssiDbm;
final double? snrDb;
final List<int>? pathBytes;
final int? senderToReceiptMs;
final int? estimatedTransmitMs;
final int? postTransmitDelayMs;
const MessageReceptionDetails({
required this.capturedAt,
this.packetLoggedAt,
this.rssiDbm,
this.snrDb,
this.pathBytes,
this.senderToReceiptMs,
this.estimatedTransmitMs,
this.postTransmitDelayMs,
});
String? get pathBytesHex => pathBytes == null || pathBytes!.isEmpty
? null
: pathBytes!.map((b) => b.toRadixString(16).padLeft(2, '0')).join(':');
Map<String, dynamic> toJson() {
return {
'capturedAtMillis': capturedAt.millisecondsSinceEpoch,
'packetLoggedAtMillis': packetLoggedAt?.millisecondsSinceEpoch,
'rssiDbm': rssiDbm,
'snrDb': snrDb,
'pathBytes': pathBytes,
'senderToReceiptMs': senderToReceiptMs,
'estimatedTransmitMs': estimatedTransmitMs,
'postTransmitDelayMs': postTransmitDelayMs,
};
}
static MessageReceptionDetails? fromJson(Map<String, dynamic> json) {
final capturedAtMillis = json['capturedAtMillis'];
if (capturedAtMillis is! int) {
return null;
}
final pathBytes = json['pathBytes'];
return MessageReceptionDetails(
capturedAt: DateTime.fromMillisecondsSinceEpoch(capturedAtMillis),
packetLoggedAt: json['packetLoggedAtMillis'] is int
? DateTime.fromMillisecondsSinceEpoch(
json['packetLoggedAtMillis'] as int,
)
: null,
rssiDbm: json['rssiDbm'] as int?,
snrDb: (json['snrDb'] as num?)?.toDouble(),
pathBytes: pathBytes is List
? pathBytes.whereType<num>().map((b) => b.toInt()).toList()
: null,
senderToReceiptMs: json['senderToReceiptMs'] as int?,
estimatedTransmitMs: json['estimatedTransmitMs'] as int?,
postTransmitDelayMs: json['postTransmitDelayMs'] as int?,
);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
import 'package:flutter/foundation.dart';
import 'package:latlong2/latlong.dart';
import '../models/contact.dart';
import '../models/message_contact_location.dart';
import '../services/cayenne_lpp_parser.dart';
import '../services/contact_storage_service.dart';
import '../utils/key_comparison.dart';
@@ -214,6 +215,52 @@ class ContactsProvider with ChangeNotifier {
List<Contact> get chatContactsWithLocation =>
chatContacts.where((c) => c.displayLocation != null).toList();
MessageContactLocation? buildMessageContactLocationSnapshot(
Contact contact, {
DateTime? capturedAt,
}) {
final snapshotTime = capturedAt ?? DateTime.now();
final telemetryGps = _getValidGpsOrNull(contact.telemetry?.gpsLocation);
final telemetryTimestamp = contact.telemetry?.timestamp;
AdvertLocation? advertLocation;
for (final point in contact.advertHistory) {
if (!point.timestamp.isAfter(snapshotTime)) {
advertLocation = point;
break;
}
}
advertLocation ??= contact.advertHistory.isNotEmpty
? contact.advertHistory.first
: null;
if (telemetryGps != null) {
final shouldUseTelemetry =
telemetryTimestamp == null ||
advertLocation == null ||
!telemetryTimestamp.isBefore(advertLocation.timestamp);
if (shouldUseTelemetry) {
return MessageContactLocation(
location: telemetryGps,
source: 'telemetry',
capturedAt: snapshotTime,
sourceTimestamp: telemetryTimestamp,
);
}
}
if (advertLocation != null) {
return MessageContactLocation(
location: advertLocation.location,
source: 'advert',
capturedAt: snapshotTime,
sourceTimestamp: advertLocation.timestamp,
);
}
return null;
}
/// Sort contacts by last seen (most recent first)
int _sortByLastSeen(Contact a, Contact b) {
return b.lastSeenTime.compareTo(a.lastSeenTime);
@@ -470,6 +517,22 @@ class ContactsProvider with ChangeNotifier {
return _contacts[keyHex];
}
/// Clear a contact's learned path locally so the UI and next send both
/// prefer flood routing until the radio reports a fresh route.
void markPathUnhealthy(Uint8List publicKey) {
final contact = findContactByKey(publicKey);
if (contact == null || !contact.hasPath) {
return;
}
_contacts[contact.publicKeyHex] = contact.copyWith(
outPathLen: -1,
outPath: Uint8List(0),
);
_persistContacts();
notifyListeners();
}
/// Add or refresh a pending advert entry from PUSH_CODE_ADVERT (0x80).
/// Excludes self key and existing contacts.
void addPendingAdvert(Uint8List publicKey, {Uint8List? devicePublicKey}) {

View File

@@ -0,0 +1,43 @@
import 'dart:async';
/// Tracks one or more in-flight waiters for the same fragment ACK key.
///
/// Duplicate fetch requests can race and wait on the same fragment ACK at once.
/// Completing all registered waiters avoids losing the earlier completer when a
/// later request registers for the same key.
class FragmentAckWaitRegistry {
final Map<String, List<Completer<void>>> _waiters = {};
Future<bool> waitFor(
String key, {
Duration timeout = const Duration(seconds: 8),
}) async {
final completer = Completer<void>();
final waiters = _waiters.putIfAbsent(key, () => <Completer<void>>[]);
waiters.add(completer);
try {
await completer.future.timeout(timeout);
return true;
} catch (_) {
final pending = _waiters[key];
pending?.remove(completer);
if (pending != null && pending.isEmpty) {
_waiters.remove(key);
}
return false;
}
}
int complete(String key) {
final waiters = _waiters.remove(key);
if (waiters == null || waiters.isEmpty) {
return 0;
}
for (final completer in waiters) {
if (!completer.isCompleted) {
completer.complete();
}
}
return waiters.length;
}
}

View File

@@ -1,3 +1,5 @@
import 'dart:typed_data';
/// Message delivery tracking helper
///
/// Manages message delivery tracking for sent messages, including:
@@ -16,6 +18,9 @@ class MessageDeliveryTracker {
/// Messages tracked here before sending, popped when RESP_CODE_SENT arrives
final List<String> _pendingMessageIds = [];
/// Contact-scoped FIFOs for matching direct-message SENT responses.
final Map<String, List<String>> _pendingMessageIdsByContact = {};
/// Map of ACK tag to message ID for delivery confirmation
final Map<int, String> _ackTagToMessageId = {};
@@ -33,6 +38,15 @@ class MessageDeliveryTracker {
_pendingMessageIds.add(messageId);
}
/// Track a pending direct message ID for a specific contact.
void trackPendingDirectMessage(String messageId, Uint8List contactPublicKey) {
trackPendingMessage(messageId);
final contactKey = _contactKey(contactPublicKey);
_pendingMessageIdsByContact
.putIfAbsent(contactKey, () => [])
.add(messageId);
}
/// Pop the next pending message ID from FIFO queue
///
/// Called when RESP_CODE_SENT arrives. Returns null if queue empty.
@@ -43,6 +57,24 @@ class MessageDeliveryTracker {
return _pendingMessageIds.removeAt(0);
}
/// Pop the next pending direct message ID for a specific contact.
///
/// Falls back to the legacy global FIFO if the contact queue is empty.
String? popPendingDirectMessageId(Uint8List contactPublicKey) {
final contactKey = _contactKey(contactPublicKey);
final queue = _pendingMessageIdsByContact[contactKey];
if (queue == null || queue.isEmpty) {
return popPendingMessageId();
}
final messageId = queue.removeAt(0);
if (queue.isEmpty) {
_pendingMessageIdsByContact.remove(contactKey);
}
_pendingMessageIds.remove(messageId);
return messageId;
}
/// Map ACK tag to message ID after RESP_CODE_SENT received
///
/// Creates bidirectional mapping for efficient cleanup and tracking.
@@ -86,6 +118,17 @@ class MessageDeliveryTracker {
_ackTagToMessageId.remove(ackTag);
_ackTagTimestamps.remove(ackTag);
}
_pendingMessageIds.remove(messageId);
final emptyKeys = <String>[];
for (final entry in _pendingMessageIdsByContact.entries) {
entry.value.remove(messageId);
if (entry.value.isEmpty) {
emptyKeys.add(entry.key);
}
}
for (final key in emptyKeys) {
_pendingMessageIdsByContact.remove(key);
}
}
/// Clean up stale ACK mappings
@@ -114,6 +157,7 @@ class MessageDeliveryTracker {
/// Clear all tracking state
void clearTracking() {
_pendingMessageIds.clear();
_pendingMessageIdsByContact.clear();
_ackTagToMessageId.clear();
_messageIdToAckTag.clear();
_ackTagTimestamps.clear();
@@ -133,9 +177,7 @@ class MessageDeliveryTracker {
/// Get oldest pending ACK timestamp (for debugging)
DateTime? get oldestPendingTimestamp {
if (_ackTagTimestamps.isEmpty) return null;
return _ackTagTimestamps.values.reduce(
(a, b) => a.isBefore(b) ? a : b,
);
return _ackTagTimestamps.values.reduce((a, b) => a.isBefore(b) ? a : b);
}
/// Get diagnostic info for debugging
@@ -145,6 +187,15 @@ class MessageDeliveryTracker {
'shouldRateLimit': shouldRateLimit,
'oldestPending': oldestPendingTimestamp?.toIso8601String(),
'ackTags': _ackTagToMessageId.keys.toList(),
'pendingByContact': _pendingMessageIdsByContact.map(
(key, value) => MapEntry(key, value.length),
),
};
}
String _contactKey(Uint8List contactPublicKey) {
return contactPublicKey
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join();
}
}

View File

@@ -1,3 +1,6 @@
import 'dart:convert';
import 'dart:math' as math;
import '../../models/message.dart';
import '../../models/contact.dart';
@@ -17,11 +20,18 @@ class MessageRetryManager {
// Track retry state for each message ID
final Map<String, int> _retryAttempts = {};
final Map<String, DateTime> _lastRetryTimes = {};
final Map<String, int> _pathFailureStreaks = {};
// Progressive timeout values in milliseconds
// These are app-level timeouts, separate from firmware's suggested timeout
// Firmware timeout is for ACK arrival, these are for retry attempts
static const List<int> _timeouts = [4000, 8000, 12000];
static const int _defaultLoRaSf = 10;
static const int _defaultLoRaCr = 5;
static const int _defaultLoRaBwHz = 250000;
static const int _defaultLoRaPreambleSymbols = 8;
static const int _defaultLoRaCrcEnabled = 1;
static const int _defaultLoRaExplicitHeader = 1;
/// Get timeout for a specific retry attempt (0-2)
/// Returns: 4000ms for attempt 0, 8000ms for attempt 1, 12000ms for attempt 2
@@ -32,6 +42,30 @@ class MessageRetryManager {
return _timeouts[attempt];
}
/// Calculate a conservative delivery-ACK timeout when firmware doesn't
/// provide one or returns an invalid value.
int calculateAckTimeoutMs({
required String text,
required Contact? contact,
int? suggestedTimeoutMs,
}) {
if (suggestedTimeoutMs != null && suggestedTimeoutMs > 0) {
return suggestedTimeoutMs;
}
final payloadBytes = utf8.encode(text).length;
final airtimeMs = _estimateLoRaAirtimeMs(payloadBytes);
final hopCount = contact?.hasPath == true
? math.max(contact!.outPathLen, 0)
: -1;
if (hopCount < 0) {
return ((airtimeMs * 10) + 4000).clamp(10000, 30000);
}
return ((airtimeMs * (hopCount + 1) * 2) + 1500).clamp(4000, 20000);
}
/// Check if a message is eligible for retry
///
/// Returns true if:
@@ -67,8 +101,8 @@ class MessageRetryManager {
/// Contacts without paths already use flood mode automatically.
bool shouldUseFloodFallback(Message message, Contact contact) {
return message.retryAttempt >= 3 &&
contact.hasPath && // ✅ FIXED: Flood fallback for failed direct paths
!message.usedFloodFallback;
contact.hasPath && // ✅ FIXED: Flood fallback for failed direct paths
!message.usedFloodFallback;
}
/// Track a retry attempt for a message
@@ -87,6 +121,7 @@ class MessageRetryManager {
void clearAll() {
_retryAttempts.clear();
_lastRetryTimes.clear();
_pathFailureStreaks.clear();
}
/// Get current retry attempt for a message (for debugging)
@@ -98,4 +133,50 @@ class MessageRetryManager {
DateTime? getLastRetryTime(String messageId) {
return _lastRetryTimes[messageId];
}
/// Record a successful delivery for a contact and clear any accumulated
/// route failure streak for future sends.
void recordDeliverySuccess(Contact contact) {
_pathFailureStreaks.remove(contact.publicKeyHex);
}
/// Record a permanent route failure for a contact.
///
/// Returns the updated failure streak so callers can decide when to reset
/// the learned path on the radio and in local state.
int recordPathFailure(Contact contact) {
final contactKey = contact.publicKeyHex;
final next = (_pathFailureStreaks[contactKey] ?? 0) + 1;
_pathFailureStreaks[contactKey] = next;
return next;
}
int? getPathFailureStreak(Contact contact) {
return _pathFailureStreaks[contact.publicKeyHex];
}
int _estimateLoRaAirtimeMs(int payloadLenBytes) {
final sf = _defaultLoRaSf;
final bw = _defaultLoRaBwHz.toDouble();
final cr = (_defaultLoRaCr - 4).clamp(1, 4);
final ih = _defaultLoRaExplicitHeader == 1 ? 0 : 1;
final de = (sf >= 11 && _defaultLoRaBwHz <= 125000) ? 1 : 0;
final symbolMs = ((1 << sf) / bw) * 1000.0;
final preambleMs = (_defaultLoRaPreambleSymbols + 4.25) * symbolMs;
final num =
(8 * payloadLenBytes) -
(4 * sf) +
28 +
(16 * _defaultLoRaCrcEnabled) -
(20 * ih);
final den = 4 * (sf - (2 * de));
final payloadSymCoeff = den <= 0 ? 0 : (num / den).ceil();
final payloadSymbols =
8 + (payloadSymCoeff < 0 ? 0 : payloadSymCoeff) * (cr + 4);
final payloadMs = payloadSymbols * symbolMs;
return (preambleMs + payloadMs).ceil();
}
}

View File

@@ -0,0 +1,81 @@
import 'package:flutter/foundation.dart';
import '../../models/contact.dart';
typedef RawPacketSender =
Future<void> Function({
required Uint8List contactPath,
required int contactPathLen,
required Uint8List payload,
});
Future<bool> serveCachedSessionFragments<T>({
required String providerLabel,
required String sessionId,
required Contact requester,
required List<T> fragments,
required int maxDirectPayloadHops,
required int Function(T fragment) indexOf,
required Uint8List Function(T fragment) encodeBinary,
required RawPacketSender? sendRawPacket,
Set<int>? requestedIndices,
}) async {
if (fragments.isEmpty) {
debugPrint('⚠️ [$providerLabel] No cached fragments for $sessionId');
return false;
}
if (sendRawPacket == null) {
debugPrint('⚠️ [$providerLabel] sendRawPacketCallback not set');
return false;
}
if (requester.outPathLen < 0) {
debugPrint('⚠️ [$providerLabel] ${requester.advName} has no direct path');
return false;
}
if (requester.outPathLen > maxDirectPayloadHops) {
debugPrint(
'⚠️ [$providerLabel] ${requester.advName} is too far: ${requester.outPathLen} hops (max $maxDirectPayloadHops)',
);
return false;
}
if (requester.outPath.isEmpty) {
debugPrint(
'⚠️ [$providerLabel] ${requester.advName} has empty outPath payload',
);
return false;
}
var servedCount = 0;
for (final fragment in fragments) {
final index = indexOf(fragment);
if (index < 0) {
debugPrint('⚠️ [$providerLabel] Invalid fragment index $index');
continue;
}
if (requestedIndices != null && !requestedIndices.contains(index)) {
continue;
}
try {
await sendRawPacket(
contactPath: requester.outPath,
contactPathLen: requester.outPathLen,
payload: encodeBinary(fragment),
);
servedCount++;
} catch (e, st) {
debugPrint(
'❌ [$providerLabel] Serve error for $sessionId#$index: $e\n$st',
);
return false;
}
}
if (servedCount == 0) {
debugPrint(
'⚠️ [$providerLabel] No fragments matched request for $sessionId',
);
return false;
}
debugPrint('✅ [$providerLabel] Served $servedCount fragments for $sessionId');
return true;
}

View File

@@ -0,0 +1,38 @@
import '../../utils/image_message_parser.dart';
import '../../utils/voice_message_parser.dart';
class RestoredSessionMetadata {
final Map<String, String> voiceSenderKeyBySession;
final Map<String, ImageEnvelope> imageEnvelopeBySession;
const RestoredSessionMetadata({
required this.voiceSenderKeyBySession,
required this.imageEnvelopeBySession,
});
}
RestoredSessionMetadata restoreSessionMetadataFromMessages(
Iterable<String> messageTexts,
) {
final voiceSenderKeyBySession = <String, String>{};
final imageEnvelopeBySession = <String, ImageEnvelope>{};
for (final text in messageTexts) {
final voiceEnvelope = VoiceEnvelope.tryParseText(text);
if (voiceEnvelope != null) {
voiceSenderKeyBySession[voiceEnvelope.sessionId] = voiceEnvelope
.senderKey6
.toLowerCase();
}
final imageEnvelope = ImageEnvelope.tryParse(text);
if (imageEnvelope != null) {
imageEnvelopeBySession[imageEnvelope.sessionId] = imageEnvelope;
}
}
return RestoredSessionMetadata(
voiceSenderKeyBySession: voiceSenderKeyBySession,
imageEnvelopeBySession: imageEnvelopeBySession,
);
}

View File

@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/contact.dart';
import 'helpers/raw_session_retransmit.dart';
import '../utils/image_message_parser.dart';
/// Reassembly state for one incoming image session.
@@ -13,6 +14,8 @@ class ImageSession {
final int width;
final int height;
final List<ImagePacket?> fragments; // indexed by fragment.index
DateTime? firstFragmentAt;
DateTime? lastFragmentAt;
ImageSession({
required this.sessionId,
@@ -25,6 +28,21 @@ class ImageSession {
int get receivedCount => fragments.where((f) => f != null).length;
bool get isComplete => receivedCount == total;
Duration? estimateRemaining() {
if (isComplete) return Duration.zero;
if (firstFragmentAt == null || lastFragmentAt == null) return null;
if (receivedCount < 2) return null;
final elapsedMs = lastFragmentAt!
.difference(firstFragmentAt!)
.inMilliseconds;
if (elapsedMs <= 0) return null;
final avgMsPerFragment = elapsedMs / (receivedCount - 1);
final remaining = total - receivedCount;
if (remaining <= 0) return Duration.zero;
return Duration(milliseconds: (avgMsPerFragment * remaining).round());
}
/// Reassemble the complete image bytes, or null if any fragment is missing.
Uint8List? get imageBytes => reassembleImage(fragments);
}
@@ -36,9 +54,11 @@ class ImageSession {
class ImageProvider with ChangeNotifier {
static const String _storageKey = 'stored_image_sessions_v1';
static const Duration _outgoingTtl = Duration(minutes: 15);
static const int maxDirectPayloadHops = 3;
/// Incoming sessions keyed by sessionId.
final Map<String, ImageSession> _sessions = {};
final Set<String> _ignoredIncomingSessions = {};
/// Outgoing sessions cached for deferred serving.
final Map<String, _OutgoingSession> _outgoing = {};
@@ -61,6 +81,10 @@ class ImageProvider with ChangeNotifier {
bool isComplete(String sessionId) =>
_sessions[sessionId]?.isComplete ?? false;
bool hasOutgoing(String sessionId) => _outgoing.containsKey(sessionId);
Duration? estimateRemainingTransferTime(String sessionId) =>
_sessions[sessionId]?.estimateRemaining();
bool isReceiveCanceled(String sessionId) =>
_ignoredIncomingSessions.contains(sessionId);
List<int> missingFragmentIndices(String sessionId) {
final session = _sessions[sessionId];
@@ -80,6 +104,12 @@ class ImageProvider with ChangeNotifier {
///
/// Returns true when the session just became complete.
bool addFragment(ImagePacket fragment, {int width = 0, int height = 0}) {
if (_ignoredIncomingSessions.contains(fragment.sessionId)) {
debugPrint(
'⏹️ [ImageProvider] Ignoring canceled incoming session ${fragment.sessionId}',
);
return false;
}
_sessions.putIfAbsent(
fragment.sessionId,
() => ImageSession(
@@ -93,7 +123,13 @@ class ImageProvider with ChangeNotifier {
final session = _sessions[fragment.sessionId]!;
if (fragment.index < session.total) {
final wasMissing = session.fragments[fragment.index] == null;
session.fragments[fragment.index] = fragment;
if (wasMissing) {
final now = DateTime.now();
session.firstFragmentAt ??= now;
session.lastFragmentAt = now;
}
}
final justComplete = session.isComplete;
@@ -102,22 +138,27 @@ class ImageProvider with ChangeNotifier {
return justComplete;
}
void cancelIncomingSession(String sessionId) {
_ignoredIncomingSessions.add(sessionId);
_sessions.remove(sessionId);
unawaited(_persist());
notifyListeners();
}
void resumeIncomingSession(String sessionId) {
if (_ignoredIncomingSessions.remove(sessionId)) {
notifyListeners();
}
}
/// Register envelope metadata for a session (called when IE1 is received
/// before any binary fragments arrive).
void registerEnvelope(ImageEnvelope envelope) {
_sessions.putIfAbsent(
envelope.sessionId,
() => ImageSession(
sessionId: envelope.sessionId,
format: envelope.format,
total: envelope.total,
width: envelope.width,
height: envelope.height,
),
);
// Update dimensions if we created the session from a fragment (w/h = 0).
final session = _sessions[envelope.sessionId]!;
if (session.width == 0 || session.height == 0) {
if (_ignoredIncomingSessions.contains(envelope.sessionId)) {
return;
}
final existing = _sessions[envelope.sessionId];
if (existing == null) {
_sessions[envelope.sessionId] = ImageSession(
sessionId: envelope.sessionId,
format: envelope.format,
@@ -125,12 +166,38 @@ class ImageProvider with ChangeNotifier {
width: envelope.width,
height: envelope.height,
);
// Copy existing fragments into the new session.
final old = _sessions[envelope.sessionId]!;
for (var i = 0; i < session.fragments.length && i < old.total; i++) {
old.fragments[i] = session.fragments[i];
unawaited(_persist());
notifyListeners();
return;
}
final needsMerge =
existing.width == 0 ||
existing.height == 0 ||
existing.total != envelope.total ||
existing.format != envelope.format;
if (!needsMerge) {
notifyListeners();
return;
}
final merged = ImageSession(
sessionId: envelope.sessionId,
format: envelope.format,
total: envelope.total,
width: envelope.width,
height: envelope.height,
);
merged.firstFragmentAt = existing.firstFragmentAt;
merged.lastFragmentAt = existing.lastFragmentAt;
for (final fragment in existing.fragments) {
if (fragment == null) continue;
if (fragment.index < merged.total) {
merged.fragments[fragment.index] = fragment;
}
}
_sessions[envelope.sessionId] = merged;
unawaited(_persist());
notifyListeners();
}
@@ -182,35 +249,17 @@ class ImageProvider with ChangeNotifier {
debugPrint('⚠️ [ImageProvider] No cached session for $sessionId');
return false;
}
if (sendRawPacketCallback == null) {
debugPrint('⚠️ [ImageProvider] sendRawPacketCallback not set');
return false;
}
if (requester.outPathLen < 0) {
debugPrint('⚠️ [ImageProvider] ${requester.advName} has no direct path');
return false;
}
for (final fragment in cached.fragments) {
if (requestedIndices != null &&
!requestedIndices.contains(fragment.index)) {
continue;
}
try {
await sendRawPacketCallback!(
contactPath: requester.outPath,
contactPathLen: requester.outPathLen,
payload: fragment.encodeBinary(),
);
} catch (e, st) {
debugPrint('❌ [ImageProvider] Serve error for $sessionId: $e\n$st');
return false;
}
}
debugPrint(
'📷 [ImageProvider] Served ${cached.fragments.length} fragments of $sessionId',
return serveCachedSessionFragments<ImagePacket>(
providerLabel: 'ImageProvider',
sessionId: sessionId,
requester: requester,
fragments: cached.fragments,
maxDirectPayloadHops: maxDirectPayloadHops,
indexOf: (fragment) => fragment.index,
encodeBinary: (fragment) => fragment.encodeBinary(),
sendRawPacket: sendRawPacketCallback,
requestedIndices: requestedIndices,
);
return true;
}
// ── Persistence ──────────────────────────────────────────────────────────
@@ -218,6 +267,7 @@ class ImageProvider with ChangeNotifier {
Future<void> clearAll() async {
_sessions.clear();
_outgoing.clear();
_ignoredIncomingSessions.clear();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();

View File

@@ -2,6 +2,8 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/message.dart';
import '../models/contact.dart';
import '../models/message_contact_location.dart';
import '../models/message_reception_details.dart';
import '../models/sar_marker.dart';
import '../models/map_drawing.dart';
import '../services/message_storage_service.dart';
@@ -20,6 +22,8 @@ class MessagesProvider with ChangeNotifier {
final NotificationService _notificationService = NotificationService();
bool _isInitialized = false;
AppLocalizations? _localizations;
final Map<String, MessageContactLocation> _messageContactLocations = {};
final Map<String, MessageReceptionDetails> _messageReceptionDetails = {};
// Track pending sent messages by expected ACK/TAG
final Map<int, Message> _pendingSentMessages = {};
@@ -28,6 +32,13 @@ class MessagesProvider with ChangeNotifier {
// Key: message ID (not ACK tag, since multiple messages can share same ACK)
final Map<String, Timer> _timeoutTimers = {};
// Recently completed ACKs are kept briefly to ignore duplicate confirms.
final Map<int, DateTime> _completedAckHistory = {};
// Preserve ACK tags assigned to a message across retries.
final Map<String, Set<int>> _messageAckHistory = {};
final Map<int, (String, DateTime)> _ackHistoryLookup = {};
// Retry management
final MessageRetryManager _retryManager = MessageRetryManager();
@@ -65,6 +76,9 @@ class MessagesProvider with ChangeNotifier {
})?
sendMessageCallback;
Future<void> Function({required Contact contact, required int failureStreak})?
onDirectPathFailedCallback;
List<Message> get messages => List.unmodifiable(_messages);
List<Message> get contactMessages =>
@@ -97,6 +111,12 @@ class MessagesProvider with ChangeNotifier {
String? get targetMessageId => _targetMessageId;
MessageContactLocation? getMessageContactLocation(String messageId) =>
_messageContactLocations[messageId];
MessageReceptionDetails? getMessageReceptionDetails(String messageId) =>
_messageReceptionDetails[messageId];
/// Set localizations for notifications
void setLocalizations(AppLocalizations localizations) {
_localizations = localizations;
@@ -125,6 +145,16 @@ class MessagesProvider with ChangeNotifier {
try {
debugPrint('📦 [MessagesProvider] Loading persisted messages...');
final storedMessages = await _storageService.loadMessages();
final storedContactLocations = await _storageService
.loadMessageContactLocations();
final storedReceptionDetails = await _storageService
.loadMessageReceptionDetails();
_messageContactLocations
..clear()
..addAll(storedContactLocations);
_messageReceptionDetails
..clear()
..addAll(storedReceptionDetails);
// Add stored messages with enhancement to ensure SAR detection
for (final message in storedMessages) {
@@ -287,6 +317,8 @@ class MessagesProvider with ChangeNotifier {
void addMessage(
Message message, {
String Function(String name)? contactLookup,
MessageContactLocation? contactLocationSnapshot,
MessageReceptionDetails? receptionDetailsSnapshot,
}) {
// Always enhance message with SAR parser to detect SAR markers
var enhancedMessage = SarMessageParser.enhanceMessage(message);
@@ -373,10 +405,32 @@ class MessagesProvider with ChangeNotifier {
debugPrint(
' Text: ${finalMessage.text.substring(0, finalMessage.text.length > 50 ? 50 : finalMessage.text.length)}...',
);
final existingIndex = _messages.indexWhere(
(existing) =>
existing.messageType == finalMessage.messageType &&
existing.senderTimestamp == finalMessage.senderTimestamp &&
existing.text == finalMessage.text,
);
if (existingIndex != -1) {
final existingId = _messages[existingIndex].id;
if (contactLocationSnapshot != null) {
_messageContactLocations[existingId] = contactLocationSnapshot;
}
if (receptionDetailsSnapshot != null) {
_messageReceptionDetails[existingId] = receptionDetailsSnapshot;
}
_persistMessages();
}
return; // Skip duplicate
}
_messages.add(finalMessage);
if (contactLocationSnapshot != null) {
_messageContactLocations[finalMessage.id] = contactLocationSnapshot;
}
if (receptionDetailsSnapshot != null) {
_messageReceptionDetails[finalMessage.id] = receptionDetailsSnapshot;
}
// If it's a SAR marker message, extract and store the marker
if (finalMessage.isSarMarker) {
@@ -563,7 +617,11 @@ class MessagesProvider with ChangeNotifier {
/// Persist messages to storage (async, non-blocking)
Future<void> _persistMessages() async {
try {
await _storageService.saveMessages(_messages);
await _storageService.saveMessages(
_messages,
messageContactLocations: _messageContactLocations,
messageReceptionDetails: _messageReceptionDetails,
);
} catch (e) {
debugPrint('❌ [MessagesProvider] Error persisting messages: $e');
}
@@ -678,6 +736,8 @@ class MessagesProvider with ChangeNotifier {
}
_messageContactMap.remove(messageId);
_groupedMessageMapping.remove(messageId);
_messageContactLocations.remove(messageId);
_messageReceptionDetails.remove(messageId);
debugPrint('🗑️ [MessagesProvider] Message $messageId deleted');
@@ -706,6 +766,8 @@ class MessagesProvider with ChangeNotifier {
void clearMessages() {
_messages.clear();
_sarMarkers.clear();
_messageContactLocations.clear();
_messageReceptionDetails.clear();
_persistMessages();
notifyListeners();
}
@@ -720,6 +782,8 @@ class MessagesProvider with ChangeNotifier {
void clearAll() {
_messages.clear();
_sarMarkers.clear();
_messageContactLocations.clear();
_messageReceptionDetails.clear();
_persistMessages();
notifyListeners();
}
@@ -906,11 +970,13 @@ class MessagesProvider with ChangeNotifier {
final (groupId, recipientPublicKey) = groupMapping;
debugPrint(' ✅ This is part of a grouped message: $groupId');
// Update the recipient status to "sent" in the grouped message
// ACK-tracked recipients stay pending until the delivery confirm arrives.
updateGroupedMessageRecipientStatus(
groupId,
recipientPublicKey,
MessageDeliveryStatus.sent,
expectedAckTag > 0
? MessageDeliveryStatus.sending
: MessageDeliveryStatus.sent,
);
// Track the ACK for this specific recipient
@@ -1015,23 +1081,36 @@ class MessagesProvider with ChangeNotifier {
if (index != -1) {
final message = _messages[index];
final contact = _messageContactMap[messageId];
final effectiveTimeout = _retryManager.calculateAckTimeoutMs(
text: message.text,
contact: contact,
suggestedTimeoutMs: suggestedTimeoutMs > 0 ? suggestedTimeoutMs : null,
);
debugPrint(' Current status: ${message.deliveryStatus}');
debugPrint(' Message type: ${message.messageType}');
debugPrint(
' Message text preview: ${message.text.substring(0, message.text.length > 30 ? 30 : message.text.length)}...',
);
// Once the device accepts a direct message and returns an ACK tag, the
// send itself succeeded locally even if end-to-end delivery confirmation
// may still arrive later. Keep ACK tracking, but stop showing "waiting".
final updatedMessage = message.copyWith(
deliveryStatus: MessageDeliveryStatus.sent,
expectedAckTag: expectedAckTag > 0 ? expectedAckTag : null,
suggestedTimeoutMs: suggestedTimeoutMs > 0 ? suggestedTimeoutMs : null,
suggestedTimeoutMs: expectedAckTag > 0 ? effectiveTimeout : null,
);
_messages[index] = updatedMessage;
// Only track and set timeout for direct messages (channel messages have expectedAckTag=0)
if (expectedAckTag > 0 && suggestedTimeoutMs > 0) {
if (expectedAckTag > 0) {
// Track by ACK tag for matching with delivery confirmation
_pendingSentMessages[expectedAckTag] = updatedMessage;
_messageAckHistory
.putIfAbsent(messageId, () => <int>{})
.add(expectedAckTag);
_ackHistoryLookup[expectedAckTag] = (messageId, DateTime.now());
debugPrint(
' ✅ Added to pending messages map with ACK: $expectedAckTag',
);
@@ -1042,7 +1121,7 @@ class MessagesProvider with ChangeNotifier {
// Start timeout timer using message ID as key
_timeoutTimers[messageId] = Timer(
Duration(milliseconds: suggestedTimeoutMs),
Duration(milliseconds: effectiveTimeout),
() {
debugPrint(
'⏱️ [MessagesProvider] Timeout for message $messageId (ACK $expectedAckTag)',
@@ -1054,7 +1133,7 @@ class MessagesProvider with ChangeNotifier {
);
debugPrint(
'⏱️ [MessagesProvider] Started ${suggestedTimeoutMs}ms timeout timer for message $messageId (ACK $expectedAckTag)',
'⏱️ [MessagesProvider] Started ${effectiveTimeout}ms timeout timer for message $messageId (ACK $expectedAckTag)',
);
} else {
debugPrint(
@@ -1245,6 +1324,8 @@ class MessagesProvider with ChangeNotifier {
/// Update message status to delivered with RTT
void markMessageDelivered(int ackCode, int roundTripTimeMs) {
_cleanupCompletedAckHistory();
_cleanupAckHistoryLookup();
debugPrint(
'🔍 [MessagesProvider] markMessageDelivered called with ACK: $ackCode, RTT: ${roundTripTimeMs}ms',
);
@@ -1296,6 +1377,7 @@ class MessagesProvider with ChangeNotifier {
);
_ackTagToRecipients.remove(ackCode);
_pendingSentMessages.remove(ackCode);
_rememberCompletedAck(ackCode);
}
debugPrint(
@@ -1339,9 +1421,15 @@ class MessagesProvider with ChangeNotifier {
// Remove from pending
_pendingSentMessages.remove(ackCode);
_rememberCompletedAck(ackCode);
_clearAckHistoryForMessage(message.id);
// Clear retry tracking on successful delivery
_retryManager.clearRetry(message.id);
final deliveredContact = _messageContactMap[message.id];
if (deliveredContact != null) {
_retryManager.recordDeliverySuccess(deliveredContact);
}
debugPrint(
'✅ [MessagesProvider] Message ${message.id} delivered in ${roundTripTimeMs}ms (ACK $ackCode)',
@@ -1362,6 +1450,43 @@ class MessagesProvider with ChangeNotifier {
);
}
} else {
final historicalMatch = _ackHistoryLookup[ackCode];
if (historicalMatch != null) {
final historicalMessageId = historicalMatch.$1;
final historicalIndex = _messages.indexWhere(
(m) => m.id == historicalMessageId,
);
if (historicalIndex != -1 &&
_messages[historicalIndex].deliveryStatus !=
MessageDeliveryStatus.delivered) {
_messages[historicalIndex] = _messages[historicalIndex].copyWith(
deliveryStatus: MessageDeliveryStatus.delivered,
roundTripTimeMs: roundTripTimeMs,
deliveredAt: DateTime.now(),
);
_timeoutTimers[historicalMessageId]?.cancel();
_timeoutTimers.remove(historicalMessageId);
_rememberCompletedAck(ackCode);
_clearAckHistoryForMessage(historicalMessageId);
_retryManager.clearRetry(historicalMessageId);
final deliveredContact = _messageContactMap[historicalMessageId];
if (deliveredContact != null) {
_retryManager.recordDeliverySuccess(deliveredContact);
}
_persistMessages();
notifyListeners();
debugPrint(
'✅ [MessagesProvider] Historical ACK $ackCode matched message $historicalMessageId',
);
return;
}
}
if (_completedAckHistory.containsKey(ackCode)) {
debugPrint(
' [MessagesProvider] Duplicate/late ACK $ackCode ignored (already completed)',
);
return;
}
debugPrint(
'⚠️ [MessagesProvider] No pending message found for ACK code: $ackCode',
);
@@ -1482,18 +1607,31 @@ class MessagesProvider with ChangeNotifier {
debugPrint(
'⏰ [MessagesProvider] Executing retry $nextAttempt for message $messageId',
);
final currentIndex = _messages.indexWhere((m) => m.id == messageId);
if (currentIndex == -1) {
return;
}
final currentMessage = _messages[currentIndex];
if (currentMessage.deliveryStatus == MessageDeliveryStatus.delivered) {
return;
}
if (sendMessageCallback != null) {
await sendMessageCallback!(
final queued = await sendMessageCallback!(
contactPublicKey: contact.publicKey,
text: message.text,
messageId: messageId,
contact: contact,
retryAttempt: nextAttempt,
);
if (!queued) {
_markAsPermanentlyFailed(messageId, currentMessage);
}
} else {
debugPrint(
'⚠️ [MessagesProvider] sendMessageCallback not set, cannot retry',
);
_markAsPermanentlyFailed(messageId, currentMessage);
}
});
@@ -1529,17 +1667,21 @@ class MessagesProvider with ChangeNotifier {
// Send with flood mode (no retry after this)
if (sendMessageCallback != null) {
await sendMessageCallback!(
final queued = await sendMessageCallback!(
contactPublicKey: contact.publicKey,
text: message.text,
messageId: messageId,
contact: contact,
retryAttempt: 0, // Reset attempt for flood
);
if (!queued) {
_markAsPermanentlyFailed(messageId, _messages[index]);
}
} else {
debugPrint(
'⚠️ [MessagesProvider] sendMessageCallback not set, cannot send flood',
);
_markAsPermanentlyFailed(messageId, _messages[index]);
}
_persistMessages();
@@ -1562,10 +1704,27 @@ class MessagesProvider with ChangeNotifier {
if (message.expectedAckTag != null) {
_pendingSentMessages.remove(message.expectedAckTag);
}
_clearAckHistoryForMessage(messageId);
// Clear retry tracking
_retryManager.clearRetry(messageId);
final failedContact = _messageContactMap[messageId];
if (failedContact != null && failedContact.hasPath) {
final failureStreak = _retryManager.recordPathFailure(failedContact);
debugPrint(
' Path failure streak for ${failedContact.advName}: $failureStreak',
);
if (failureStreak >= 2 && onDirectPathFailedCallback != null) {
unawaited(
onDirectPathFailedCallback!(
contact: failedContact,
failureStreak: failureStreak,
),
);
}
}
_persistMessages();
notifyListeners();
}
@@ -1608,17 +1767,21 @@ class MessagesProvider with ChangeNotifier {
// Send again
if (sendMessageCallback != null) {
await sendMessageCallback!(
final queued = await sendMessageCallback!(
contactPublicKey: contact.publicKey,
text: message.text,
messageId: messageId,
contact: contact,
retryAttempt: 0,
);
if (!queued) {
_markAsPermanentlyFailed(messageId, _messages[index]);
}
} else {
debugPrint(
'⚠️ [MessagesProvider] sendMessageCallback not set, cannot resend',
);
_markAsPermanentlyFailed(messageId, _messages[index]);
}
_persistMessages();
@@ -1631,10 +1794,62 @@ class MessagesProvider with ChangeNotifier {
timer.cancel();
}
_timeoutTimers.clear();
_completedAckHistory.clear();
_messageAckHistory.clear();
_ackHistoryLookup.clear();
// Clear retry manager
_retryManager.clearAll();
super.dispose();
}
void _rememberCompletedAck(int ackCode) {
_completedAckHistory[ackCode] = DateTime.now();
_cleanupCompletedAckHistory();
}
void _cleanupCompletedAckHistory({
Duration maxAge = const Duration(minutes: 15),
}) {
final cutoff = DateTime.now().subtract(maxAge);
final staleAcks = _completedAckHistory.entries
.where((entry) => entry.value.isBefore(cutoff))
.map((entry) => entry.key)
.toList();
for (final ack in staleAcks) {
_completedAckHistory.remove(ack);
}
}
void _clearAckHistoryForMessage(String messageId) {
final ackTags = _messageAckHistory.remove(messageId);
if (ackTags == null) {
return;
}
for (final ack in ackTags) {
_ackHistoryLookup.remove(ack);
}
}
void _cleanupAckHistoryLookup({
Duration maxAge = const Duration(minutes: 15),
}) {
final cutoff = DateTime.now().subtract(maxAge);
final staleAcks = _ackHistoryLookup.entries
.where((entry) => entry.value.$2.isBefore(cutoff))
.map((entry) => entry.key)
.toList();
for (final ack in staleAcks) {
final messageId = _ackHistoryLookup.remove(ack)?.$1;
if (messageId == null) {
continue;
}
final history = _messageAckHistory[messageId];
history?.remove(ack);
if (history != null && history.isEmpty) {
_messageAckHistory.remove(messageId);
}
}
}
}

View File

@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/contact.dart';
import 'helpers/raw_session_retransmit.dart';
import '../utils/voice_message_parser.dart';
import '../services/voice_codec_service.dart';
import '../services/voice_player_service.dart';
@@ -13,6 +14,8 @@ class VoiceSession {
final VoicePacketMode mode;
final int total;
final List<VoicePacket?> packets; // indexed by packet.index
DateTime? firstPacketAt;
DateTime? lastPacketAt;
VoiceSession({
required this.sessionId,
@@ -23,6 +26,19 @@ class VoiceSession {
int get receivedCount => packets.where((p) => p != null).length;
bool get isComplete => receivedCount == total;
Duration? estimateRemaining() {
if (isComplete) return Duration.zero;
if (firstPacketAt == null || lastPacketAt == null) return null;
if (receivedCount < 2) return null;
final elapsedMs = lastPacketAt!.difference(firstPacketAt!).inMilliseconds;
if (elapsedMs <= 0) return null;
final avgMsPerPacket = elapsedMs / (receivedCount - 1);
final remaining = total - receivedCount;
if (remaining <= 0) return Duration.zero;
return Duration(milliseconds: (avgMsPerPacket * remaining).round());
}
/// Total estimated audio duration in seconds (sum of all received packets).
double get estimatedDurationSeconds {
var ms = 0;
@@ -36,12 +52,14 @@ class VoiceSession {
/// Manages incoming voice packet sessions and coordinates playback.
class VoiceProvider with ChangeNotifier {
static const String _voiceSessionsStorageKey = 'stored_voice_sessions_v1';
static const int maxDirectPayloadHops = 3;
final VoiceCodecService _codec;
final VoicePlayerService _player;
late final StreamSubscription<void> _playerEventsSub;
/// Active sessions keyed by sessionId.
final Map<String, VoiceSession> _sessions = {};
final Set<String> _ignoredIncomingSessions = {};
/// Currently playing session ID, or null.
String? _playingSessionId;
@@ -92,6 +110,10 @@ class VoiceProvider with ChangeNotifier {
bool hasOutgoingSession(String sessionId) =>
_outgoingSessions.containsKey(sessionId);
Duration? estimateRemainingTransferTime(String sessionId) =>
_sessions[sessionId]?.estimateRemaining();
bool isReceiveCanceled(String sessionId) =>
_ignoredIncomingSessions.contains(sessionId);
List<int> missingPacketIndices(String sessionId) {
final session = _sessions[sessionId];
@@ -108,6 +130,12 @@ class VoiceProvider with ChangeNotifier {
/// Add an incoming [packet] to its session. Creates the session on first packet.
/// Returns true if the session just became complete.
bool addPacket(VoicePacket packet) {
if (_ignoredIncomingSessions.contains(packet.sessionId)) {
debugPrint(
'⏹️ [VoiceProvider] Ignoring canceled incoming session ${packet.sessionId}',
);
return false;
}
_sessions.putIfAbsent(
packet.sessionId,
() => VoiceSession(
@@ -119,7 +147,13 @@ class VoiceProvider with ChangeNotifier {
final session = _sessions[packet.sessionId]!;
if (packet.index < session.total) {
final wasMissing = session.packets[packet.index] == null;
session.packets[packet.index] = packet;
if (wasMissing) {
final now = DateTime.now();
session.firstPacketAt ??= now;
session.lastPacketAt = now;
}
}
final justComplete = session.isComplete;
@@ -128,6 +162,23 @@ class VoiceProvider with ChangeNotifier {
return justComplete;
}
void cancelIncomingSession(String sessionId) {
_ignoredIncomingSessions.add(sessionId);
_sessions.remove(sessionId);
if (_playingSessionId == sessionId) {
unawaited(_player.stop());
_playingSessionId = null;
}
_persistVoiceData();
notifyListeners();
}
void resumeIncomingSession(String sessionId) {
if (_ignoredIncomingSessions.remove(sessionId)) {
notifyListeners();
}
}
/// Cache encoded packets for deferred voice serving.
void cacheOutgoingSession(String sessionId, List<VoicePacket> packets) {
if (packets.isEmpty) return;
@@ -151,36 +202,17 @@ class VoiceProvider with ChangeNotifier {
);
return false;
}
if (sendRawPacketCallback == null) {
debugPrint('⚠️ [VoiceProvider] sendRawPacketCallback is not set');
return false;
}
if (requester.outPathLen < 0) {
debugPrint(
'⚠️ [VoiceProvider] Requester ${requester.advName} has no direct path',
);
return false;
}
for (final packet in cached.packets) {
if (requestedIndices != null &&
!requestedIndices.contains(packet.index)) {
continue;
}
try {
await sendRawPacketCallback!(
contactPath: requester.outPath,
contactPathLen: requester.outPathLen,
payload: packet.encodeBinary(),
);
} catch (e, st) {
debugPrint(
'❌ [VoiceProvider] Failed serving packet for $sessionId: $e\n$st',
);
return false;
}
}
return true;
return serveCachedSessionFragments<VoicePacket>(
providerLabel: 'VoiceProvider',
sessionId: sessionId,
requester: requester,
fragments: cached.packets,
maxDirectPayloadHops: maxDirectPayloadHops,
indexOf: (packet) => packet.index,
encodeBinary: (packet) => packet.encodeBinary(),
sendRawPacket: sendRawPacketCallback,
requestedIndices: requestedIndices,
);
}
// ── Playback ─────────────────────────────────────────────────────────────
@@ -224,6 +256,7 @@ class VoiceProvider with ChangeNotifier {
Future<void> clearStoredVoiceData() async {
_sessions.clear();
_outgoingSessions.clear();
_ignoredIncomingSessions.clear();
_playingSessionId = null;
notifyListeners();
try {

View File

@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';
import '../providers/connection_provider.dart';
import '../services/validation_service.dart';
import '../l10n/app_localizations.dart';
@@ -722,7 +722,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Client Repeat Mode'),
subtitle: deviceInfo.allowedRepeatFreqRanges != null &&
subtitle:
deviceInfo.allowedRepeatFreqRanges != null &&
deviceInfo.allowedRepeatFreqRanges!.isNotEmpty
? Text(
'Allowed: ${deviceInfo.allowedRepeatFreqRanges!.map((r) => r.lower == r.upper ? '${(r.lower / 1000).toStringAsFixed(3)} MHz' : '${(r.lower / 1000).toStringAsFixed(3)}${(r.upper / 1000).toStringAsFixed(3)} MHz').join(', ')}',

View File

@@ -6,6 +6,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';
import '../providers/connection_provider.dart';
import '../providers/app_provider.dart';
import '../models/device_info.dart' show ConnectionMode;
import '../providers/messages_provider.dart';
import '../providers/contacts_provider.dart';
import '../theme/app_theme.dart';
@@ -16,12 +17,15 @@ import 'map_management_screen.dart';
import 'settings_screen.dart';
import 'device_config_screen.dart';
import 'packet_log_screen.dart';
import 'spectrum_scan_screen.dart';
import '../utils/toast_logger.dart';
import '../l10n/app_localizations.dart';
import '../widgets/permission_request_dialog.dart';
import '../widgets/connection_dialog.dart';
import '../utils/battery_display_helper.dart';
enum _HomeTab { messages, contacts, map }
class HomeScreen extends StatefulWidget {
final Function(AppThemeMode) onThemeChanged;
final Function(Locale?) onLocaleChanged;
@@ -42,20 +46,41 @@ class HomeScreen extends StatefulWidget {
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen>
with SingleTickerProviderStateMixin {
class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
late TabController _tabController;
late final AppProvider _appProvider;
int _currentIndex = 0;
bool _isMapFullscreen = false;
bool _showRxTxIndicators = true;
bool _isMapEnabled = true;
bool _isContactsEnabled = true;
List<_HomeTab> get _enabledTabs {
return [
_HomeTab.messages,
if (_isContactsEnabled) _HomeTab.contacts,
if (_isMapEnabled) _HomeTab.map,
];
}
_HomeTab get _currentTab {
final tabs = _enabledTabs;
final safeIndex = _currentIndex < tabs.length
? _currentIndex
: tabs.length - 1;
return tabs[safeIndex < 0 ? 0 : safeIndex];
}
@override
void initState() {
super.initState();
_appProvider = context.read<AppProvider>();
_isMapEnabled = _appProvider.isMapEnabled;
_isContactsEnabled = _appProvider.isContactsEnabled;
_appProvider.addListener(_handleAppProviderChanged);
// Initialize synchronously so first build always has a valid controller.
_initTabController();
_loadMapEnabledAndInitTabs();
_loadRxTxPreference();
// Show permission dialog after the first frame if needed
@@ -66,58 +91,102 @@ class _HomeScreenState extends State<HomeScreen>
}
}
Future<void> _loadMapEnabledAndInitTabs() async {
final prefs = await SharedPreferences.getInstance();
final mapEnabled = prefs.getBool('map_enabled') ?? true;
if (!mounted) return;
if (_isMapEnabled != mapEnabled) {
_updateTabController(mapEnabled);
}
}
void _initTabController() {
final tabCount = _isMapEnabled ? 3 : 2;
_tabController = TabController(length: tabCount, vsync: this);
_tabController = TabController(length: _enabledTabs.length, vsync: this);
_tabController.addListener(_onTabChanged);
}
void _onTabChanged() {
setState(() {
_currentIndex = _tabController.index;
// Exit fullscreen when switching away from map tab (only if map is enabled and is tab 2)
if (_isMapEnabled && _currentIndex != 2) {
_isMapFullscreen = false;
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_handleTabActivated(_currentTab);
});
}
void _updateTabController(bool mapEnabled) {
if (_isMapEnabled == mapEnabled) return;
void _handleAppProviderChanged() {
if (!mounted) return;
_updateTabController(
mapEnabled: _appProvider.isMapEnabled,
contactsEnabled: _appProvider.isContactsEnabled,
);
}
// Save current index before rebuilding
final oldIndex = _tabController.index;
void _onTabChanged() {
final previousTab = _currentTab;
final nextIndex = _tabController.index;
// Remove old listener and dispose
_tabController.removeListener(_onTabChanged);
_tabController.dispose();
setState(() {
_currentIndex = nextIndex;
if (_currentTab != _HomeTab.map) {
_isMapFullscreen = false;
}
});
final nextTab = _currentTab;
if (previousTab != nextTab) {
_handleTabActivated(nextTab);
}
}
void _updateTabController({
required bool mapEnabled,
required bool contactsEnabled,
}) {
if (_isMapEnabled == mapEnabled && _isContactsEnabled == contactsEnabled) {
return;
}
final oldTabs = _enabledTabs;
final oldIndex = oldTabs.isEmpty
? 0
: _tabController.index.clamp(0, oldTabs.length - 1);
final oldTab = oldTabs[oldIndex];
final oldController = _tabController;
oldController.removeListener(_onTabChanged);
oldController.dispose();
// Update state
_isMapEnabled = mapEnabled;
// Create new controller
final tabCount = mapEnabled ? 3 : 2;
_tabController = TabController(length: tabCount, vsync: this);
_tabController.addListener(_onTabChanged);
// Restore index (clamp to valid range)
if (oldIndex < tabCount) {
_tabController.index = oldIndex;
_currentIndex = oldIndex;
} else {
_currentIndex = tabCount - 1;
_isContactsEnabled = contactsEnabled;
if (!_isMapEnabled) {
_isMapFullscreen = false;
}
final newTabs = _enabledTabs;
final newIndex = newTabs.indexOf(oldTab);
// Create new controller
_tabController = TabController(length: newTabs.length, vsync: this);
_tabController.addListener(_onTabChanged);
_currentIndex = newIndex >= 0 ? newIndex : 0;
_tabController.index = _currentIndex;
setState(() {});
_handleTabActivated(_currentTab);
}
void _navigateToTab(_HomeTab tab) {
final targetIndex = _enabledTabs.indexOf(tab);
if (targetIndex >= 0 && targetIndex != _tabController.index) {
_tabController.animateTo(targetIndex);
}
}
void _handleTabActivated(_HomeTab tab) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
switch (tab) {
case _HomeTab.messages:
context.read<MessagesProvider>().markAllAsRead();
break;
case _HomeTab.contacts:
context.read<ContactsProvider>().markAllAsViewed();
break;
case _HomeTab.map:
break;
}
});
}
Future<void> _loadRxTxPreference() async {
@@ -131,6 +200,7 @@ class _HomeScreenState extends State<HomeScreen>
@override
void dispose() {
_appProvider.removeListener(_handleAppProviderChanged);
_tabController.removeListener(_onTabChanged);
_tabController.dispose();
super.dispose();
@@ -275,18 +345,12 @@ class _HomeScreenState extends State<HomeScreen>
messagesProvider.setLocalizations(localizations);
}
// Check if map enabled setting changed and update tab controller
final appProvider = context.watch<AppProvider>();
if (_isMapEnabled != appProvider.isMapEnabled) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_updateTabController(appProvider.isMapEnabled);
});
}
context.watch<AppProvider>();
// Determine if we should hide the UI (only in fullscreen on map tab)
final shouldHideUI =
_isMapEnabled && _isMapFullscreen && _currentIndex == 2;
final enabledTabs = _enabledTabs;
final isMapTabActive = _currentTab == _HomeTab.map;
final shouldHideUI = _isMapEnabled && _isMapFullscreen && isMapTabActive;
final shouldShowTabBar = enabledTabs.length > 1;
return Scaffold(
appBar: shouldHideUI
@@ -298,7 +362,7 @@ class _HomeScreenState extends State<HomeScreen>
builder: (context, provider, child) {
final isConnected =
provider.deviceInfo.isConnected ||
provider.isSseClientConnected;
provider.deviceInfo.isConnected;
if (isConnected) {
return IconButton(
onPressed: () async {
@@ -339,6 +403,26 @@ class _HomeScreenState extends State<HomeScreen>
});
},
),
PopupMenuItem(
child: Row(
children: [
const Icon(Icons.radar),
const SizedBox(width: 8),
const Text('Spectrum Scan'),
],
),
onTap: () {
final navigator = Navigator.of(context);
Future.delayed(Duration.zero, () {
if (!mounted) return;
navigator.push(
MaterialPageRoute(
builder: (context) => const SpectrumScanScreen(),
),
);
});
},
),
PopupMenuItem(
child: Row(
children: [
@@ -373,29 +457,33 @@ class _HomeScreenState extends State<HomeScreen>
),
body: TabBarView(
controller: _tabController,
children: [
MessagesTab(
onNavigateToMap: _isMapEnabled
? () => _tabController.animateTo(2)
: null,
),
ContactsTab(
onNavigateToMap: _isMapEnabled
? () => _tabController.animateTo(2)
: null,
),
if (_isMapEnabled)
MapTab(
onFullscreenChanged: (isFullscreen) {
setState(() {
_isMapFullscreen = isFullscreen;
});
},
onNavigateToMessages: () => _tabController.animateTo(0),
),
],
children: enabledTabs.map((tab) {
switch (tab) {
case _HomeTab.messages:
return MessagesTab(
onNavigateToMap: _isMapEnabled
? () => _navigateToTab(_HomeTab.map)
: null,
);
case _HomeTab.contacts:
return ContactsTab(
onNavigateToMap: _isMapEnabled
? () => _navigateToTab(_HomeTab.map)
: null,
);
case _HomeTab.map:
return MapTab(
onFullscreenChanged: (isFullscreen) {
setState(() {
_isMapFullscreen = isFullscreen;
});
},
onNavigateToMessages: () => _navigateToTab(_HomeTab.messages),
);
}
}).toList(),
),
bottomNavigationBar: shouldHideUI
bottomNavigationBar: shouldHideUI || !shouldShowTabBar
? null
: Consumer2<MessagesProvider, ContactsProvider>(
builder: (context, messagesProvider, contactsProvider, child) {
@@ -414,27 +502,31 @@ class _HomeScreenState extends State<HomeScreen>
),
child: TabBar(
controller: _tabController,
tabs: [
Tab(
icon: _buildTabIconWithBadge(
Icons.message,
unreadCount,
),
text: AppLocalizations.of(context)!.messages,
),
Tab(
icon: _buildTabIconWithBadge(
Icons.contacts,
newContactsCount,
),
text: AppLocalizations.of(context)!.contacts,
),
if (_isMapEnabled)
Tab(
icon: const Icon(Icons.map),
text: AppLocalizations.of(context)!.map,
),
],
tabs: enabledTabs.map((tab) {
switch (tab) {
case _HomeTab.messages:
return Tab(
icon: _buildTabIconWithBadge(
Icons.message,
unreadCount,
),
text: AppLocalizations.of(context)!.messages,
);
case _HomeTab.contacts:
return Tab(
icon: _buildTabIconWithBadge(
Icons.contacts,
newContactsCount,
),
text: AppLocalizations.of(context)!.contacts,
);
case _HomeTab.map:
return Tab(
icon: const Icon(Icons.map),
text: AppLocalizations.of(context)!.map,
);
}
}).toList(),
),
);
},
@@ -446,9 +538,9 @@ class _HomeScreenState extends State<HomeScreen>
return Consumer<ConnectionProvider>(
builder: (context, provider, child) {
final deviceInfo = provider.deviceInfo;
final isBleConnected = deviceInfo.isConnected;
final isSseConnected = provider.isSseClientConnected;
final isConnected = isBleConnected || isSseConnected;
final isConnected = deviceInfo.isConnected;
final isTcpConnected = provider.connectionMode == ConnectionMode.tcp;
final isBleConnected = isConnected && !isTcpConnected;
if (!isConnected) {
// Disconnected state: show connect button
@@ -536,10 +628,10 @@ class _HomeScreenState extends State<HomeScreen>
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isSseConnected
isTcpConnected
? Icons.wifi
: Icons.bluetooth_connected,
color: isSseConnected
color: isTcpConnected
? Colors.green
: (deviceInfo.signalRssi != null
? BatteryDisplayHelper.getSignalColor(
@@ -561,10 +653,10 @@ class _HomeScreenState extends State<HomeScreen>
),
),
],
if (isSseConnected && !isBleConnected) ...[
if (isTcpConnected) ...[
const SizedBox(width: 3),
Text(
'SSE',
'WiFi',
style: const TextStyle(
fontSize: 11,
color: Colors.green,

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
@@ -17,7 +19,9 @@ import '../models/message.dart';
import '../models/contact.dart';
import '../widgets/messages/sar_update_sheet.dart';
import '../widgets/messages/recipient_selector_sheet.dart';
import '../widgets/messages/message_bubble.dart';
import '../widgets/messages/messages_composer.dart';
import '../widgets/messages/messages_content.dart';
import '../widgets/common/contact_avatar.dart';
import '../services/message_destination_preferences.dart';
import '../services/voice_bitrate_preferences.dart';
import '../services/voice_recorder_service.dart';
@@ -26,6 +30,7 @@ import '../utils/toast_logger.dart';
import '../utils/key_comparison.dart';
import '../utils/voice_message_parser.dart';
import '../utils/image_message_parser.dart';
import '../utils/tictactoe_message_parser.dart';
import '../providers/image_provider.dart' as ip;
import '../services/image_codec_service.dart';
import '../services/image_preferences.dart';
@@ -42,11 +47,14 @@ class MessagesTab extends StatefulWidget {
}
class _MessagesTabState extends State<MessagesTab> {
static const int _maxContactMessageBytes = 156;
static const int _maxChannelMessageBytes = 127;
static const double _composerOverlayHeight = 148;
final TextEditingController _textController = TextEditingController();
final FocusNode _focusNode = FocusNode();
final ScrollController _scrollController = ScrollController();
int _characterCount = 0;
static const int _maxCharacters = 160;
int _messageByteCount = 0;
String? _highlightedMessageId;
Timer? _highlightTimer; // Timer for clearing message highlight
@@ -67,7 +75,7 @@ class _MessagesTabState extends State<MessagesTab> {
static const double _silenceRmsThreshold = 500.0;
static const double _silencePeakThreshold = 1400.0;
static const int _maxInteriorSilentChunks = 2;
bool get _voiceSupported => Platform.isIOS || Platform.isAndroid;
bool get _voiceSupported => !kIsWeb && (Platform.isIOS || Platform.isAndroid);
StreamSubscription<Int16List>? _voiceStreamSub;
String? _currentVoiceSessionId;
final List<Int16List> _recordedChunks = [];
@@ -164,10 +172,44 @@ class _MessagesTabState extends State<MessagesTab> {
void _updateCharacterCount() {
setState(() {
_characterCount = _textController.text.length;
_messageByteCount = utf8.encode(_textController.text).length;
});
}
int get _maxMessageBytes =>
_destinationType == MessageDestinationPreferences.destinationTypeChannel
? _maxChannelMessageBytes
: _maxContactMessageBytes;
TextInputFormatter get _messageByteLimiter =>
TextInputFormatter.withFunction((oldValue, newValue) {
if (utf8.encode(newValue.text).length <= _maxMessageBytes) {
return newValue;
}
return oldValue;
});
void _enforceMessageByteLimit() {
final currentText = _textController.text;
if (utf8.encode(currentText).length <= _maxMessageBytes) {
_updateCharacterCount();
return;
}
var truncated = currentText;
while (truncated.isNotEmpty &&
utf8.encode(truncated).length > _maxMessageBytes) {
truncated = truncated.substring(0, truncated.length - 1);
}
_textController.value = _textController.value.copyWith(
text: truncated,
selection: TextSelection.collapsed(offset: truncated.length),
composing: TextRange.empty,
);
_updateCharacterCount();
}
/// Load saved message destination from preferences
Future<void> _loadSavedDestination() async {
final savedDestination =
@@ -209,6 +251,8 @@ class _MessagesTabState extends State<MessagesTab> {
await MessageDestinationPreferences.clearDestination();
}
}
_enforceMessageByteLimit();
}
/// Show recipient selector bottom sheet
@@ -248,6 +292,8 @@ class _MessagesTabState extends State<MessagesTab> {
_selectedRecipient = recipient;
});
_enforceMessageByteLimit();
// Save to preferences
await MessageDestinationPreferences.setDestination(
type,
@@ -271,18 +317,16 @@ class _MessagesTabState extends State<MessagesTab> {
}
}
/// Get tooltip for destination button
String _getDestinationTooltip() {
String _getDestinationLabel() {
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel &&
_selectedRecipient != null) {
final channelName = _selectedRecipient!.getLocalizedDisplayName(context);
return '$channelName (tap to change)';
} else if (_selectedRecipient != null) {
final recipientName = _selectedRecipient!.displayName;
return '$recipientName (tap to change)';
return _selectedRecipient!.getLocalizedDisplayName(context);
}
return 'Select recipient';
if (_selectedRecipient != null) {
return _selectedRecipient!.displayName;
}
return 'Public Channel';
}
Future<void> _sendMessage() async {
@@ -369,7 +413,7 @@ class _MessagesTabState extends State<MessagesTab> {
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
messagesProvider.addSentMessage(sentMessage, contact: _selectedRecipient);
// Send to selected channel
await connectionProvider.sendChannelMessage(
@@ -411,7 +455,7 @@ class _MessagesTabState extends State<MessagesTab> {
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
messagesProvider.addSentMessage(sentMessage, contact: _selectedRecipient);
// Send message to selected recipient
final sentSuccessfully = await connectionProvider.sendTextMessage(
@@ -427,12 +471,63 @@ class _MessagesTabState extends State<MessagesTab> {
}
}
Future<void> _startTicTacToeGame() async {
if (!mounted) return;
if (_destinationType !=
MessageDestinationPreferences.destinationTypeContact ||
_selectedRecipient == null) {
ToastLogger.warning(
context,
'Tic-Tac-Toe works only in direct messages. Choose a contact first.',
);
return;
}
final connectionProvider = context.read<ConnectionProvider>();
final messagesProvider = context.read<MessagesProvider>();
final contactsProvider = context.read<ContactsProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
ToastLogger.error(context, 'Not connected to device');
return;
}
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
if (devicePublicKey == null || devicePublicKey.length < 6) {
ToastLogger.error(context, 'Device key unavailable');
return;
}
final gameId = List.generate(
8,
(_) => math.Random.secure().nextInt(16).toRadixString(16),
).join();
final starterKey6 = devicePublicKey
.sublist(0, 6)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join('');
final startMessage = TicTacToeMessageParser.encodeStart(
gameId: gameId,
starterKey6: starterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
await _sendToRecipient(
startMessage,
connectionProvider,
messagesProvider,
contactsProvider,
);
}
// ── Image sending ───────────────────────────────────────────────────────────
Future<void> _pickAndSendImage({
ImageSource source = ImageSource.gallery,
}) async {
if (_isSendingImage) return;
final shouldContinue = await _confirmPublicChannelMediaSend('image');
if (!shouldContinue) return;
if (!mounted) return;
final connectionProvider = context.read<ConnectionProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
ToastLogger.error(context, 'Not connected to device');
@@ -534,10 +629,14 @@ class _MessagesTabState extends State<MessagesTab> {
final isChannel =
_destinationType ==
MessageDestinationPreferences.destinationTypeChannel;
final channelIdx = isChannel
? (_selectedRecipient?.publicKey[1] ?? 0)
: null;
final recipient = _selectedRecipient;
final placeholder = Message(
id: msgId,
messageType: isChannel ? MessageType.channel : MessageType.contact,
channelIdx: isChannel ? 0 : null,
channelIdx: channelIdx,
senderPublicKeyPrefix: deviceKey.sublist(0, 6),
pathLen: 0,
textType: MessageTextType.plain,
@@ -545,30 +644,37 @@ class _MessagesTabState extends State<MessagesTab> {
text: envelope.encode(),
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: isChannel ? null : recipient?.publicKey,
);
messagesProvider.addSentMessage(placeholder);
messagesProvider.addSentMessage(placeholder, contact: recipient);
// Send IE1 envelope via normal message path.
final envelopeText = envelope.encode();
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel) {
if (isChannel) {
await connectionProvider.sendChannelMessage(
channelIdx: 0,
channelIdx: channelIdx ?? 0,
text: envelopeText,
messageId: msgId,
);
} else if (_selectedRecipient != null) {
} else if (recipient != null) {
final sent = await connectionProvider.sendTextMessage(
contactPublicKey: _selectedRecipient!.publicKey,
contactPublicKey: recipient.publicKey,
text: envelopeText,
messageId: msgId,
contact: _selectedRecipient!,
contact: recipient,
);
if (!sent) {
messagesProvider.markMessageFailed(msgId);
if (!mounted) return;
ToastLogger.error(context, 'Failed to announce image');
return;
}
} else {
messagesProvider.markMessageFailed(msgId);
if (!mounted) return;
ToastLogger.error(context, 'No recipient selected');
return;
}
debugPrint(
@@ -576,6 +682,9 @@ class _MessagesTabState extends State<MessagesTab> {
'${fragments.length} fragments, ${compressed.length}B, '
'chunk=${imageDataBytesPerFragment}B',
);
// Image fragments are always served on demand after an explicit IR2
// fetch request, including direct contacts.
} catch (e, st) {
debugPrint('❌ [Image] _pickAndSendImage: $e\n$st');
if (!mounted) return;
@@ -712,6 +821,17 @@ class _MessagesTabState extends State<MessagesTab> {
return;
}
final shouldContinue = await _confirmPublicChannelMediaSend('voice');
if (!shouldContinue) {
if (mounted) {
setState(() {
_isSendingVoice = false;
_currentVoiceSessionId = null;
});
}
return;
}
try {
await _encodeAndSendAllPackets(
chunks: chunks,
@@ -743,8 +863,6 @@ class _MessagesTabState extends State<MessagesTab> {
final connectionProvider = context.read<ConnectionProvider>();
final messagesProvider = context.read<MessagesProvider>();
final voiceProvider = context.read<VoiceProvider>();
// Insert the chat placeholder before sending (so it appears immediately).
final msgId = 'voice_${sessionId}_sent';
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix =
@@ -754,24 +872,8 @@ class _MessagesTabState extends State<MessagesTab> {
final isChannel =
_destinationType ==
MessageDestinationPreferences.destinationTypeChannel;
final sentMsg = Message(
id: msgId,
messageType: (!isChannel && _selectedRecipient != null)
? MessageType.contact
: MessageType.channel,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
text: '',
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sent,
isVoice: true,
voiceId: sessionId,
channelIdx: isChannel ? (_selectedRecipient?.publicKey[1] ?? 0) : null,
recipientPublicKey: _selectedRecipient?.publicKey,
);
messagesProvider.addSentMessage(sentMsg);
final recipient = _selectedRecipient;
final channelIdx = isChannel ? (recipient?.publicKey[1] ?? 0) : null;
final encodedPackets = <VoicePacket>[];
debugPrint(
@@ -831,32 +933,49 @@ class _MessagesTabState extends State<MessagesTab> {
);
final envelopeText = envelope.encodeText();
// Insert placeholder with real VE1 envelope text so technical details are populated.
final sentMsg = Message(
id: msgId,
messageType: (!isChannel && recipient != null)
? MessageType.contact
: MessageType.channel,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
text: envelopeText,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sent,
isVoice: true,
voiceId: sessionId,
channelIdx: channelIdx,
recipientPublicKey: isChannel ? null : recipient?.publicKey,
);
messagesProvider.addSentMessage(sentMsg, contact: recipient);
try {
if (isChannel) {
final channelIdx = _selectedRecipient?.publicKey[1] ?? 0;
await connectionProvider.sendChannelMessage(
channelIdx: channelIdx,
channelIdx: channelIdx ?? 0,
text: envelopeText,
messageId: msgId,
);
} else if (_selectedRecipient != null) {
} else if (recipient != null) {
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: _selectedRecipient!.publicKey,
contactPublicKey: recipient.publicKey,
text: envelopeText,
messageId: msgId,
contact: _selectedRecipient,
contact: recipient,
);
if (!sentSuccessfully) {
messagesProvider.markMessageFailed(msgId);
return;
}
} else {
// Fallback to public channel if destination cannot be resolved.
await connectionProvider.sendChannelMessage(
channelIdx: 0,
text: envelopeText,
messageId: msgId,
);
messagesProvider.markMessageFailed(msgId);
if (!mounted) return;
ToastLogger.error(context, 'No recipient selected');
return;
}
} catch (e, st) {
debugPrint('❌ [Voice] envelope send error: $e\n$st');
@@ -913,6 +1032,43 @@ class _MessagesTabState extends State<MessagesTab> {
return rms < _silenceRmsThreshold && peak < _silencePeakThreshold;
}
bool _isPublicChannelSelected() {
if (_destinationType !=
MessageDestinationPreferences.destinationTypeChannel) {
return false;
}
final channelIdx = _selectedRecipient?.publicKey[1] ?? 0;
return channelIdx == 0;
}
Future<bool> _confirmPublicChannelMediaSend(String mediaType) async {
if (!_isPublicChannelSelected() || !mounted) return true;
final decision = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Send to Public Channel?'),
content: Text(
'You are about to send $mediaType to the Public Channel. '
'This is not advised because everyone on the mesh may receive it. '
'Choose a private or tagged channel unless this is what you want.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('Send anyway'),
),
],
),
);
return decision ?? false;
}
// ── SAR dialog ─────────────────────────────────────────────────────────────
void _showSarDialog() {
@@ -945,6 +1101,16 @@ class _MessagesTabState extends State<MessagesTab> {
);
}
Future<void> _runAfterSheetDismissal(
BuildContext sheetContext,
Future<void> Function() action,
) async {
Navigator.pop(sheetContext);
await Future<void>.delayed(const Duration(milliseconds: 180));
if (!mounted) return;
await action();
}
void _showComposerActions() {
showModalBottomSheet(
context: context,
@@ -956,9 +1122,10 @@ class _MessagesTabState extends State<MessagesTab> {
ListTile(
leading: const Icon(Icons.add_location_alt),
title: Text(AppLocalizations.of(context)!.sendSarMarker),
onTap: () {
Navigator.pop(sheetContext);
_showSarDialog();
onTap: () async {
await _runAfterSheetDismissal(sheetContext, () async {
_showSarDialog();
});
},
),
if (_voiceSupported)
@@ -968,13 +1135,14 @@ class _MessagesTabState extends State<MessagesTab> {
title: Text(_isRecording ? 'Stop recording' : 'Record voice'),
onTap: _isSendingVoice
? null
: () {
Navigator.pop(sheetContext);
if (_isRecording) {
_stopAndSendVoice();
} else {
_startVoiceRecording();
}
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
if (_isRecording) {
await _stopAndSendVoice();
} else {
await _startVoiceRecording();
}
});
},
),
ListTile(
@@ -983,9 +1151,10 @@ class _MessagesTabState extends State<MessagesTab> {
title: const Text('Send image from gallery'),
onTap: _isSendingImage
? null
: () {
Navigator.pop(sheetContext);
_pickAndSendImage(source: ImageSource.gallery);
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _pickAndSendImage(source: ImageSource.gallery);
});
},
),
ListTile(
@@ -994,11 +1163,22 @@ class _MessagesTabState extends State<MessagesTab> {
title: const Text('Take photo'),
onTap: _isSendingImage
? null
: () {
Navigator.pop(sheetContext);
_pickAndSendImage(source: ImageSource.camera);
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _pickAndSendImage(source: ImageSource.camera);
});
},
),
ListTile(
leading: const Icon(Icons.grid_3x3),
title: const Text('Start Tic-Tac-Toe'),
subtitle: const Text('DM only'),
onTap: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _startTicTacToeGame();
});
},
),
],
),
);
@@ -1006,6 +1186,23 @@ class _MessagesTabState extends State<MessagesTab> {
);
}
Widget _buildDestinationAvatar(BuildContext context) {
final recipient = _selectedRecipient;
if (recipient != null) {
return ContactAvatar(
contact: recipient,
radius: 14,
displayName: _getDestinationLabel(),
);
}
return Icon(
_getDestinationIcon(),
size: 17,
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
}
Future<void> _sendSarMessage(
String emoji,
String name,
@@ -1192,9 +1389,6 @@ class _MessagesTabState extends State<MessagesTab> {
// SAR marker data is automatically added by SarMessageParser.enhanceMessage in MessagesProvider
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
// Look up the room contact for path logging
final contactsProvider = context.read<ContactsProvider>();
final roomContact = contactsProvider.contacts.where((c) {
@@ -1202,6 +1396,9 @@ class _MessagesTabState extends State<MessagesTab> {
c.publicKey.matches(roomPublicKey);
}).firstOrNull;
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage, contact: roomContact);
// Send SAR message to selected room (persisted and immutable)
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: roomPublicKey!,
@@ -1257,13 +1454,20 @@ class _MessagesTabState extends State<MessagesTab> {
List<Message> filteredMessages;
// If public channel is selected, show ALL messages
// If channel destination is selected, filter by selected channel.
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel &&
_selectedRecipient == null) {
filteredMessages = allMessages;
MessageDestinationPreferences.destinationTypeChannel) {
final selectedChannelIdx = _selectedRecipient?.publicKey[1] ?? 0;
if (selectedChannelIdx == 0) {
// Public channel view keeps showing all messages (current app behavior).
filteredMessages = allMessages;
} else {
filteredMessages = allMessages
.where((message) => message.channelIdx == selectedChannelIdx)
.toList();
}
}
// If a contact or room is selected, filter by recipient
// If a contact or room is selected, filter by recipient/sender prefixes.
else if ((_destinationType ==
MessageDestinationPreferences.destinationTypeContact ||
_destinationType ==
@@ -1310,254 +1514,78 @@ class _MessagesTabState extends State<MessagesTab> {
return filteredMessages;
}
void _handleMessageTap(Message message) {
if (widget.onNavigateToMap == null) return;
if (message.isSarMarker && message.sarGpsCoordinates != null) {
final mapProvider = context.read<MapProvider>();
mapProvider.navigateToLocation(
location: message.sarGpsCoordinates!,
zoom: 15.0,
);
widget.onNavigateToMap?.call();
return;
}
if (message.isDrawing && message.drawingId != null) {
debugPrint('🗺️ [MessagesTab] Drawing tapped! ID: ${message.drawingId}');
final mapProvider = context.read<MapProvider>();
final drawingProvider = context.read<DrawingProvider>();
mapProvider.navigateToDrawing(message.drawingId!, drawingProvider);
widget.onNavigateToMap?.call();
}
}
@override
Widget build(BuildContext context) {
return Consumer<MessagesProvider>(
builder: (context, messagesProvider, child) {
final messages = _getFilteredMessages(messagesProvider);
final bottomInset = MediaQuery.of(context).viewPadding.bottom;
final composerBottomPadding = bottomInset > 0 ? 2.0 : 10.0;
return Column(
children: [
// Messages list with pull-to-refresh
Expanded(
child: RefreshIndicator(
onRefresh: _handleRefresh,
child: messages.isEmpty
? LayoutBuilder(
builder: (context, constraints) =>
SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraints.maxHeight,
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.message_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(height: 16),
Text(
AppLocalizations.of(
context,
)!.noMessagesYet,
style: Theme.of(
context,
).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(
context,
)!.pullDownToSync,
style: Theme.of(
context,
).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
],
),
),
),
),
)
: ListView.builder(
controller: _scrollController,
reverse: true,
padding: const EdgeInsets.all(8),
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
final isHighlighted =
message.id == _highlightedMessageId;
return MessageBubble(
key: ValueKey(message.id),
message: message,
isHighlighted: isHighlighted,
onNavigateToMap: widget.onNavigateToMap,
onTap:
widget.onNavigateToMap != null &&
message.isSarMarker &&
message.sarGpsCoordinates != null
? () {
final mapProvider = context
.read<MapProvider>();
mapProvider.navigateToLocation(
location: message.sarGpsCoordinates!,
zoom: 15.0,
);
widget.onNavigateToMap?.call();
}
: widget.onNavigateToMap != null &&
message.isDrawing &&
message.drawingId != null
? () {
debugPrint(
'🗺️ [MessagesTab] Drawing tapped! ID: ${message.drawingId}',
);
final mapProvider = context
.read<MapProvider>();
final drawingProvider = context
.read<DrawingProvider>();
mapProvider.navigateToDrawing(
message.drawingId!,
drawingProvider,
);
widget.onNavigateToMap?.call();
}
: null,
);
},
),
),
),
// Message input area
Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border(
top: BorderSide(
color: Theme.of(context).dividerColor,
width: 1,
),
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => FocusScope.of(context).unfocus(),
child: Stack(
children: [
Positioned.fill(
child: MessagesContent(
messages: messages,
scrollController: _scrollController,
highlightedMessageId: _highlightedMessageId,
bottomContentPadding:
_composerOverlayHeight + composerBottomPadding,
onRefresh: _handleRefresh,
onNavigateToMap: widget.onNavigateToMap,
onMessageTap: _handleMessageTap,
),
),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Quick actions (+) button
IconButton(
icon: Icon(_isRecording ? Icons.stop : Icons.add),
tooltip: _isRecording ? 'Stop recording' : 'More actions',
onPressed: _isRecording
? _stopAndSendVoice
: _showComposerActions,
style: IconButton.styleFrom(
backgroundColor: Theme.of(
context,
).colorScheme.primaryContainer,
foregroundColor: _isRecording
? Colors.red
: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
const SizedBox(width: 4),
// Destination switcher button
IconButton(
icon: Icon(_getDestinationIcon()),
tooltip: _getDestinationTooltip(),
onPressed: _showRecipientSelector,
style: IconButton.styleFrom(
backgroundColor:
_destinationType ==
MessageDestinationPreferences
.destinationTypeChannel
? Theme.of(
context,
).colorScheme.surfaceContainerHighest
: Theme.of(context).colorScheme.secondaryContainer,
foregroundColor:
_destinationType ==
MessageDestinationPreferences
.destinationTypeChannel
? Theme.of(context).colorScheme.onSurface
: Theme.of(context).colorScheme.onSecondaryContainer,
),
),
const SizedBox(width: 4),
// Text field with embedded send button
Expanded(
child: TextField(
controller: _textController,
focusNode: _focusNode,
maxLength: _maxCharacters,
maxLines: null,
maxLengthEnforcement: MaxLengthEnforcement.enforced,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
hintText: AppLocalizations.of(context)!.typeYourMessage,
hintStyle: const TextStyle(fontSize: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
isDense: true,
counterText: _characterCount >= 150
? '$_characterCount/$_maxCharacters'
: '',
counterStyle: TextStyle(
fontSize: 10,
color: _characterCount > _maxCharacters * 0.9
? Colors.orange
: Theme.of(context).textTheme.bodySmall?.color,
),
suffixIcon: GestureDetector(
onLongPressStart:
(_voiceSupported && !_isSendingVoice)
? (_) => _startVoiceRecording()
: null,
onLongPressEnd: (_voiceSupported && _isRecording)
? (_) => _stopAndSendVoice()
: null,
onLongPressCancel: (_voiceSupported && _isRecording)
? () => _stopAndSendVoice()
: null,
child: IconButton(
icon: _isSendingVoice
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: Icon(
_isRecording
? Icons.mic
: Icons.send_rounded,
size: 22,
color: _isRecording
? Colors.red
: (_textController.text.trim().isEmpty
? Theme.of(context).disabledColor
: Theme.of(
context,
).colorScheme.primary),
),
onPressed:
_isRecording ||
_isSendingVoice ||
_textController.text.trim().isEmpty
? null
: _sendMessage,
tooltip: _isRecording
? 'Recording... release to send voice'
: (_isSendingVoice
? 'Sending voice...'
: _voiceSupported
? 'Send (long press to record voice)'
: 'Send'),
),
),
),
textInputAction: TextInputAction.send,
onSubmitted: (_) => _sendMessage(),
),
),
],
Positioned(
left: 0,
right: 0,
bottom: 0,
child: MessagesComposer(
textController: _textController,
focusNode: _focusNode,
messageByteLimiter: _messageByteLimiter,
messageByteCount: _messageByteCount,
maxMessageBytes: _maxMessageBytes,
isRecording: _isRecording,
isSendingVoice: _isSendingVoice,
voiceSupported: _voiceSupported,
bottomPadding: composerBottomPadding,
destinationLabel: _getDestinationLabel(),
destinationAvatar: _buildDestinationAvatar(context),
onShowComposerActions: _showComposerActions,
onShowRecipientSelector: _showRecipientSelector,
onStartVoiceRecording: _startVoiceRecording,
onStopAndSendVoice: _stopAndSendVoice,
onSendMessage: _sendMessage,
),
),
),
],
],
),
);
},
);

View File

@@ -1,10 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:meshcore_client/meshcore_client.dart';
import '../l10n/app_localizations.dart';
import '../providers/connection_provider.dart';
import '../providers/contacts_provider.dart';
import '../utils/log_rx_route_decoder.dart';
class PacketLogScreen extends StatefulWidget {
final MeshCoreBleService bleService;
@@ -456,6 +460,26 @@ class _PacketLogCard extends StatelessWidget {
final isRx = log.direction == PacketDirection.rx;
final directionColor = isRx ? Colors.green : Colors.blue;
final rxInfo = log.logRxDataInfo;
final contacts = context.watch<ContactsProvider>().contacts;
final connectionProvider = context.watch<ConnectionProvider>();
final decodedRoute = LogRxRouteDecoder.decode(log.rawData);
final ownPublicKey = connectionProvider.deviceInfo.publicKey;
final ownName =
connectionProvider.deviceInfo.selfName ??
connectionProvider.deviceInfo.displayName;
final resolvedPath = decodedRoute?.pathHashes
.map(
(hash) => LogRxRouteDecoder.resolveHash(
hash,
contacts: contacts,
ownPublicKey: ownPublicKey,
ownName: ownName,
),
)
.toList();
final originalSender = resolvedPath != null && resolvedPath.isNotEmpty
? resolvedPath.first
: null;
return Card(
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
@@ -580,6 +604,14 @@ class _PacketLogCard extends StatelessWidget {
),
),
],
if (isRx && decodedRoute != null) ...[
const SizedBox(height: 12),
_RouteSection(
route: decodedRoute,
path: resolvedPath ?? const [],
originalSender: originalSender,
),
],
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
@@ -723,6 +755,162 @@ class _PacketLogCard extends StatelessWidget {
}
}
class _RouteSection extends StatelessWidget {
final DecodedLogRxRoute route;
final List<ResolvedNodeHash> path;
final ResolvedNodeHash? originalSender;
const _RouteSection({
required this.route,
required this.path,
required this.originalSender,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Row(
children: [
Icon(Icons.alt_route, size: 16),
SizedBox(width: 6),
Text(
'Mesh Route',
style: TextStyle(fontWeight: FontWeight.w700, fontSize: 12),
),
],
),
const SizedBox(height: 10),
Wrap(
spacing: 10,
runSpacing: 10,
children: [
_FactCard(
icon: Icons.route,
label: 'Payload',
value: _payloadTypeLabel(route.payloadType),
),
_FactCard(
icon: Icons.hub,
label: 'Hops',
value: '${route.pathHashes.length}',
),
if (originalSender != null)
_FactCard(
icon: Icons.person_pin_circle,
label: 'Original sender',
value: _nodeLabel(originalSender!),
),
],
),
const SizedBox(height: 12),
if (path.isEmpty)
Text(
'Direct packet, no hop path attached.',
style: TextStyle(fontSize: 12, color: Colors.grey[700]),
)
else
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (var i = 0; i < path.length; i++) ...[
_RouteHopChip(index: i + 1, node: path[i]),
if (i < path.length - 1)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 2),
child: Icon(Icons.arrow_right_alt, size: 16),
),
],
],
),
],
),
);
}
static String _payloadTypeLabel(int payloadType) {
switch (payloadType) {
case 0x00:
return 'REQ';
case 0x01:
return 'RESP';
case 0x02:
return 'TXT';
case 0x03:
return 'ACK';
case 0x04:
return 'ADVERT';
case 0x05:
return 'GRP_TXT';
case 0x06:
return 'GRP_DATA';
case 0x07:
return 'ANON_REQ';
case 0x08:
return 'PATH';
case 0x09:
return 'TRACE';
case 0x0A:
return 'MULTIPART';
case 0x0B:
return 'CONTROL';
default:
return '0x${payloadType.toRadixString(16).padLeft(2, '0')}';
}
}
static String _nodeLabel(ResolvedNodeHash node) {
if (node.isOwnNode) {
return '${node.label} (${node.hexLabel})';
}
if (node.matchCount == 0) {
return node.hexLabel;
}
if (node.isUniqueMatch) {
return '${node.label} (${node.hexLabel})';
}
return '${node.label} (${node.hexLabel}, ${node.matchCount} matches)';
}
}
class _RouteHopChip extends StatelessWidget {
final int index;
final ResolvedNodeHash node;
const _RouteHopChip({required this.index, required this.node});
@override
Widget build(BuildContext context) {
final color = node.isOwnNode
? Colors.blue
: node.isUniqueMatch
? Colors.green
: Colors.orange;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(999),
border: Border.all(color: color.withValues(alpha: 0.35)),
),
child: Text(
'$index. ${_RouteSection._nodeLabel(node)}',
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
),
);
}
}
class _FactCard extends StatelessWidget {
final IconData icon;
final String label;

View File

@@ -403,25 +403,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
channelCount: 2,
);
final sarMessages = SampleDataGenerator.generateSarMarkerMessages(
final sampleMessages = SampleDataGenerator.generateAllMessages(
centerLocation: centerLocation,
l10n: l10n,
foundPersonCount: 2,
fireCount: 1,
stagingCount: 1,
objectCount: 1,
);
final channelMessages = SampleDataGenerator.generateChannelMessages(
centerLocation: centerLocation,
l10n: l10n,
generalChannelMessages: 8,
emergencyChannelMessages: 5,
);
// Combine all messages
final allMessages = [...sarMessages, ...channelMessages];
// Add to providers
final contactsProvider = Provider.of<ContactsProvider>(
context,
@@ -433,7 +425,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
contactsProvider.addContacts(contacts);
messagesProvider.addMessages(allMessages);
for (final message in sampleMessages.messages) {
messagesProvider.addMessage(
message,
contactLocationSnapshot: sampleMessages.contactLocations[message.id],
);
}
if (!mounted) return;
@@ -446,8 +443,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
AppLocalizations.of(context)!.loadedSampleData(
teamCount,
channelCount,
sarMessages.length,
channelMessages.length,
sampleMessages.messages.where((m) => m.isSarMarker).length,
sampleMessages.messages.length,
),
),
backgroundColor: Colors.green,
@@ -621,6 +618,46 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
Future<void> _clearMessages() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Clear Messages'),
content: const Text(
'This will permanently delete all stored messages. Are you sure?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(AppLocalizations.of(context)!.cancel),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(AppLocalizations.of(context)!.clear),
),
],
),
);
if (confirmed != true || !mounted) return;
final messagesProvider = Provider.of<MessagesProvider>(
context,
listen: false,
);
messagesProvider.clearMessages();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('All messages cleared'),
backgroundColor: Colors.orange,
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -661,6 +698,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
),
Consumer<AppProvider>(
builder: (context, appProvider, child) => SwitchListTile(
secondary: const Icon(Icons.person_add_alt_1),
title: const Text('Auto-add discovered contacts'),
subtitle: const Text(
'Automatically fetch and add new contacts when they are discovered',
),
value: appProvider.autoAddDiscoveredContacts,
onChanged: (value) async {
await appProvider.toggleAutoAddDiscoveredContacts(value);
},
),
),
Consumer<AppProvider>(
builder: (context, appProvider, child) => SwitchListTile(
secondary: const Icon(Icons.map_outlined),
@@ -674,6 +724,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
),
Consumer<AppProvider>(
builder: (context, appProvider, child) => SwitchListTile(
secondary: const Icon(Icons.contacts_outlined),
title: const Text('Disable Contacts'),
subtitle: const Text(
'Hide the contacts tab to simplify navigation',
),
value: !appProvider.isContactsEnabled,
onChanged: (value) async {
await appProvider.toggleContactsEnabled(!value);
},
),
),
ListTile(
leading: const Icon(Icons.language),
title: Text(AppLocalizations.of(context)!.language),
@@ -681,6 +744,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLanguageDialog(),
),
ListTile(
leading: const Icon(Icons.delete_sweep, color: Colors.red),
title: const Text(
'Clear Messages',
style: TextStyle(color: Colors.red),
),
subtitle: const Text('Delete all stored message history'),
onTap: _clearMessages,
),
const Divider(),
// Voice Settings Section

View File

@@ -0,0 +1,601 @@
import 'package:flutter/material.dart';
import 'package:meshcore_client/meshcore_client.dart';
import 'package:provider/provider.dart';
import '../models/device_info.dart';
import '../providers/connection_provider.dart';
import '../widgets/device/spectrum_scan_panel.dart';
class SpectrumScanScreen extends StatefulWidget {
const SpectrumScanScreen({super.key});
@override
State<SpectrumScanScreen> createState() => _SpectrumScanScreenState();
}
class _SpectrumScanScreenState extends State<SpectrumScanScreen> {
static const List<String> _bandwidthOptions = [
'7.8 kHz',
'10.4 kHz',
'15.6 kHz',
'20.8 kHz',
'31.25 kHz',
'41.7 kHz',
'62.5 kHz',
'125 kHz',
'250 kHz',
'500 kHz',
];
String _selectedBandwidth = '62.5 kHz';
bool _isSpectrumScanRunning = false;
bool _rangeInitialized = false;
String? _lastRangeSourceKey;
late double _scanRangeMinMhz;
late double _scanRangeMaxMhz;
late RangeValues _scanRangeValues;
List<SpectrumScanCandidate> _scanCandidates = const [];
int? _selectedScanFrequencyKhz;
int _completedScanSectors = 0;
int _totalScanSectors = 0;
List<SpectrumScanCandidate> get _recommendedScanCandidates =>
_scanCandidates.take(8).toList();
@override
void initState() {
super.initState();
final deviceInfo = _deviceInfo;
if (deviceInfo.radioBw != null &&
deviceInfo.radioBw! >= 0 &&
deviceInfo.radioBw! < _bandwidthOptions.length) {
_selectedBandwidth = _bandwidthOptions[deviceInfo.radioBw!];
}
_syncRangeFromDevice(deviceInfo);
_selectedScanFrequencyKhz = deviceInfo.radioFreq;
}
DeviceInfo get _deviceInfo => context.read<ConnectionProvider>().deviceInfo;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_syncRangeFromDevice(context.watch<ConnectionProvider>().deviceInfo);
}
void _syncRangeFromDevice(DeviceInfo deviceInfo) {
final minKhz = deviceInfo.spectrumScanMinKhz;
final maxKhz = deviceInfo.spectrumScanMaxKhz;
late double normalizedMinMhz;
late double normalizedMaxMhz;
late String sourceKey;
if (minKhz != null && maxKhz != null && maxKhz > minKhz) {
final normalized = _normalizeScanRange(
minKhz / 1000.0,
maxKhz / 1000.0,
deviceInfo.radioFreq != null ? deviceInfo.radioFreq! / 1000.0 : null,
);
normalizedMinMhz = normalized.$1;
normalizedMaxMhz = normalized.$2;
sourceKey = 'fw:$minKhz:$maxKhz';
} else {
final normalized = _normalizeScanRange(
null,
null,
deviceInfo.radioFreq != null ? deviceInfo.radioFreq! / 1000.0 : null,
);
normalizedMinMhz = normalized.$1;
normalizedMaxMhz = normalized.$2;
sourceKey =
'fallback:${deviceInfo.radioFreq != null ? deviceInfo.radioFreq! ~/ 1000 : 869525}';
}
if (_rangeInitialized && _lastRangeSourceKey == sourceKey) {
return;
}
_scanRangeMinMhz = normalizedMinMhz;
_scanRangeMaxMhz = normalizedMaxMhz;
if (_scanRangeMaxMhz <= _scanRangeMinMhz) {
_scanRangeMaxMhz = _scanRangeMinMhz + 0.5;
}
_scanRangeValues = RangeValues(_scanRangeMinMhz, _scanRangeMaxMhz);
_rangeInitialized = true;
_lastRangeSourceKey = sourceKey;
}
(double, double) _normalizeScanRange(
double? minMhz,
double? maxMhz,
double? centerMhz,
) {
const hardMinMhz = 800.0;
const hardMaxMhz = 950.0;
final center = centerMhz ?? 869.525;
if (minMhz != null && maxMhz != null) {
final clampedMin = minMhz.clamp(hardMinMhz, hardMaxMhz);
final clampedMax = maxMhz.clamp(hardMinMhz, hardMaxMhz);
if (clampedMax > clampedMin) {
return (clampedMin, clampedMax);
}
}
if (center >= 900.0 && center <= 930.0) {
return (902.0, 928.0);
}
return (863.0, 870.0);
}
double _bandwidthToKhz(String bw) {
switch (bw) {
case '7.8 kHz':
return 7.8;
case '10.4 kHz':
return 10.4;
case '15.6 kHz':
return 15.6;
case '20.8 kHz':
return 20.8;
case '31.25 kHz':
return 31.25;
case '41.7 kHz':
return 41.7;
case '62.5 kHz':
return 62.5;
case '125 kHz':
return 125.0;
case '250 kHz':
return 250.0;
case '500 kHz':
return 500.0;
default:
return 62.5;
}
}
String _currentParamProfile(DeviceInfo deviceInfo) {
final sf = deviceInfo.radioSf ?? 8;
final cr = deviceInfo.radioCr ?? 8;
return 'BW $_selectedBandwidth | SF$sf | CR 4/$cr';
}
String _recommendationTitle(int index) {
switch (index) {
case 0:
return 'Best candidate';
case 1:
return 'Alternate';
case 2:
return 'Fallback';
default:
return 'Candidate ${index + 1}';
}
}
List<int> _possibleBracketFrequenciesKhz() {
final bandwidthKhz = _bandwidthToKhz(_selectedBandwidth);
final halfBandwidthKhz = bandwidthKhz / 2.0;
final startKhz = (_scanRangeValues.start * 1000).round();
final stopKhz = (_scanRangeValues.end * 1000).round();
final firstCenterKhz = (startKhz + halfBandwidthKhz).round();
final lastCenterKhz = (stopKhz - halfBandwidthKhz).round();
if (lastCenterKhz < firstCenterKhz) {
return const [];
}
final stepKhz = bandwidthKhz >= 125.0 ? bandwidthKhz.round() : 25;
final centers = <int>[];
for (
var centerKhz = firstCenterKhz;
centerKhz <= lastCenterKhz && centers.length < 8;
centerKhz += stepKhz
) {
centers.add(centerKhz);
}
if (centers.isEmpty || centers.last != lastCenterKhz) {
centers.add(lastCenterKhz);
}
return centers.toSet().toList()..sort();
}
void _resetDerivedScanResults() {
_scanCandidates = const [];
_selectedScanFrequencyKhz = null;
}
List<(int startKhz, int stopKhz)> _buildScanSectors(double bandwidthKhz) {
final startKhz = (_scanRangeValues.start * 1000).round();
final stopKhz = (_scanRangeValues.end * 1000).round();
final sectorWidthKhz = (bandwidthKhz * 24).round().clamp(250, 1200);
final overlapKhz = bandwidthKhz.round().clamp(8, 500);
final sectors = <(int startKhz, int stopKhz)>[];
var sectorStartKhz = startKhz;
while (sectorStartKhz < stopKhz) {
final sectorStopKhz = (sectorStartKhz + sectorWidthKhz).clamp(
sectorStartKhz + overlapKhz,
stopKhz,
);
sectors.add((sectorStartKhz, sectorStopKhz));
if (sectorStopKhz >= stopKhz) {
break;
}
sectorStartKhz = sectorStopKhz - overlapKhz;
}
return sectors;
}
List<SpectrumScanCandidate> _mergeSectorCandidates(
Iterable<SpectrumScanCandidate> candidates,
) {
final byFrequency = <int, SpectrumScanCandidate>{};
for (final candidate in candidates) {
final existing = byFrequency[candidate.centerFrequencyKhz];
if (existing == null ||
candidate.occupancyPercent < existing.occupancyPercent ||
(candidate.occupancyPercent == existing.occupancyPercent &&
candidate.peakRssiDbm < existing.peakRssiDbm) ||
(candidate.occupancyPercent == existing.occupancyPercent &&
candidate.peakRssiDbm == existing.peakRssiDbm &&
candidate.avgRssiDbm < existing.avgRssiDbm)) {
byFrequency[candidate.centerFrequencyKhz] = candidate;
}
}
final merged = byFrequency.values.toList()
..sort((a, b) {
final occupancyCompare = a.occupancyPercent.compareTo(
b.occupancyPercent,
);
if (occupancyCompare != 0) return occupancyCompare;
final peakCompare = a.peakRssiDbm.compareTo(b.peakRssiDbm);
if (peakCompare != 0) return peakCompare;
return a.avgRssiDbm.compareTo(b.avgRssiDbm);
});
return merged;
}
Future<void> _runSpectrumScan() async {
final connectionProvider = context.read<ConnectionProvider>();
final bandwidthKhz = _bandwidthToKhz(_selectedBandwidth);
final sectors = _buildScanSectors(bandwidthKhz);
final sectorCandidates = <SpectrumScanCandidate>[];
setState(() {
_isSpectrumScanRunning = true;
_resetDerivedScanResults();
_completedScanSectors = 0;
_totalScanSectors = sectors.length;
});
try {
for (var i = 0; i < sectors.length; i++) {
final sector = sectors[i];
final result = await connectionProvider.scanSpectrum(
startFrequencyKhz: sector.$1,
stopFrequencyKhz: sector.$2,
bandwidthKhz: bandwidthKhz.round(),
stepKhz: (bandwidthKhz / 2).round().clamp(1, 1000),
dwellMs: 160,
thresholdDb: 8,
);
if (result != null) {
sectorCandidates.addAll(result.candidates);
final mergedCandidates = _mergeSectorCandidates(sectorCandidates);
if (mounted) {
setState(() {
_scanCandidates = mergedCandidates;
if (_selectedScanFrequencyKhz == null &&
mergedCandidates.isNotEmpty) {
_selectedScanFrequencyKhz =
mergedCandidates.first.centerFrequencyKhz;
}
_completedScanSectors = i + 1;
});
}
} else if (mounted) {
setState(() {
_completedScanSectors = i + 1;
});
}
}
} finally {
if (mounted) {
setState(() {
_isSpectrumScanRunning = false;
if (_completedScanSectors == 0) {
_totalScanSectors = sectors.length;
}
});
}
}
if (!mounted) return;
final mergedCandidates = _mergeSectorCandidates(sectorCandidates);
if (mergedCandidates.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Spectrum scan returned no candidate frequencies'),
backgroundColor: Colors.red,
),
);
return;
}
setState(() {
_scanCandidates = mergedCandidates;
_selectedScanFrequencyKhz = mergedCandidates.first.centerFrequencyKhz;
});
}
Future<void> _applySelectedScanFrequency() async {
if (_selectedScanFrequencyKhz == null) return;
final connectionProvider = context.read<ConnectionProvider>();
final deviceInfo = connectionProvider.deviceInfo;
await connectionProvider.setRadioParams(
frequency: _selectedScanFrequencyKhz!,
bandwidth: _bandwidthOptions.indexOf(_selectedBandwidth),
spreadingFactor: deviceInfo.radioSf ?? 8,
codingRate: deviceInfo.radioCr ?? 8,
repeat: deviceInfo.clientRepeat,
);
await connectionProvider.refreshDeviceInfo();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Applied ${(_selectedScanFrequencyKhz! / 1000.0).toStringAsFixed(3)} MHz',
),
backgroundColor: Colors.green,
),
);
}
int? _currentPreviewFrequencyKhz(DeviceInfo deviceInfo) {
if (_selectedScanFrequencyKhz != null) {
return _selectedScanFrequencyKhz;
}
return deviceInfo.radioFreq;
}
@override
Widget build(BuildContext context) {
final deviceInfo = context.watch<ConnectionProvider>().deviceInfo;
final theme = Theme.of(context);
final possibleBracketFrequencies = _possibleBracketFrequenciesKhz();
final recommendedScanCandidates = _recommendedScanCandidates;
final recommendationFrequencies = recommendedScanCandidates.isNotEmpty
? recommendedScanCandidates
.map((candidate) => candidate.centerFrequencyKhz)
.toList()
: possibleBracketFrequencies;
return Scaffold(
appBar: AppBar(title: const Text('Spectrum Scan')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButtonFormField<String>(
initialValue: _selectedBandwidth,
decoration: const InputDecoration(
labelText: 'Bandwidth',
border: OutlineInputBorder(),
helperText:
'Scan and apply frequencies for this bandwidth',
),
items: _bandwidthOptions.map((value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
if (value == null) return;
setState(() {
_selectedBandwidth = value;
_resetDerivedScanResults();
});
},
),
const SizedBox(height: 16),
Text(
deviceInfo.spectrumScanMinKhz != null &&
deviceInfo.spectrumScanMaxKhz != null
? 'Firmware scan range: ${_scanRangeMinMhz.toStringAsFixed(3)}-${_scanRangeMaxMhz.toStringAsFixed(3)} MHz'
: 'Fallback scan range selected from current band. MeshCore commonly uses EU868 or US915.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
if (_isSpectrumScanRunning) ...[
const SizedBox(height: 8),
Text(
'Scanning sector ${_completedScanSectors + 1} of $_totalScanSectors. Results update as each sector completes.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
],
const SizedBox(height: 12),
SpectrumScanPanel(
theme: theme,
scanSupported: deviceInfo.supportsSpectrumScan == true,
isRunning: _isSpectrumScanRunning,
rangeMinMhz: _scanRangeMinMhz,
rangeMaxMhz: _scanRangeMaxMhz,
rangeValues: _scanRangeValues,
bandwidthKhz: _bandwidthToKhz(_selectedBandwidth),
selectedFrequencyKhz: _currentPreviewFrequencyKhz(
deviceInfo,
),
graphCandidates: _scanCandidates,
selectableCandidates: recommendedScanCandidates,
onRangeChanged: (values) {
setState(() {
_scanRangeValues = values;
_resetDerivedScanResults();
});
},
onCandidateChanged: (value) {
setState(() {
_selectedScanFrequencyKhz = value;
});
},
onRunScan: _runSpectrumScan,
onApplySelected: _applySelectedScanFrequency,
),
if (recommendationFrequencies.isNotEmpty) ...[
const SizedBox(height: 18),
Text(
_scanCandidates.isNotEmpty
? 'Recommended profiles'
: 'Possible brackets',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
_scanCandidates.isNotEmpty
? 'Suggested frequencies from the latest scan with the radio parameters to keep alongside them.'
: 'Usable frequency brackets derived from the selected span and bandwidth, even without live scan data.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 12),
for (
var i = 0;
i < recommendationFrequencies.length;
i++
) ...[
_RecommendationTile(
title: _recommendationTitle(i),
frequencyKhz: recommendationFrequencies[i],
candidate: recommendedScanCandidates.isNotEmpty
? recommendedScanCandidates[i]
: null,
bandwidthKhz: _bandwidthToKhz(_selectedBandwidth),
paramsLabel: _currentParamProfile(deviceInfo),
isSelected:
_selectedScanFrequencyKhz ==
recommendationFrequencies[i],
onSelect: () {
setState(() {
_selectedScanFrequencyKhz =
recommendationFrequencies[i];
});
},
),
if (i != recommendationFrequencies.length - 1)
const SizedBox(height: 10),
],
],
],
),
),
),
],
),
);
}
}
class _RecommendationTile extends StatelessWidget {
final String title;
final int frequencyKhz;
final SpectrumScanCandidate? candidate;
final double bandwidthKhz;
final String paramsLabel;
final bool isSelected;
final VoidCallback onSelect;
const _RecommendationTile({
required this.title,
required this.frequencyKhz,
required this.candidate,
required this.bandwidthKhz,
required this.paramsLabel,
required this.isSelected,
required this.onSelect,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return InkWell(
onTap: onSelect,
borderRadius: BorderRadius.circular(14),
child: Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: isSelected
? scheme.primaryContainer.withValues(alpha: 0.55)
: scheme.surfaceContainerHighest.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: isSelected ? scheme.primary : scheme.outlineVariant,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
title,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
if (isSelected)
Icon(Icons.check_circle, color: scheme.primary, size: 18),
],
),
const SizedBox(height: 8),
Text(
'${(frequencyKhz / 1000.0).toStringAsFixed(3)} MHz',
style: theme.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 6),
Text(paramsLabel, style: theme.textTheme.bodyMedium),
const SizedBox(height: 6),
Text(
candidate != null
? 'Occupancy ${candidate!.occupancyPercent}% | Avg ${candidate!.avgRssiDbm} dBm | Peak ${candidate!.peakRssiDbm} dBm'
: 'Bracket ${(frequencyKhz / 1000.0 - bandwidthKhz / 2000.0).toStringAsFixed(3)}-${(frequencyKhz / 1000.0 + bandwidthKhz / 2000.0).toStringAsFixed(3)} MHz',
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
);
}
}

View File

@@ -25,6 +25,14 @@ class CayenneLppParser {
int fieldCount = 0;
while (reader.hasRemaining) {
if (fieldCount > 0 && _isZeroPaddedTail(data, reader.remainingBytesCount)) {
debugPrint(
' Detected zero-padded telemetry tail, stopping parse at position '
'${data.length - reader.remainingBytesCount}',
);
break;
}
try {
fieldCount++;
debugPrint(
@@ -250,6 +258,14 @@ class CayenneLppParser {
return ((voltage - 3.0) / 1.2) * 100.0;
}
static bool _isZeroPaddedTail(Uint8List data, int remainingBytes) {
final start = data.length - remainingBytes;
for (int i = start; i < data.length; i++) {
if (data[i] != 0) return false;
}
return remainingBytes > 0;
}
/// Create Cayenne LPP data for GPS location
/// Standard Cayenne LPP GPS format (type 0x88):
/// - Latitude: 3 bytes, signed 24-bit, big-endian, × 10000

View File

@@ -64,6 +64,8 @@ class LocalePreferences {
return 'Italiano';
case 'el':
return 'Greek';
case 'cn':
return '简体中文';
default:
return locale.languageCode;
}
@@ -88,6 +90,8 @@ class LocalePreferences {
return 'Italiano';
case 'el':
return 'Ελληνικά';
case 'cn':
return '简体中文';
default:
return locale.languageCode;
}

View File

@@ -0,0 +1,75 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class MeshMapNode {
final int type;
final String name;
final String publicKey;
final double latitude;
final double longitude;
final int updatedAtMs;
const MeshMapNode({
required this.type,
required this.name,
required this.publicKey,
required this.latitude,
required this.longitude,
required this.updatedAtMs,
});
factory MeshMapNode.fromJson(Map<String, dynamic> json) {
return MeshMapNode(
type: (json['type'] as num?)?.toInt() ?? 0,
name: (json['name'] as String?)?.trim() ?? 'Unknown',
publicKey: ((json['public_key'] as String?) ?? '').toLowerCase(),
latitude: (json['latitude'] as num?)?.toDouble() ?? 0.0,
longitude: (json['longitude'] as num?)?.toDouble() ?? 0.0,
updatedAtMs: (json['updated_at'] as num?)?.toInt() ?? 0,
);
}
}
class MeshMapNodesService {
static const String _nodesEndpoint =
'https://api.meshcore.nz/api/v1/map/nodes';
static const Duration _cacheTtl = Duration(minutes: 2);
static const Duration traceCacheTtl = Duration(minutes: 10);
static List<MeshMapNode>? _cachedNodes;
static DateTime? _cachedAt;
static Future<List<MeshMapNode>> fetchNodes({
bool forceRefresh = false,
Duration cacheTtl = _cacheTtl,
}) async {
final now = DateTime.now();
if (!forceRefresh &&
_cachedNodes != null &&
_cachedAt != null &&
now.difference(_cachedAt!) < cacheTtl) {
return _cachedNodes!;
}
final response = await http
.get(Uri.parse(_nodesEndpoint))
.timeout(const Duration(seconds: 12));
if (response.statusCode < 200 || response.statusCode >= 300) {
throw Exception('Map nodes API returned ${response.statusCode}');
}
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
final nodesRaw = decoded['nodes'] as List<dynamic>? ?? const [];
final nodes = nodesRaw
.whereType<Map<String, dynamic>>()
.map(MeshMapNode.fromJson)
.where(
(n) => n.publicKey.isNotEmpty && n.latitude != 0 && n.longitude != 0,
)
.toList();
_cachedNodes = nodes;
_cachedAt = now;
return nodes;
}
}

View File

@@ -2,15 +2,25 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/message.dart';
import '../models/message_contact_location.dart';
import '../models/message_reception_details.dart';
import 'package:latlong2/latlong.dart';
/// Service for persisting messages to local storage
class MessageStorageService {
static const String _messagesKey = 'stored_messages';
static const String _messageContactLocationsKey =
'stored_message_contact_locations';
static const String _messageReceptionDetailsKey =
'stored_message_reception_details';
static const int _maxStoredMessages = 1000; // Store up to 1000 messages
/// Save messages to persistent storage
Future<void> saveMessages(List<Message> messages) async {
Future<void> saveMessages(
List<Message> messages, {
Map<String, MessageContactLocation> messageContactLocations = const {},
Map<String, MessageReceptionDetails> messageReceptionDetails = const {},
}) async {
try {
final prefs = await SharedPreferences.getInstance();
@@ -24,6 +34,29 @@ class MessageStorageService {
final jsonString = jsonEncode(limitedList);
await prefs.setString(_messagesKey, jsonString);
final retainedMessageIds = limitedList
.map((entry) => entry['id'] as String)
.toSet();
final locationJson = <String, dynamic>{};
final receptionJson = <String, dynamic>{};
for (final entry in messageContactLocations.entries) {
if (retainedMessageIds.contains(entry.key)) {
locationJson[entry.key] = entry.value.toJson();
}
}
for (final entry in messageReceptionDetails.entries) {
if (retainedMessageIds.contains(entry.key)) {
receptionJson[entry.key] = entry.value.toJson();
}
}
await prefs.setString(
_messageContactLocationsKey,
jsonEncode(locationJson),
);
await prefs.setString(
_messageReceptionDetailsKey,
jsonEncode(receptionJson),
);
debugPrint(
'✅ [MessageStorage] Saved ${limitedList.length} messages to storage',
@@ -33,6 +66,66 @@ class MessageStorageService {
}
}
Future<Map<String, MessageContactLocation>>
loadMessageContactLocations() async {
try {
final prefs = await SharedPreferences.getInstance();
final jsonString = prefs.getString(_messageContactLocationsKey);
if (jsonString == null || jsonString.isEmpty) {
return const {};
}
final decoded = jsonDecode(jsonString);
if (decoded is! Map<String, dynamic>) {
return const {};
}
final result = <String, MessageContactLocation>{};
for (final entry in decoded.entries) {
final value = entry.value;
if (value is! Map<String, dynamic>) continue;
final snapshot = MessageContactLocation.fromJson(value);
if (snapshot != null) {
result[entry.key] = snapshot;
}
}
return result;
} catch (e) {
debugPrint('❌ [MessageStorage] Error loading contact locations: $e');
return const {};
}
}
Future<Map<String, MessageReceptionDetails>>
loadMessageReceptionDetails() async {
try {
final prefs = await SharedPreferences.getInstance();
final jsonString = prefs.getString(_messageReceptionDetailsKey);
if (jsonString == null || jsonString.isEmpty) {
return const {};
}
final decoded = jsonDecode(jsonString);
if (decoded is! Map<String, dynamic>) {
return const {};
}
final result = <String, MessageReceptionDetails>{};
for (final entry in decoded.entries) {
final value = entry.value;
if (value is! Map<String, dynamic>) continue;
final snapshot = MessageReceptionDetails.fromJson(value);
if (snapshot != null) {
result[entry.key] = snapshot;
}
}
return result;
} catch (e) {
debugPrint('❌ [MessageStorage] Error loading reception details: $e');
return const {};
}
}
/// Load messages from persistent storage
Future<List<Message>> loadMessages() async {
try {
@@ -66,6 +159,8 @@ class MessageStorageService {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_messagesKey);
await prefs.remove(_messageContactLocationsKey);
await prefs.remove(_messageReceptionDetailsKey);
debugPrint('✅ [MessageStorage] Cleared all stored messages');
} catch (e) {
debugPrint('❌ [MessageStorage] Error clearing messages: $e');

View File

@@ -1,213 +1,155 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:nsd/nsd.dart';
/// Discovered SSE server on the network
/// Discovered MeshCore device on the network (TCP/WiFi)
class DiscoveredServer {
final String ipAddress;
final int port;
final int responseTime; // in milliseconds
final String serverUrl;
final int responseTime; // milliseconds
DiscoveredServer({
const DiscoveredServer({
required this.ipAddress,
required this.port,
required this.responseTime,
}) : serverUrl = 'http://$ipAddress:$port';
});
@override
String toString() {
return 'DiscoveredServer($ipAddress:$port, ${responseTime}ms)';
}
String toString() => 'DiscoveredServer($ipAddress:$port, ${responseTime}ms)';
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is DiscoveredServer &&
other.ipAddress == ipAddress &&
other.port == port;
}
bool operator ==(Object other) =>
other is DiscoveredServer &&
other.ipAddress == ipAddress &&
other.port == port;
@override
int get hashCode => Object.hash(ipAddress, port);
}
/// Network Scanner Service
/// Discovers MeshCore devices running the TCP/WiFi server (port 5000).
///
/// Discovers SSE servers on the local network using Bonjour/mDNS.
/// Falls back to port scanning (12929) if no services are discovered.
/// Uses parallel scanning (20 IPs at once) for fast discovery.
/// First tries mDNS/Bonjour (_meshcore._tcp), then falls back to a parallel
/// TCP-connect port scan of the local /24 subnet.
class NetworkScannerService {
static const int defaultPort = 12929;
static const String serviceType = '_meshcore-sse._tcp';
static const int defaultPort = 5000;
static const String serviceType = '_meshcore._tcp';
static const int parallelScans = 20;
static const Duration scanTimeout = Duration(seconds: 2);
static const Duration connectTimeout = Duration(seconds: 2);
static const Duration bonjourTimeout = Duration(seconds: 5);
Discovery? _activeDiscovery;
/// Callback for when a server is discovered
Function(DiscoveredServer)? onServerDiscovered;
/// Callback for scan progress updates
Function(int scanned, int total)? onProgressUpdate;
bool _isScanning = false;
bool get isScanning => _isScanning;
/// Cached discovered servers from the last scan
List<DiscoveredServer> _cachedServers = [];
List<DiscoveredServer> get cachedServers => List.unmodifiable(_cachedServers);
/// Whether we have cached results from a previous scan
bool get hasCachedResults => _cachedServers.isNotEmpty;
/// Get all local IP addresses
Future<Set<String>> _getLocalIpAddresses() async {
final Set<String> localIps = {};
// ── Helpers ────────────────────────────────────────────────────────────────
Future<Set<String>> _getLocalIpAddresses() async {
final ips = <String>{};
try {
final interfaces = await NetworkInterface.list();
for (final interface in interfaces) {
for (final addr in interface.addresses) {
if (addr.type == InternetAddressType.IPv4) {
localIps.add(addr.address);
}
for (final iface in await NetworkInterface.list()) {
for (final addr in iface.addresses) {
if (addr.type == InternetAddressType.IPv4) ips.add(addr.address);
}
}
} catch (e) {
debugPrint('❌ [NetworkScanner] Error getting local IPs: $e');
}
return localIps;
return ips;
}
/// Get local network IP range to scan
Future<List<String>> _getLocalNetworkRange() async {
final List<String> ips = [];
try {
// Get all network interfaces
final interfaces = await NetworkInterface.list();
for (final interface in interfaces) {
for (final addr in interface.addresses) {
// Only scan IPv4 addresses that are not loopback
for (final iface in await NetworkInterface.list()) {
for (final addr in iface.addresses) {
if (addr.type == InternetAddressType.IPv4 && !addr.isLoopback) {
final ip = addr.address;
final parts = ip.split('.');
final parts = addr.address.split('.');
if (parts.length == 4) {
// Generate range for the same subnet (e.g., 192.168.1.1-254)
final subnet = '${parts[0]}.${parts[1]}.${parts[2]}';
// Scan from .1 to .254 (skip .0 and .255)
for (int i = 1; i <= 254; i++) {
ips.add('$subnet.$i');
}
debugPrint('📡 [NetworkScanner] Will scan subnet: $subnet.0/24');
// Only scan first viable subnet
return ips;
debugPrint('📡 [NetworkScanner] Scanning subnet $subnet.0/24');
return [for (int i = 1; i <= 254; i++) '$subnet.$i'];
}
}
}
}
} catch (e) {
debugPrint('❌ [NetworkScanner] Error getting network interfaces: $e');
debugPrint('❌ [NetworkScanner] Error getting network range: $e');
}
return ips;
return [];
}
/// Check if an IP has an SSE server running
Future<DiscoveredServer?> _checkServer(String ip, int port) async {
/// Try a raw TCP connect to check if the MeshCore TCP server is listening.
Future<DiscoveredServer?> _checkDevice(String ip, int port) async {
final sw = Stopwatch()..start();
Socket? socket;
try {
final stopwatch = Stopwatch()..start();
final url = Uri.parse('http://$ip:$port/api/status');
final response = await http.get(url).timeout(scanTimeout);
stopwatch.stop();
if (response.statusCode == 200) {
debugPrint('✅ [NetworkScanner] Found server at $ip:$port (${stopwatch.elapsedMilliseconds}ms)');
return DiscoveredServer(
ipAddress: ip,
port: port,
responseTime: stopwatch.elapsedMilliseconds,
);
}
} on TimeoutException {
// Timeout - server not responding, ignore
socket = await Socket.connect(
ip,
port,
timeout: connectTimeout,
);
sw.stop();
debugPrint(
'✅ [NetworkScanner] Found device at $ip:$port (${sw.elapsedMilliseconds}ms)');
return DiscoveredServer(
ipAddress: ip,
port: port,
responseTime: sw.elapsedMilliseconds,
);
} on SocketException {
// Connection refused - no server at this IP, ignore
// Connection refused or timed out — no device here
} catch (e) {
// Other errors - ignore
debugPrint('⚠️ [NetworkScanner] Error checking $ip:$port - $e');
debugPrint('⚠️ [NetworkScanner] Error checking $ip:$port$e');
} finally {
socket?.destroy();
}
return null;
}
/// Discover servers using Bonjour/mDNS
Future<List<DiscoveredServer>> _discoverViaBonjourAsync({int? port}) async {
// ── mDNS discovery ─────────────────────────────────────────────────────────
Future<List<DiscoveredServer>> _discoverViaMdns({int? port}) async {
final scanPort = port ?? defaultPort;
final List<DiscoveredServer> discoveredServers = [];
final found = <DiscoveredServer>[];
try {
debugPrint('🔍 [NetworkScanner] Starting Bonjour discovery for $serviceType...');
// Get local IP addresses to filter out
debugPrint('🔍 [NetworkScanner] mDNS discovery for $serviceType...');
final localIps = await _getLocalIpAddresses();
debugPrint('📍 [NetworkScanner] Local IPs: ${localIps.join(", ")}');
// Start discovery with IP lookup
_activeDiscovery = await startDiscovery(
serviceType,
ipLookupType: IpLookupType.any,
);
// Wait for discovery to find services
await Future.delayed(bonjourTimeout);
// Process discovered services
final services = _activeDiscovery?.services ?? [];
debugPrint('📡 [NetworkScanner] Bonjour found ${services.length} services');
for (final service in services) {
if (service.addresses != null && service.addresses!.isNotEmpty) {
for (final address in service.addresses!) {
// Skip if this is a local IP address
if (localIps.contains(address.address)) {
debugPrint('⏭️ [NetworkScanner] Skipping local IP: ${address.address}');
continue;
}
// Verify service is actually reachable
final result = await _checkServer(
address.address,
service.port ?? scanPort,
);
if (result != null) {
discoveredServers.add(result);
onServerDiscovered?.call(result);
}
for (final service in _activeDiscovery?.services ?? []) {
for (final addr in service.addresses ?? []) {
if (localIps.contains(addr.address)) continue;
final result =
await _checkDevice(addr.address, service.port ?? scanPort);
if (result != null) {
found.add(result);
onServerDiscovered?.call(result);
}
}
}
// Stop discovery
await stopDiscovery(_activeDiscovery!);
_activeDiscovery = null;
debugPrint('✅ [NetworkScanner] Bonjour discovery complete. Found ${discoveredServers.length} servers.');
debugPrint(
'✅ [NetworkScanner] mDNS done. Found ${found.length} devices.');
} catch (e) {
debugPrint('⚠️ [NetworkScanner] Bonjour discovery failed: $e');
debugPrint('⚠️ [NetworkScanner] mDNS failed: $e');
if (_activeDiscovery != null) {
try {
await stopDiscovery(_activeDiscovery!);
@@ -216,132 +158,70 @@ class NetworkScannerService {
}
}
return discoveredServers;
return found;
}
/// Scan the local network for SSE servers
/// First tries Bonjour/mDNS, then falls back to port scanning if nothing found
Future<List<DiscoveredServer>> scan({int? port}) async {
if (_isScanning) {
debugPrint('⚠️ [NetworkScanner] Scan already in progress');
return [];
}
// ── Port scan fallback ─────────────────────────────────────────────────────
_isScanning = true;
Future<List<DiscoveredServer>> _scanByPort({int? port}) async {
final scanPort = port ?? defaultPort;
List<DiscoveredServer> discoveredServers = [];
final found = <DiscoveredServer>[];
try {
// Try Bonjour/mDNS discovery first
discoveredServers = await _discoverViaBonjourAsync(port: scanPort);
final localIps = await _getLocalIpAddresses();
final ips = await _getLocalNetworkRange();
if (ips.isEmpty) return [];
// Fall back to port scanning if Bonjour found nothing
if (discoveredServers.isEmpty) {
debugPrint('🔍 [NetworkScanner] Bonjour found nothing, falling back to port scanning...');
discoveredServers = await _scanByPortAsync(port: scanPort);
debugPrint(
'🔍 [NetworkScanner] Port scan: ${ips.length} IPs, port $scanPort');
int scanned = 0;
for (int i = 0; i < ips.length; i += parallelScans) {
final batch = ips.skip(i).take(parallelScans).toList();
final results =
await Future.wait(batch.map((ip) => _checkDevice(ip, scanPort)));
for (final result in results) {
if (result != null && !localIps.contains(result.ipAddress)) {
found.add(result);
onServerDiscovered?.call(result);
}
}
// Cache the results
_cachedServers = discoveredServers;
} catch (e) {
debugPrint('❌ [NetworkScanner] Scan error: $e');
scanned += batch.length;
onProgressUpdate?.call(scanned, ips.length);
}
return found;
}
// ── Public API ─────────────────────────────────────────────────────────────
/// Scan for MeshCore WiFi devices. Tries mDNS first, falls back to port scan.
Future<List<DiscoveredServer>> scan({int? port}) async {
if (_isScanning) return [];
_isScanning = true;
try {
var found = await _discoverViaMdns(port: port);
if (found.isEmpty) {
debugPrint(
'🔍 [NetworkScanner] mDNS found nothing, falling back to port scan');
found = await _scanByPort(port: port);
}
_cachedServers = found;
return found;
} finally {
_isScanning = false;
}
return discoveredServers;
}
/// Fallback port scanning method
Future<List<DiscoveredServer>> _scanByPortAsync({int? port}) async {
final scanPort = port ?? defaultPort;
final List<DiscoveredServer> discoveredServers = [];
try {
debugPrint('🔍 [NetworkScanner] Starting port scan on port $scanPort...');
// Get local IP addresses to filter out
final localIps = await _getLocalIpAddresses();
debugPrint('📍 [NetworkScanner] Local IPs: ${localIps.join(", ")}');
final ips = await _getLocalNetworkRange();
if (ips.isEmpty) {
debugPrint('⚠️ [NetworkScanner] No network interfaces found');
return [];
}
debugPrint('📊 [NetworkScanner] Scanning ${ips.length} IPs with $parallelScans parallel connections');
int scannedCount = 0;
// Scan in batches of 20 parallel connections
for (int i = 0; i < ips.length; i += parallelScans) {
final batch = ips.skip(i).take(parallelScans).toList();
// Scan batch in parallel
final futures = batch.map((ip) => _checkServer(ip, scanPort)).toList();
final results = await Future.wait(futures);
// Collect discovered servers (excluding local IPs)
for (int j = 0; j < results.length; j++) {
final result = results[j];
if (result != null) {
// Skip if this is a local IP address
if (localIps.contains(result.ipAddress)) {
debugPrint('⏭️ [NetworkScanner] Skipping local IP: ${result.ipAddress}');
continue;
}
discoveredServers.add(result);
onServerDiscovered?.call(result);
}
}
scannedCount += batch.length;
onProgressUpdate?.call(scannedCount, ips.length);
}
debugPrint('✅ [NetworkScanner] Port scan complete. Found ${discoveredServers.length} servers.');
} catch (e) {
debugPrint('❌ [NetworkScanner] Port scan error: $e');
}
return discoveredServers;
}
/// Clear cached results (useful for forcing a fresh scan)
void clearCache() {
_cachedServers = [];
debugPrint('🗑️ [NetworkScanner] Cache cleared');
}
/// Stop ongoing scan
void stopScan() {
if (_isScanning) {
debugPrint('🛑 [NetworkScanner] Stopping scan...');
_isScanning = false;
}
}
/// Verify that a previously discovered server is still available
/// Returns true if server is reachable, false otherwise
/// Verify a previously discovered device is still reachable.
Future<bool> verifyServer(DiscoveredServer server) async {
try {
debugPrint('🔍 [NetworkScanner] Verifying server at ${server.ipAddress}:${server.port}...');
final result = await _checkServer(server.ipAddress, server.port);
if (result != null) {
debugPrint('✅ [NetworkScanner] Server verified at ${server.ipAddress}:${server.port}');
return true;
} else {
debugPrint('❌ [NetworkScanner] Server no longer available at ${server.ipAddress}:${server.port}');
return false;
}
} catch (e) {
debugPrint('❌ [NetworkScanner] Server verification failed: $e');
return false;
}
final result = await _checkDevice(server.ipAddress, server.port);
return result != null;
}
void clearCache() => _cachedServers = [];
void stopScan() => _isScanning = false;
}

View File

@@ -0,0 +1,146 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import '../models/ble_packet_log.dart';
class StoredPacketCapture {
final DateTime timestamp;
final String direction;
final int? responseCode;
final String? description;
final String rawBase64;
final int rawSize;
final double? snrDb;
final int? rssiDbm;
const StoredPacketCapture({
required this.timestamp,
required this.direction,
required this.responseCode,
required this.description,
required this.rawBase64,
required this.rawSize,
required this.snrDb,
required this.rssiDbm,
});
Map<String, dynamic> toJson() {
return {
'ts': timestamp.millisecondsSinceEpoch,
'dir': direction,
'code': responseCode,
'desc': description,
'raw': rawBase64,
'size': rawSize,
'snr': snrDb,
'rssi': rssiDbm,
};
}
static StoredPacketCapture fromJson(Map<String, dynamic> json) {
return StoredPacketCapture(
timestamp: DateTime.fromMillisecondsSinceEpoch((json['ts'] as num).toInt()),
direction: (json['dir'] as String?) ?? 'rx',
responseCode: (json['code'] as num?)?.toInt(),
description: json['desc'] as String?,
rawBase64: (json['raw'] as String?) ?? '',
rawSize: (json['size'] as num?)?.toInt() ?? 0,
snrDb: (json['snr'] as num?)?.toDouble(),
rssiDbm: (json['rssi'] as num?)?.toInt(),
);
}
}
/// Durable storage for raw BLE packets so future features can consume
/// historical packet bytes across app restarts.
class PacketCaptureStorageService {
static const String _fileName = 'packet_captures.jsonl';
static const int _maxStoredPackets = 20000;
File? _file;
Future<File> _resolveFile() async {
if (_file != null) return _file!;
final dir = await getApplicationSupportDirectory();
final file = File('${dir.path}/$_fileName');
if (!await file.exists()) {
await file.create(recursive: true);
}
_file = file;
return file;
}
Future<void> appendLogs(List<BlePacketLog> logs) async {
if (logs.isEmpty) return;
try {
final file = await _resolveFile();
final sink = file.openWrite(mode: FileMode.append);
for (final log in logs) {
final row = StoredPacketCapture(
timestamp: log.timestamp,
direction: log.direction.name,
responseCode: log.responseCode,
description: log.description,
rawBase64: base64Encode(log.rawData),
rawSize: log.rawData.length,
snrDb: log.logRxDataInfo?.snrDb,
rssiDbm: log.logRxDataInfo?.rssiDbm,
);
sink.writeln(jsonEncode(row.toJson()));
}
await sink.flush();
await sink.close();
await _pruneIfNeeded(file);
} catch (e) {
debugPrint('❌ [PacketCaptureStorage] Failed to append logs: $e');
}
}
Future<List<StoredPacketCapture>> loadRecent({int limit = 500}) async {
try {
final file = await _resolveFile();
if (!await file.exists()) return const [];
final lines = await file.readAsLines();
if (lines.isEmpty) return const [];
final start = lines.length > limit ? lines.length - limit : 0;
return lines
.sublist(start)
.where((l) => l.trim().isNotEmpty)
.map((l) => StoredPacketCapture.fromJson(jsonDecode(l) as Map<String, dynamic>))
.toList();
} catch (e) {
debugPrint('❌ [PacketCaptureStorage] Failed to load recent logs: $e');
return const [];
}
}
Future<int> count() async {
try {
final file = await _resolveFile();
if (!await file.exists()) return 0;
final lines = await file.readAsLines();
return lines.where((l) => l.trim().isNotEmpty).length;
} catch (_) {
return 0;
}
}
Future<void> clear() async {
try {
final file = await _resolveFile();
if (await file.exists()) {
await file.writeAsString('');
}
} catch (e) {
debugPrint('❌ [PacketCaptureStorage] Failed to clear logs: $e');
}
}
Future<void> _pruneIfNeeded(File file) async {
final lines = await file.readAsLines();
if (lines.length <= _maxStoredPackets) return;
final keep = lines.sublist(lines.length - _maxStoredPackets);
await file.writeAsString('${keep.join('\n')}\n');
}
}

View File

@@ -1,667 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as io_client;
import '../models/message.dart';
import '../models/contact.dart';
import 'package:latlong2/latlong.dart';
/// SSE Client Service
///
/// Connects to a remote SSE server to receive messages and contacts in real-time.
/// This enables multiple app instances to share a single MeshCore BLE device
/// without direct BLE connections.
class SseClientService {
String? _serverUrl;
String? _authToken;
http.Client? _httpClient;
StreamSubscription? _messageSubscription;
StreamSubscription? _contactSubscription;
bool _isConnected = false;
bool _isConnecting = false;
bool _hasConnectedBefore =
false; // Track if we've ever successfully connected
Timer? _reconnectTimer;
Timer? _heartbeatTimer;
int _reconnectAttempts = 0;
static const int _maxReconnectAttempts = 10;
static const Duration _reconnectDelay = Duration(seconds: 5);
/// Callback for when a message is received
Function(Message)? onMessageReceived;
/// Callback for when a contact is received
Function(Contact)? onContactReceived;
/// Callback for connection state changes
Function(bool isConnected)? onConnectionStateChanged;
/// Callback for errors
Function(String error)? onError;
/// Check if client is connected
bool get isConnected => _isConnected;
/// Check if client is currently connecting
bool get isConnecting => _isConnecting;
/// Get current reconnection attempt number
int get reconnectionAttempts => _reconnectAttempts;
/// Get maximum reconnection attempts
int get maxReconnectionAttempts => _maxReconnectAttempts;
/// Get server URL
String? get serverUrl => _serverUrl;
/// Connect to SSE server
Future<void> connect({required String serverUrl, String? authToken}) async {
if (_isConnected) {
debugPrint('⚠️ [SseClient] Already connected');
return;
}
_serverUrl = serverUrl;
_authToken = authToken;
_isConnecting = true;
debugPrint(
'🔌 [SseClient] Connecting to $serverUrl (attempt ${_reconnectAttempts + 1}/$_maxReconnectAttempts)',
);
try {
// Create a new HTTP client with custom configuration for SSE streaming
// Using IOClient with custom HttpClient for better control over connection settings
final ioHttpClient = io.HttpClient();
ioHttpClient.connectionTimeout = const Duration(seconds: 10);
ioHttpClient.idleTimeout = const Duration(
hours: 1,
); // Keep SSE connections alive
_httpClient = io_client.IOClient(ioHttpClient);
// Test server availability
await _checkServerStatus();
// Fetch initial message history
await _fetchMessageHistory();
// Fetch initial contact list
await _fetchContacts();
// Subscribe to SSE streams
debugPrint('🔗 [SseClient] Subscribing to message stream...');
debugPrint(
'🔗 [SseClient] Using HTTP client type: ${_httpClient.runtimeType}',
);
await _subscribeToMessages();
debugPrint('🔗 [SseClient] Subscribing to contact stream...');
await _subscribeToContacts();
debugPrint('🔗 [SseClient] All subscriptions complete');
_isConnected = true;
_isConnecting = false;
_hasConnectedBefore = true; // Mark that we've successfully connected
_reconnectAttempts = 0;
debugPrint('🔔 [SseClient] Calling onConnectionStateChanged(true)');
onConnectionStateChanged?.call(true);
// Start heartbeat to detect connection loss
_startHeartbeat();
debugPrint('✅ [SseClient] Connected successfully');
} catch (e) {
_isConnecting = false;
_httpClient?.close();
_httpClient = null;
debugPrint('❌ [SseClient] Connection failed: $e');
onError?.call('Connection failed: $e');
// Only auto-reconnect if we've successfully connected before
// Initial connection failures should be handled by the user
if (_hasConnectedBefore) {
_scheduleReconnect();
}
}
}
/// Disconnect from SSE server
Future<void> disconnect() async {
debugPrint('🔌 [SseClient] Disconnecting...');
_isConnected = false;
_isConnecting = false;
_hasConnectedBefore = false; // Reset on manual disconnect
_reconnectTimer?.cancel();
_heartbeatTimer?.cancel();
await _messageSubscription?.cancel();
await _contactSubscription?.cancel();
_httpClient?.close();
_serverUrl = null;
_authToken = null;
_httpClient = null;
onConnectionStateChanged?.call(false);
debugPrint('✅ [SseClient] Disconnected');
}
/// Check server status
Future<void> _checkServerStatus() async {
final url = Uri.parse('$_serverUrl/api/status');
try {
final response = await http
.get(url, headers: _getHeaders())
.timeout(const Duration(seconds: 5));
if (response.statusCode != 200) {
throw Exception('Server returned ${response.statusCode}');
}
final data = jsonDecode(response.body);
debugPrint('📊 [SseClient] Server status: ${data['status']}');
debugPrint(' Connected clients: ${data['connectedClients']}');
debugPrint(' Messages: ${data['messageCount']}');
debugPrint(' Contacts: ${data['contactCount']}');
} catch (e) {
// Wrap the error with more user-friendly message
throw Exception(_formatConnectionError(e));
}
}
/// Format connection error to be more user-friendly
String _formatConnectionError(dynamic error) {
final errorStr = error.toString();
// Extract the actual server URL being connected to
final serverUri = Uri.tryParse(_serverUrl ?? '');
final host = serverUri?.host ?? 'unknown';
final port = serverUri?.port ?? 0;
if (errorStr.contains('Connection refused')) {
return 'Server not available at $host:$port. The server may be offline or not running.';
} else if (errorStr.contains('TimeoutException') ||
errorStr.contains('timed out')) {
return 'Connection to $host:$port timed out. Check your network connection.';
} else if (errorStr.contains('SocketException')) {
return 'Network error connecting to $host:$port. Check your network connection.';
} else if (errorStr.contains('Failed host lookup')) {
return 'Could not resolve hostname: $host';
}
// Return the original error if we can't make it more user-friendly
return errorStr;
}
/// Fetch message history on connect
Future<void> _fetchMessageHistory() async {
try {
final url = Uri.parse('$_serverUrl/api/messages/history');
final response = await http
.get(url, headers: _getHeaders())
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception(
'Failed to fetch message history: ${response.statusCode}',
);
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
final messages = data['messages'] as List;
debugPrint(
'📥 [SseClient] Received ${messages.length} messages from history',
);
for (final msgJson in messages) {
try {
final message = _messageFromJson(msgJson);
onMessageReceived?.call(message);
} catch (e) {
debugPrint('⚠️ [SseClient] Failed to parse message: $e');
}
}
} catch (e) {
debugPrint('❌ [SseClient] Error fetching message history: $e');
// Don't throw - continue with connection even if history fetch fails
}
}
/// Fetch contacts on connect
Future<void> _fetchContacts() async {
try {
final url = Uri.parse('$_serverUrl/api/contacts');
final response = await http
.get(url, headers: _getHeaders())
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception('Failed to fetch contacts: ${response.statusCode}');
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
final contacts = data['contacts'] as List;
debugPrint('📥 [SseClient] Received ${contacts.length} contacts');
for (final contactJson in contacts) {
try {
final contact = _contactFromJson(contactJson);
onContactReceived?.call(contact);
} catch (e) {
debugPrint('⚠️ [SseClient] Failed to parse contact: $e');
}
}
} catch (e) {
debugPrint('❌ [SseClient] Error fetching contacts: $e');
// Don't throw - continue with connection even if contacts fetch fails
}
}
/// Subscribe to SSE message stream
Future<void> _subscribeToMessages() async {
try {
if (_httpClient == null) {
throw Exception('HTTP client not initialized');
}
debugPrint('📡 [SseClient] Creating message stream request...');
final url = Uri.parse('$_serverUrl/sse/messages');
final request = http.Request('GET', url);
request.headers.addAll(_getHeaders());
request.headers['Accept'] = 'text/event-stream';
request.headers['Cache-Control'] = 'no-cache';
debugPrint('📡 [SseClient] Sending message stream request to $url');
debugPrint('📡 [SseClient] Request headers: ${request.headers}');
final streamedResponse = await _httpClient!
.send(request)
.timeout(
const Duration(seconds: 10),
onTimeout: () {
debugPrint('❌ [SseClient] Timeout waiting for response headers');
throw TimeoutException(
'Message stream connection timed out after 10 seconds',
);
},
);
debugPrint(
'📡 [SseClient] Received response with status: ${streamedResponse.statusCode}',
);
debugPrint(
'📡 [SseClient] Response headers: ${streamedResponse.headers}',
);
debugPrint(
'📡 [SseClient] Response content length: ${streamedResponse.contentLength}',
);
debugPrint(
'📡 [SseClient] Response is redirect: ${streamedResponse.isRedirect}',
);
if (streamedResponse.statusCode != 200) {
throw Exception(
'SSE messages subscription failed: ${streamedResponse.statusCode}',
);
}
debugPrint(
'📡 [SseClient] Message stream response received, status: ${streamedResponse.statusCode}',
);
debugPrint('📡 [SseClient] Setting up stream listener...');
_messageSubscription = streamedResponse.stream
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(
(line) {
debugPrint('📨 [SseClient] Received line: "$line"');
_handleSseLine(line, 'message');
},
onError: (error, stackTrace) {
debugPrint('❌ [SseClient] Message stream error: $error');
debugPrint(' Stack trace: $stackTrace');
_handleDisconnect();
},
onDone: () {
debugPrint(
'⚠️ [SseClient] Message stream closed (onDone called)',
);
_handleDisconnect();
},
cancelOnError: false,
);
debugPrint('✅ [SseClient] Message stream listener set up successfully');
} catch (e) {
debugPrint('❌ [SseClient] Error subscribing to message stream: $e');
rethrow;
}
}
/// Subscribe to SSE contact stream
Future<void> _subscribeToContacts() async {
try {
if (_httpClient == null) {
throw Exception('HTTP client not initialized');
}
debugPrint('📡 [SseClient] Creating contact stream request...');
final url = Uri.parse('$_serverUrl/sse/contacts');
final request = http.Request('GET', url);
request.headers.addAll(_getHeaders());
request.headers['Accept'] = 'text/event-stream';
request.headers['Cache-Control'] = 'no-cache';
debugPrint('📡 [SseClient] Sending contact stream request to $url');
final streamedResponse = await _httpClient!
.send(request)
.timeout(
const Duration(seconds: 10),
onTimeout: () {
throw TimeoutException(
'Contact stream connection timed out after 10 seconds',
);
},
);
if (streamedResponse.statusCode != 200) {
throw Exception(
'SSE contacts subscription failed: ${streamedResponse.statusCode}',
);
}
debugPrint(
'📡 [SseClient] Contact stream response received, status: ${streamedResponse.statusCode}',
);
debugPrint('📡 [SseClient] Setting up contact stream listener...');
_contactSubscription = streamedResponse.stream
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(
(line) {
debugPrint('📨 [SseClient] Received contact line: "$line"');
_handleSseLine(line, 'contact');
},
onError: (error, stackTrace) {
debugPrint('❌ [SseClient] Contact stream error: $error');
debugPrint(' Stack trace: $stackTrace');
_handleDisconnect();
},
onDone: () {
debugPrint(
'⚠️ [SseClient] Contact stream closed (onDone called)',
);
_handleDisconnect();
},
cancelOnError: false,
);
debugPrint('✅ [SseClient] Contact stream listener set up successfully');
} catch (e) {
debugPrint('❌ [SseClient] Error subscribing to contact stream: $e');
rethrow;
}
}
/// Handle SSE line
String _eventType = '';
void _handleSseLine(String line, String streamType) {
if (line.isEmpty) {
// Event complete, reset
_eventType = '';
return;
}
if (line.startsWith('event:')) {
_eventType = line.substring(6).trim();
} else if (line.startsWith('data:')) {
final jsonData = line.substring(5).trim();
try {
final data = jsonDecode(jsonData) as Map<String, dynamic>;
if (streamType == 'message' && _eventType == 'message') {
final message = _messageFromJson(data);
onMessageReceived?.call(message);
} else if (streamType == 'contact' && _eventType == 'contact') {
final contact = _contactFromJson(data);
onContactReceived?.call(contact);
}
} catch (e) {
debugPrint('⚠️ [SseClient] Failed to parse SSE data: $e');
}
}
}
/// Handle disconnect
void _handleDisconnect() {
if (!_isConnected) return;
_isConnected = false;
onConnectionStateChanged?.call(false);
_scheduleReconnect();
}
/// Schedule reconnection attempt
void _scheduleReconnect() {
if (_reconnectAttempts >= _maxReconnectAttempts) {
debugPrint('❌ [SseClient] Max reconnection attempts reached');
onError?.call('Max reconnection attempts reached');
return;
}
_reconnectAttempts++;
final delay = _reconnectDelay * _reconnectAttempts;
debugPrint(
'🔄 [SseClient] Scheduling reconnect attempt $_reconnectAttempts in ${delay.inSeconds}s',
);
_reconnectTimer?.cancel();
_reconnectTimer = Timer(delay, () {
if (_serverUrl != null) {
connect(serverUrl: _serverUrl!, authToken: _authToken);
}
});
}
/// Start heartbeat to detect connection loss
void _startHeartbeat() {
_heartbeatTimer?.cancel();
_heartbeatTimer = Timer.periodic(const Duration(seconds: 30), (
timer,
) async {
try {
await _checkServerStatus();
} catch (e) {
debugPrint('⚠️ [SseClient] Heartbeat failed: $e');
_handleDisconnect();
}
});
}
/// Send message to server
Future<bool> sendMessage({
required String recipientPublicKey,
required String text,
}) async {
if (!_isConnected || _serverUrl == null) {
throw Exception('Not connected to server');
}
try {
final url = Uri.parse('$_serverUrl/api/messages');
final response = await http
.post(
url,
headers: {..._getHeaders(), 'Content-Type': 'application/json'},
body: jsonEncode({
'recipientPublicKey': recipientPublicKey,
'text': text,
}),
)
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception('Send message failed: ${response.statusCode}');
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
return data['success'] as bool? ?? false;
} catch (e) {
debugPrint('❌ [SseClient] Error sending message: $e');
rethrow;
}
}
/// Send channel message to server
Future<void> sendChannelMessage({
required int channelIdx,
required String text,
}) async {
if (!_isConnected || _serverUrl == null) {
throw Exception('Not connected to server');
}
try {
final url = Uri.parse('$_serverUrl/api/messages/channel');
final response = await http
.post(
url,
headers: {..._getHeaders(), 'Content-Type': 'application/json'},
body: jsonEncode({'channelIdx': channelIdx, 'text': text}),
)
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception('Send channel message failed: ${response.statusCode}');
}
} catch (e) {
debugPrint('❌ [SseClient] Error sending channel message: $e');
rethrow;
}
}
/// Request contact sync
Future<void> syncContacts() async {
if (!_isConnected || _serverUrl == null) {
throw Exception('Not connected to server');
}
try {
final url = Uri.parse('$_serverUrl/api/contacts/sync');
final response = await http
.post(url, headers: _getHeaders())
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception('Contact sync failed: ${response.statusCode}');
}
debugPrint('✅ [SseClient] Contact sync requested');
} catch (e) {
debugPrint('❌ [SseClient] Error syncing contacts: $e');
rethrow;
}
}
/// Get headers for HTTP requests
Map<String, String> _getHeaders() {
final headers = <String, String>{};
if (_authToken != null) {
headers['Authorization'] = 'Bearer $_authToken';
}
return headers;
}
/// Convert JSON to Message
Message _messageFromJson(Map<String, dynamic> json) {
return Message(
id: json['id'] as String,
messageType: MessageType.values.firstWhere(
(e) => e.name == json['messageType'],
orElse: () => MessageType.contact,
),
senderPublicKeyPrefix: json['senderPublicKeyPrefix'] != null
? Uint8List.fromList(
(json['senderPublicKeyPrefix'] as List).cast<int>(),
)
: null,
channelIdx: json['channelIdx'] as int?,
pathLen: json['pathLen'] as int,
textType: MessageTextType.fromValue(json['textType'] as int),
senderTimestamp: json['senderTimestamp'] as int,
text: json['text'] as String,
isSarMarker: json['isSarMarker'] as bool? ?? false,
sarGpsCoordinates: json['sarGpsCoordinates'] != null
? LatLng(
(json['sarGpsCoordinates']['latitude'] as num).toDouble(),
(json['sarGpsCoordinates']['longitude'] as num).toDouble(),
)
: null,
sarNotes: json['sarNotes'] as String?,
sarCustomEmoji: json['sarCustomEmoji'] as String?,
sarColorIndex: json['sarColorIndex'] as int?,
receivedAt: DateTime.parse(json['receivedAt'] as String),
senderName: json['senderName'] as String?,
deliveryStatus: MessageDeliveryStatus.values.firstWhere(
(e) => e.name == json['deliveryStatus'],
orElse: () => MessageDeliveryStatus.received,
),
expectedAckTag: json['expectedAckTag'] as int?,
suggestedTimeoutMs: json['suggestedTimeoutMs'] as int?,
roundTripTimeMs: json['roundTripTimeMs'] as int?,
deliveredAt: json['deliveredAt'] != null
? DateTime.parse(json['deliveredAt'] as String)
: null,
recipientPublicKey: json['recipientPublicKey'] != null
? Uint8List.fromList((json['recipientPublicKey'] as List).cast<int>())
: null,
retryAttempt: json['retryAttempt'] as int? ?? 0,
lastRetryAt: json['lastRetryAt'] != null
? DateTime.parse(json['lastRetryAt'] as String)
: null,
usedFloodFallback: json['usedFloodFallback'] as bool? ?? false,
isRead: json['isRead'] as bool? ?? false,
echoCount: json['echoCount'] as int? ?? 0,
firstEchoAt: json['firstEchoAt'] != null
? DateTime.parse(json['firstEchoAt'] as String)
: null,
lastEchoSnrRaw: json['lastEchoSnrRaw'] as int?,
lastEchoRssiDbm: json['lastEchoRssiDbm'] as int?,
lastEchoAt: json['lastEchoAt'] != null
? DateTime.parse(json['lastEchoAt'] as String)
: null,
isDrawing: json['isDrawing'] as bool? ?? false,
drawingId: json['drawingId'] as String?,
);
}
/// Convert JSON to Contact
Contact _contactFromJson(Map<String, dynamic> json) {
return Contact(
publicKey: Uint8List.fromList((json['publicKey'] as List).cast<int>()),
type: ContactType.fromValue(json['type'] as int),
flags: json['flags'] as int,
outPathLen: json['outPathLen'] as int,
outPath: Uint8List.fromList((json['outPath'] as List).cast<int>()),
advName: json['advName'] as String,
lastAdvert: json['lastAdvert'] as int,
advLat: json['advLat'] as int,
advLon: json['advLon'] as int,
lastMod: json['lastMod'] as int,
);
}
/// Dispose resources
void dispose() {
disconnect();
}
}

View File

@@ -5,16 +5,19 @@ import '../models/update_info.dart';
import 'build_info_service.dart';
/// Service for checking if a new app version is available
/// Compares current build's commit hash with latest manifest from server
/// Compares current build's commit hash with latest GitHub release
class UpdateCheckerService {
static final UpdateCheckerService _instance = UpdateCheckerService._internal();
static final UpdateCheckerService _instance =
UpdateCheckerService._internal();
factory UpdateCheckerService() => _instance;
UpdateCheckerService._internal();
final BuildInfoService _buildInfoService = BuildInfoService();
// Manifest URL for the latest unstable build
static const String _manifestUrl = 'https://meshcore-sar.dz0ny.dev/unstable/latest/manifest.json';
static const String _repoOwner = 'dz0ny';
static const String _repoName = 'meshcore-sar';
static const String _latestReleaseUrl =
'https://api.github.com/repos/$_repoOwner/$_repoName/releases/latest';
/// Check if an update is available
/// Returns UpdateInfo with availability status and download URL if available
@@ -25,61 +28,78 @@ class UpdateCheckerService {
// Skip check for dev builds (local development)
if (currentCommitHash == 'dev' || currentCommitHash == 'unknown') {
debugPrint('[UpdateChecker] Skipping update check for dev/unknown build');
debugPrint(
'[UpdateChecker] Skipping update check for dev/unknown build',
);
return UpdateInfo.noUpdate(currentCommitHash);
}
debugPrint('[UpdateChecker] Current commit hash: $currentCommitHash');
debugPrint('[UpdateChecker] Fetching latest manifest from: $_manifestUrl');
// Fetch manifest from server
final response = await http.get(
Uri.parse(_manifestUrl),
headers: {'Accept': 'application/json'},
).timeout(
const Duration(seconds: 10),
onTimeout: () {
debugPrint('[UpdateChecker] Manifest fetch timed out');
throw Exception('Manifest fetch timed out');
},
debugPrint(
'[UpdateChecker] Fetching latest release from: $_latestReleaseUrl',
);
// Fetch latest release from GitHub
final response = await http
.get(
Uri.parse(_latestReleaseUrl),
headers: {
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
},
)
.timeout(
const Duration(seconds: 10),
onTimeout: () {
debugPrint('[UpdateChecker] Latest release fetch timed out');
throw Exception('Latest release fetch timed out');
},
);
if (response.statusCode != 200) {
debugPrint('[UpdateChecker] Failed to fetch manifest: ${response.statusCode}');
debugPrint(
'[UpdateChecker] Failed to fetch release: ${response.statusCode}',
);
return UpdateInfo.noUpdate(currentCommitHash);
}
// Parse manifest JSON
final Map<String, dynamic> manifest = json.decode(response.body);
final latestCommitHash = manifest['commit'] as String?;
final commitShort = manifest['commit_short'] as String?;
final buildId = manifest['build_id'] as String?;
final timestamp = manifest['timestamp'] as String?;
final artifacts = manifest['artifacts'] as List<dynamic>?;
// Parse release JSON
final Map<String, dynamic> release = json.decode(response.body);
final tagName = release['tag_name'] as String?;
final targetCommitish = release['target_commitish'] as String?;
final publishedAt = release['published_at'] as String?;
final assets = release['assets'] as List<dynamic>?;
if (latestCommitHash == null || commitShort == null) {
debugPrint('[UpdateChecker] Invalid manifest: missing commit information');
if (tagName == null) {
debugPrint('[UpdateChecker] Invalid release: missing tag_name');
return UpdateInfo.noUpdate(currentCommitHash);
}
debugPrint('[UpdateChecker] Latest commit hash: $latestCommitHash');
debugPrint('[UpdateChecker] Latest commit short: $commitShort');
debugPrint('[UpdateChecker] Latest release tag: $tagName');
if (targetCommitish != null && targetCommitish.isNotEmpty) {
debugPrint(
'[UpdateChecker] Release target commitish: $targetCommitish',
);
}
// Compare commit hashes
// Current hash might be full SHA or short (7 chars)
// Latest from manifest is full SHA
final isUpdateAvailable = !_compareCommitHashes(currentCommitHash, latestCommitHash);
final isUpdateAvailable = await _isUpdateAvailable(
currentCommitHash: currentCommitHash,
releaseTag: tagName,
targetCommitish: targetCommitish,
);
if (!isUpdateAvailable) {
debugPrint('[UpdateChecker] No update available (same commit)');
debugPrint('[UpdateChecker] No update available');
return UpdateInfo.noUpdate(currentCommitHash);
}
// Find Android APK in artifacts
final String? apkUrl = _findAndroidApkUrl(artifacts);
// Find Android APK in release assets
final String? apkUrl = _findAndroidApkUrl(assets);
if (apkUrl == null) {
debugPrint('[UpdateChecker] Update available but no APK found in artifacts');
debugPrint(
'[UpdateChecker] Update available but no APK found in artifacts',
);
return UpdateInfo.noUpdate(currentCommitHash);
}
@@ -87,10 +107,10 @@ class UpdateCheckerService {
return UpdateInfo.available(
currentCommitHash: currentCommitHash,
latestCommitHash: commitShort,
latestCommitHash: _formatLatestVersion(targetCommitish, tagName),
downloadUrl: apkUrl,
buildId: buildId,
timestamp: timestamp,
buildId: tagName,
timestamp: publishedAt,
);
} catch (e) {
debugPrint('[UpdateChecker] Error checking for update: $e');
@@ -118,15 +138,94 @@ class UpdateCheckerService {
return false;
}
/// Find Android APK URL in artifacts list
String? _findAndroidApkUrl(List<dynamic>? artifacts) {
if (artifacts == null || artifacts.isEmpty) return null;
Future<bool> _isUpdateAvailable({
required String currentCommitHash,
required String releaseTag,
required String? targetCommitish,
}) async {
// Prefer direct SHA compare when release target is a hash.
if (_looksLikeSha(targetCommitish)) {
return !_compareCommitHashes(currentCommitHash, targetCommitish!);
}
// Look for .apk file in artifacts
for (final artifact in artifacts) {
if (artifact is String && artifact.toLowerCase().endsWith('.apk')) {
// Construct full URL
return 'https://meshcore-sar.dz0ny.dev/unstable/latest/$artifact';
// Fallback: ask GitHub how current commit compares to the release tag.
final compareResult = await _compareWithReleaseTag(
currentCommitHash,
releaseTag,
);
if (compareResult != null) {
return compareResult;
}
// If we cannot compare, do not force update prompts.
return false;
}
Future<bool?> _compareWithReleaseTag(
String currentCommitHash,
String releaseTag,
) async {
try {
final compareUrl =
'https://api.github.com/repos/$_repoOwner/$_repoName/compare/$currentCommitHash...$releaseTag';
final response = await http
.get(
Uri.parse(compareUrl),
headers: {
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
},
)
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
debugPrint(
'[UpdateChecker] Compare API failed: ${response.statusCode}',
);
return null;
}
final Map<String, dynamic> comparison = json.decode(response.body);
final status = comparison['status'] as String?;
debugPrint('[UpdateChecker] Compare status: $status');
if (status == 'behind') return true;
if (status == 'identical' || status == 'ahead') return false;
// "diverged" means the release and current commit differ.
if (status == 'diverged') return true;
} catch (e) {
debugPrint('[UpdateChecker] Compare API error: $e');
}
return null;
}
bool _looksLikeSha(String? value) {
if (value == null) return false;
final v = value.trim();
if (v.length < 7 || v.length > 40) return false;
return RegExp(r'^[a-fA-F0-9]+$').hasMatch(v);
}
String _formatLatestVersion(String? targetCommitish, String tagName) {
if (_looksLikeSha(targetCommitish)) {
return targetCommitish!.substring(0, 7).toLowerCase();
}
return tagName;
}
/// Find Android APK URL in release assets list
String? _findAndroidApkUrl(List<dynamic>? assets) {
if (assets == null || assets.isEmpty) return null;
for (final asset in assets) {
if (asset is! Map<String, dynamic>) continue;
final name = (asset['name'] as String?)?.toLowerCase() ?? '';
if (!name.endsWith('.apk')) continue;
final browserDownloadUrl = asset['browser_download_url'] as String?;
if (browserDownloadUrl != null && browserDownloadUrl.isNotEmpty) {
return browserDownloadUrl;
}
}

View File

@@ -1,89 +1,2 @@
import 'dart:typed_data';
import 'package:codec2_flutter/codec2_flutter.dart';
import 'package:flutter/foundation.dart';
import '../utils/voice_message_parser.dart';
export 'package:codec2_flutter/codec2_flutter.dart' show Codec2Mode;
/// Maps [VoicePacketMode] to the [Codec2Mode] enum from the FFI plugin.
Codec2Mode codec2ModeFor(VoicePacketMode pktMode) {
switch (pktMode) {
case VoicePacketMode.mode3200: return Codec2Mode.mode3200;
case VoicePacketMode.mode1600: return Codec2Mode.mode1600;
case VoicePacketMode.mode1400: return Codec2Mode.mode1400;
case VoicePacketMode.mode700c: return Codec2Mode.mode700c;
case VoicePacketMode.mode1200: return Codec2Mode.mode1200;
case VoicePacketMode.mode1300: return Codec2Mode.mode1300;
case VoicePacketMode.mode2400: return Codec2Mode.mode2400;
}
}
/// Selects the [VoicePacketMode] best suited for a given LoRa radio bandwidth.
///
/// Call with [radioBandwidthHz] from the device's radio params
/// (e.g. 125000 for 125 kHz).
VoicePacketMode voiceModeForBandwidth(int radioBandwidthHz) {
if (radioBandwidthHz <= 62500) return VoicePacketMode.mode700c;
if (radioBandwidthHz <= 125000) return VoicePacketMode.mode1200;
return VoicePacketMode.mode1300;
}
/// High-level codec service that provides async Codec2 encode/decode
/// executed in a background isolate so the UI thread is never blocked.
class VoiceCodecService {
void _ensureCodec2Supported() {
if (kIsWeb ||
(defaultTargetPlatform != TargetPlatform.iOS &&
defaultTargetPlatform != TargetPlatform.android)) {
throw UnsupportedError('Codec2 is enabled only on iOS and Android.');
}
}
/// Encode [pcm] (Int16 samples, 8000 Hz mono) with [mode].
/// Returns the raw Codec2-encoded bytes.
Future<Uint8List> encode(Int16List pcm, VoicePacketMode mode) {
_ensureCodec2Supported();
return Codec2.encodeInIsolate(pcm, codec2ModeFor(mode));
}
/// Decode [codec2Bytes] back to Int16 PCM (8000 Hz mono) with [mode].
Future<Int16List> decode(Uint8List codec2Bytes, VoicePacketMode mode) {
_ensureCodec2Supported();
return Codec2.decodeInIsolate(codec2Bytes, codec2ModeFor(mode));
}
/// Decode and concatenate multiple [packets] into a single PCM Int16List.
/// Packets with null/missing entries are substituted with silence.
Future<Int16List> decodePackets(
List<VoicePacket?> packets,
VoicePacketMode mode,
) async {
_ensureCodec2Supported();
final c2Mode = codec2ModeFor(mode);
final c2 = Codec2.create(c2Mode);
final spf = c2.samplesPerFrame;
c2.destroy();
// Estimate total samples (use actual data or silence per missing packet)
final all = <Int16List>[];
for (final pkt in packets) {
if (pkt == null || pkt.codec2Data.isEmpty) {
// Silence for missing packet — duration approximated by mode
final silenceSamples = (codec2ModeFor(mode).framesPerSecond) * spf;
all.add(Int16List(silenceSamples));
} else {
final decoded = await Codec2.decodeInIsolate(pkt.codec2Data, c2Mode);
all.add(decoded);
}
}
final total = all.fold<int>(0, (sum, l) => sum + l.length);
final result = Int16List(total);
var offset = 0;
for (final chunk in all) {
result.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
return result;
}
}
export 'voice_codec_service_stub.dart'
if (dart.library.io) 'voice_codec_service_io.dart';

View File

@@ -0,0 +1,89 @@
import 'dart:typed_data';
import 'package:codec2_flutter/codec2_flutter.dart';
import 'package:flutter/foundation.dart';
import '../utils/voice_message_parser.dart';
export 'package:codec2_flutter/codec2_flutter.dart' show Codec2Mode;
/// Maps [VoicePacketMode] to the [Codec2Mode] enum from the FFI plugin.
Codec2Mode codec2ModeFor(VoicePacketMode pktMode) {
switch (pktMode) {
case VoicePacketMode.mode3200: return Codec2Mode.mode3200;
case VoicePacketMode.mode1600: return Codec2Mode.mode1600;
case VoicePacketMode.mode1400: return Codec2Mode.mode1400;
case VoicePacketMode.mode700c: return Codec2Mode.mode700c;
case VoicePacketMode.mode1200: return Codec2Mode.mode1200;
case VoicePacketMode.mode1300: return Codec2Mode.mode1300;
case VoicePacketMode.mode2400: return Codec2Mode.mode2400;
}
}
/// Selects the [VoicePacketMode] best suited for a given LoRa radio bandwidth.
///
/// Call with [radioBandwidthHz] from the device's radio params
/// (e.g. 125000 for 125 kHz).
VoicePacketMode voiceModeForBandwidth(int radioBandwidthHz) {
if (radioBandwidthHz <= 62500) return VoicePacketMode.mode700c;
if (radioBandwidthHz <= 125000) return VoicePacketMode.mode1200;
return VoicePacketMode.mode1300;
}
/// High-level codec service that provides async Codec2 encode/decode
/// executed in a background isolate so the UI thread is never blocked.
class VoiceCodecService {
void _ensureCodec2Supported() {
if (kIsWeb ||
(defaultTargetPlatform != TargetPlatform.iOS &&
defaultTargetPlatform != TargetPlatform.android)) {
throw UnsupportedError('Codec2 is enabled only on iOS and Android.');
}
}
/// Encode [pcm] (Int16 samples, 8000 Hz mono) with [mode].
/// Returns the raw Codec2-encoded bytes.
Future<Uint8List> encode(Int16List pcm, VoicePacketMode mode) {
_ensureCodec2Supported();
return Codec2.encodeInIsolate(pcm, codec2ModeFor(mode));
}
/// Decode [codec2Bytes] back to Int16 PCM (8000 Hz mono) with [mode].
Future<Int16List> decode(Uint8List codec2Bytes, VoicePacketMode mode) {
_ensureCodec2Supported();
return Codec2.decodeInIsolate(codec2Bytes, codec2ModeFor(mode));
}
/// Decode and concatenate multiple [packets] into a single PCM Int16List.
/// Packets with null/missing entries are substituted with silence.
Future<Int16List> decodePackets(
List<VoicePacket?> packets,
VoicePacketMode mode,
) async {
_ensureCodec2Supported();
final c2Mode = codec2ModeFor(mode);
final c2 = Codec2.create(c2Mode);
final spf = c2.samplesPerFrame;
c2.destroy();
// Estimate total samples (use actual data or silence per missing packet)
final all = <Int16List>[];
for (final pkt in packets) {
if (pkt == null || pkt.codec2Data.isEmpty) {
// Silence for missing packet — duration approximated by mode
final silenceSamples = (codec2ModeFor(mode).framesPerSecond) * spf;
all.add(Int16List(silenceSamples));
} else {
final decoded = await Codec2.decodeInIsolate(pkt.codec2Data, c2Mode);
all.add(decoded);
}
}
final total = all.fold<int>(0, (sum, l) => sum + l.length);
final result = Int16List(total);
var offset = 0;
for (final chunk in all) {
result.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
return result;
}
}

View File

@@ -0,0 +1,71 @@
import 'dart:typed_data';
import '../utils/voice_message_parser.dart';
/// Web/unsupported platform stub — Codec2 FFI is not available.
enum Codec2Mode {
mode3200(0),
mode2400(1),
mode1600(2),
mode1400(3),
mode1300(4),
mode1200(5),
mode700c(8);
const Codec2Mode(this.c2ModeId);
final int c2ModeId;
int get framesPerSecond => (this == mode3200 || this == mode2400) ? 50 : 25;
int get samplesPerFrame => 8000 ~/ framesPerSecond;
int get bytesPerSecond {
switch (this) {
case mode3200: return 400;
case mode700c: return 100;
case mode1200: return 150;
case mode1300: return 175;
case mode1400: return 175;
case mode1600: return 200;
case mode2400: return 300;
}
}
static const int _maxBytesPerPacket = 160;
int get packetDurationMs {
final bytesPerFrame = bytesPerSecond / framesPerSecond;
final framesPerPacket = (_maxBytesPerPacket / bytesPerFrame).floor();
return (framesPerPacket * 1000 ~/ framesPerSecond);
}
}
Codec2Mode codec2ModeFor(VoicePacketMode pktMode) {
switch (pktMode) {
case VoicePacketMode.mode3200: return Codec2Mode.mode3200;
case VoicePacketMode.mode1600: return Codec2Mode.mode1600;
case VoicePacketMode.mode1400: return Codec2Mode.mode1400;
case VoicePacketMode.mode700c: return Codec2Mode.mode700c;
case VoicePacketMode.mode1200: return Codec2Mode.mode1200;
case VoicePacketMode.mode1300: return Codec2Mode.mode1300;
case VoicePacketMode.mode2400: return Codec2Mode.mode2400;
}
}
VoicePacketMode voiceModeForBandwidth(int radioBandwidthHz) {
if (radioBandwidthHz <= 62500) return VoicePacketMode.mode700c;
if (radioBandwidthHz <= 125000) return VoicePacketMode.mode1200;
return VoicePacketMode.mode1300;
}
class VoiceCodecService {
Future<Uint8List> encode(Int16List pcm, VoicePacketMode mode) =>
Future.error(UnsupportedError('Voice not supported on web'));
Future<Int16List> decode(Uint8List codec2Bytes, VoicePacketMode mode) =>
Future.error(UnsupportedError('Voice not supported on web'));
Future<Int16List> decodePackets(
List<VoicePacket?> packets,
VoicePacketMode mode,
) =>
Future.error(UnsupportedError('Voice not supported on web'));
}

View File

@@ -18,7 +18,7 @@ class VoiceRecorderService {
/// Request microphone permission. Returns true if granted.
Future<bool> requestPermission() async {
return _recorder.hasPermission();
return _recorder.hasPermission(request: true);
}
/// Start capturing PCM audio.
@@ -38,9 +38,7 @@ class VoiceRecorderService {
throw StateError('VoiceRecorderService: already recording');
}
_controller = StreamController<Int16List>(
onCancel: () => _stopInternal(),
);
_controller = StreamController<Int16List>(onCancel: () => _stopInternal());
_isRecording = true;
_startRecording(
@@ -167,17 +165,17 @@ class _VoiceDynamicsProcessor {
required int sampleRate,
required bool enableCompressor,
required bool enableLimiter,
}) : _enableCompressor = enableCompressor,
_enableLimiter = enableLimiter,
_compressor = _SimpleCompressor(
sampleRate: sampleRate.toDouble(),
thresholdDb: -18.0,
ratio: 2.5,
attackMs: 8.0,
releaseMs: 120.0,
makeupGainDb: 4.0,
),
_limiter = _PeakLimiter(ceilingDb: -1.0);
}) : _enableCompressor = enableCompressor,
_enableLimiter = enableLimiter,
_compressor = _SimpleCompressor(
sampleRate: sampleRate.toDouble(),
thresholdDb: -18.0,
ratio: 2.5,
attackMs: 8.0,
releaseMs: 120.0,
makeupGainDb: 4.0,
),
_limiter = _PeakLimiter(ceilingDb: -1.0);
Int16List process(Int16List input) {
final output = Int16List(input.length);
@@ -214,11 +212,11 @@ class _SimpleCompressor {
required double attackMs,
required double releaseMs,
required double makeupGainDb,
}) : _thresholdDb = thresholdDb,
_ratio = ratio,
_makeupGain = math.pow(10.0, makeupGainDb / 20.0).toDouble(),
_attackCoeff = math.exp(-1.0 / (sampleRate * (attackMs / 1000.0))),
_releaseCoeff = math.exp(-1.0 / (sampleRate * (releaseMs / 1000.0)));
}) : _thresholdDb = thresholdDb,
_ratio = ratio,
_makeupGain = math.pow(10.0, makeupGainDb / 20.0).toDouble(),
_attackCoeff = math.exp(-1.0 / (sampleRate * (attackMs / 1000.0))),
_releaseCoeff = math.exp(-1.0 / (sampleRate * (releaseMs / 1000.0)));
double process(double x) {
final absX = x.abs();
@@ -266,14 +264,14 @@ class _VoiceBandPassFilter {
required int sampleRate,
required double lowCutHz,
required double highCutHz,
}) : _highPass = _BiquadFilter.highPass(
sampleRate: sampleRate.toDouble(),
cutoffHz: lowCutHz,
),
_lowPass = _BiquadFilter.lowPass(
sampleRate: sampleRate.toDouble(),
cutoffHz: highCutHz,
);
}) : _highPass = _BiquadFilter.highPass(
sampleRate: sampleRate.toDouble(),
cutoffHz: lowCutHz,
),
_lowPass = _BiquadFilter.lowPass(
sampleRate: sampleRate.toDouble(),
cutoffHz: highCutHz,
);
Int16List process(Int16List input) {
final output = Int16List(input.length);
@@ -306,11 +304,11 @@ class _BiquadFilter {
required double b2,
required double a1,
required double a2,
}) : _b0 = b0,
_b1 = b1,
_b2 = b2,
_a1 = a1,
_a2 = a2;
}) : _b0 = b0,
_b1 = b1,
_b2 = b2,
_a1 = a1,
_a2 = a2;
factory _BiquadFilter.lowPass({
required double sampleRate,

View File

@@ -0,0 +1,32 @@
class AvatarLabelHelper {
static String buildLabel(String name) {
final trimmed = name.trim();
if (trimmed.isEmpty) return '?';
if (trimmed.startsWith('#')) {
final hashBody = trimmed.substring(1).replaceAll(RegExp(r'[\s_-]+'), '');
if (hashBody.isEmpty) {
return '#';
}
return '#${_take(hashBody, 2)}'.toUpperCase();
}
final parts = trimmed
.split(RegExp(r'[\s_-]+'))
.where((part) => part.isNotEmpty)
.toList();
if (parts.length >= 2) {
final first = _take(parts[0], 1);
final second = _take(parts[1], 1);
return '$first$second'.toUpperCase();
}
return _take(trimmed, 2).toUpperCase();
}
static String _take(String value, int count) {
if (value.length <= count) return value;
return value.substring(0, count);
}
}

View File

@@ -125,7 +125,10 @@ int safeImageDataBytesForPath(int pathLen) {
? maxRawPayloadFromCommandFrame
: maxRawPayloadFromMesh;
final maxData = maxRawPayload - ImagePacket._headerLen;
return maxData.clamp(1, 255).toInt();
// Keep a safety margin below the theoretical direct-route ceiling.
// Fragments at the absolute 172-byte command-frame limit have proven flaky
// in practice, so cap to the conservative protocol default.
return maxData.clamp(1, ImagePacket.maxDataBytes).toInt();
}
/// Approximate end-to-end transmit time for image fragments on MeshCore LoRa.
@@ -243,11 +246,11 @@ int _resolveBandwidthHz(int? rawBw) {
/// Envelope announcing image availability (control plane).
///
/// Text format:
/// IE1:{sid}:{fmt}:{total}:{w}:{h}:{bytes}:{senderKey6}:{ts}:{ver}
/// IE2:{sid}:{fmt}:{total}:{w}:{h}:{bytes}:{senderKey6}:{ts}
/// Example:
/// IE1:deadbeef:0:7:128:128:1050:aabbccddeeff:1700000000:1
/// IE2:deadbeef:0:7:3k:3k:t6:aabbccddeeff:s44we8
class ImageEnvelope {
static const String prefix = 'IE1:';
static const String _prefix = 'IE2:';
final String sessionId; // 8 hex chars
final ImageFormat format;
@@ -268,38 +271,36 @@ class ImageEnvelope {
required this.sizeBytes,
required this.senderKey6,
required this.timestampSec,
this.version = 1,
this.version = 2,
});
static bool isEnvelope(String text) => text.startsWith(prefix);
static bool isEnvelope(String text) => text.startsWith(_prefix);
static ImageEnvelope? tryParse(String text) {
if (!isEnvelope(text)) return null;
final body = text.substring(prefix.length);
final body = text.substring(_prefix.length);
final parts = body.split(':');
if (parts.length != 9) return null;
if (parts.length != 8) return null;
try {
final sid = parts[0];
final fmtId = int.tryParse(parts[1]);
final total = int.tryParse(parts[2]);
final w = int.tryParse(parts[3]);
final h = int.tryParse(parts[4]);
final bytes = int.tryParse(parts[5]);
final sid = _decodeSessionId(parts[0]);
final fmtId = _parseInt(parts[1], base36: true);
final total = _parseInt(parts[2], base36: true);
final w = _parseInt(parts[3], base36: true);
final h = _parseInt(parts[4], base36: true);
final bytes = _parseInt(parts[5], base36: true);
final senderKey6 = parts[6];
final ts = int.tryParse(parts[7]);
final ver = int.tryParse(parts[8]);
final ts = _parseInt(parts[7], base36: true);
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sid)) return null;
if (sid == null) return null;
if (fmtId == null) return null;
if (total == null || total < 1 || total > 255) return null;
if (w == null || h == null || w < 1 || h < 1) return null;
if (bytes == null || bytes < 1) return null;
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(senderKey6)) return null;
if (ts == null || ts <= 0) return null;
if (ver == null || ver != 1) return null;
return ImageEnvelope(
sessionId: sid.toLowerCase(),
sessionId: sid,
format: ImageFormat.fromId(fmtId),
total: total,
width: w,
@@ -307,7 +308,7 @@ class ImageEnvelope {
sizeBytes: bytes,
senderKey6: senderKey6.toLowerCase(),
timestampSec: ts,
version: ver,
version: 2,
);
} catch (_) {
return null;
@@ -315,17 +316,21 @@ class ImageEnvelope {
}
String encode() =>
'$prefix${sessionId.toLowerCase()}:${format.id}:$total:$width:$height:$sizeBytes:${senderKey6.toLowerCase()}:$timestampSec:$version';
'$_prefix${_encodeSessionId(sessionId)}:'
'${_toBase36(format.id)}:${_toBase36(total)}:${_toBase36(width)}:'
'${_toBase36(height)}:${_toBase36(sizeBytes)}:'
'${senderKey6.toLowerCase()}:${_toBase36(timestampSec)}';
}
/// Direct request to fetch image fragments (control plane).
///
/// Text format:
/// IR1:{sid}:{want}:{requesterKey6}:{ts}:{ver}
/// IR2:{sid}:{want}:{requesterKey6}:{ts}
/// Example:
/// IR1:deadbeef:a:aabbccddeeff:1700000010:1
/// IR2:deadbeef:a:aabbccddeeff:s44wea
class ImageFetchRequest {
static const String prefix = 'IR1:';
static const String _prefix = 'IR2:';
static const int _binaryMagic = 0x69; // 'i'
final String sessionId;
final String want; // 'all' or 'missing'
@@ -340,51 +345,87 @@ class ImageFetchRequest {
this.missingIndices = const [],
required this.requesterKey6,
required this.timestampSec,
this.version = 1,
this.version = 2,
});
static bool isRequest(String text) => text.startsWith(prefix);
static bool isRequest(String text) => text.startsWith(_prefix);
static bool isRequestBinary(Uint8List payload) =>
payload.isNotEmpty && payload[0] == _binaryMagic;
static ImageFetchRequest? tryParse(String text) {
if (!isRequest(text)) return null;
final body = text.substring(prefix.length);
final body = text.substring(_prefix.length);
final parts = body.split(':');
if (parts.length != 5) return null;
if (parts.length != 4) return null;
try {
final sid = parts[0];
final sid = _decodeSessionId(parts[0]);
final wantToken = parts[1];
final requesterKey6 = parts[2];
final ts = int.tryParse(parts[3]);
final ver = int.tryParse(parts[4]);
final ts = _parseInt(parts[3], base36: true);
final normalizedWant = wantToken == 'a'
? 'all'
: (wantToken.startsWith('m-') ? 'missing' : wantToken);
: ((wantToken.startsWith('m')) ? 'missing' : wantToken);
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sid)) return null;
if (sid == null) return null;
final missingIndices = <int>[];
if (normalizedWant == 'missing') {
final encoded = wantToken.substring(2);
final encoded = wantToken.substring(1);
if (encoded.isEmpty) return null;
for (final raw in encoded.split(',')) {
final idx = int.tryParse(raw);
if (idx == null || idx < 0 || idx > 254) return null;
missingIndices.add(idx);
}
missingIndices.addAll(_decodeMissingIndicesCompact(encoded));
if (missingIndices.isEmpty) return null;
} else if (normalizedWant != 'all') {
return null;
}
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(requesterKey6)) return null;
if (ts == null || ts <= 0) return null;
if (ver == null || ver != 1) return null;
return ImageFetchRequest(
sessionId: sid.toLowerCase(),
sessionId: sid,
want: normalizedWant,
missingIndices: missingIndices,
requesterKey6: requesterKey6.toLowerCase(),
timestampSec: ts,
version: ver,
version: 2,
);
} catch (_) {
return null;
}
}
static ImageFetchRequest? tryParseBinary(Uint8List payload) {
if (!isRequestBinary(payload)) return null;
if (payload.length < 17) return null; // magic+sid+flags+key6+ts+count
try {
final sid = payload
.sublist(1, 5)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final flags = payload[5];
final requesterKey6 = payload
.sublist(6, 12)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final ts =
(payload[12] << 24) |
(payload[13] << 16) |
(payload[14] << 8) |
payload[15];
final missingCount = payload[16];
if (payload.length != 17 + missingCount) return null;
final wantMissing = (flags & 0x01) == 0x01;
final missing = <int>[];
for (var i = 0; i < missingCount; i++) {
missing.add(payload[17 + i]);
}
return ImageFetchRequest(
sessionId: sid,
want: wantMissing ? 'missing' : 'all',
missingIndices: missing,
requesterKey6: requesterKey6,
timestampSec: ts,
version: 2,
);
} catch (_) {
return null;
@@ -393,10 +434,171 @@ class ImageFetchRequest {
String encode() {
final wantToken = want == 'missing' && missingIndices.isNotEmpty
? 'm-${missingIndices.join(',')}'
? 'm${_encodeMissingIndicesCompact(missingIndices)}'
: (want == 'all' ? 'a' : want);
return '$prefix${sessionId.toLowerCase()}:$wantToken:${requesterKey6.toLowerCase()}:$timestampSec:$version';
return '$_prefix${_encodeSessionId(sessionId)}:$wantToken:${requesterKey6.toLowerCase()}:${_toBase36(timestampSec)}';
}
Uint8List encodeBinary() {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionId)) {
throw ArgumentError.value(sessionId, 'sessionId', 'Expected 8 hex chars');
}
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(requesterKey6)) {
throw ArgumentError.value(
requesterKey6,
'requesterKey6',
'Expected 12 hex chars',
);
}
final useMissing = want == 'missing' && missingIndices.isNotEmpty;
final missing = useMissing
? missingIndices.where((v) => v >= 0 && v <= 254).toList()
: <int>[];
final out = Uint8List(17 + missing.length);
out[0] = _binaryMagic;
for (var i = 0; i < 4; i++) {
out[1 + i] = int.parse(sessionId.substring(i * 2, i * 2 + 2), radix: 16);
}
out[5] = useMissing ? 0x01 : 0x00;
for (var i = 0; i < 6; i++) {
out[6 + i] = int.parse(
requesterKey6.substring(i * 2, i * 2 + 2),
radix: 16,
);
}
out[12] = (timestampSec >> 24) & 0xFF;
out[13] = (timestampSec >> 16) & 0xFF;
out[14] = (timestampSec >> 8) & 0xFF;
out[15] = timestampSec & 0xFF;
out[16] = missing.length;
for (var i = 0; i < missing.length; i++) {
out[17 + i] = missing[i];
}
return out;
}
}
/// Per-fragment ACK for raw image payload packets.
///
/// Binary format:
/// [0x6a 'j'][sessionId:4B][index:1B]
class ImageFragmentAck {
static const int _binaryMagic = 0x6a; // 'j'
final String sessionId; // 8 hex chars
final int index; // 0..254
const ImageFragmentAck({required this.sessionId, required this.index});
static bool isImageFragmentAckBinary(Uint8List payload) =>
payload.length == 6 && payload[0] == _binaryMagic;
static ImageFragmentAck? tryParseBinary(Uint8List payload) {
if (!isImageFragmentAckBinary(payload)) return null;
try {
final sid = payload
.sublist(1, 5)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final idx = payload[5];
return ImageFragmentAck(sessionId: sid, index: idx);
} catch (_) {
return null;
}
}
Uint8List encodeBinary() {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionId)) {
throw ArgumentError.value(sessionId, 'sessionId', 'Expected 8 hex chars');
}
if (index < 0 || index > 254) {
throw ArgumentError.value(index, 'index', 'Expected 0..254');
}
final out = Uint8List(6);
out[0] = _binaryMagic;
for (var i = 0; i < 4; i++) {
out[1 + i] = int.parse(sessionId.substring(i * 2, i * 2 + 2), radix: 16);
}
out[5] = index;
return out;
}
}
int? _parseInt(String token, {required bool base36}) =>
int.tryParse(token, radix: base36 ? 36 : 10);
String _toBase36(int value) => value.toRadixString(36);
String _encodeSessionId(String sessionIdHex) {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionIdHex)) {
throw ArgumentError.value(
sessionIdHex,
'sessionIdHex',
'Expected 8 hex chars',
);
}
final value = int.parse(sessionIdHex, radix: 16);
return value.toRadixString(36);
}
String? _decodeSessionId(String token) {
if (!RegExp(r'^[0-9a-z]{1,7}$').hasMatch(token)) return null;
final value = int.tryParse(token, radix: 36);
if (value == null || value < 0 || value > 0xFFFFFFFF) return null;
return value.toRadixString(16).padLeft(8, '0');
}
String _encodeMissingIndicesCompact(List<int> indices) {
final sorted = indices.where((v) => v >= 0 && v <= 254).toSet().toList()
..sort();
if (sorted.isEmpty) return '';
final chunks = <String>[];
var start = sorted.first;
var prev = sorted.first;
for (var i = 1; i < sorted.length; i++) {
final curr = sorted[i];
if (curr == prev + 1) {
prev = curr;
continue;
}
chunks.add(
start == prev
? _toBase36(start)
: '${_toBase36(start)}-${_toBase36(prev)}',
);
start = curr;
prev = curr;
}
chunks.add(
start == prev ? _toBase36(start) : '${_toBase36(start)}-${_toBase36(prev)}',
);
return chunks.join('.');
}
List<int> _decodeMissingIndicesCompact(String encoded) {
final out = <int>[];
for (final token in encoded.split('.')) {
if (token.isEmpty) continue;
if (!token.contains('-')) {
final value = int.tryParse(token, radix: 36);
if (value == null || value < 0 || value > 254) return const [];
out.add(value);
continue;
}
final parts = token.split('-');
if (parts.length != 2) return const [];
final start = int.tryParse(parts[0], radix: 36);
final end = int.tryParse(parts[1], radix: 36);
if (start == null || end == null || start < 0 || end > 254 || start > end) {
return const [];
}
for (var i = start; i <= end; i++) {
out.add(i);
}
}
return out;
}
/// Fragment the compressed image bytes into [ImagePacket] list.

View File

@@ -0,0 +1,25 @@
String formatPlusCode(double lat, double lon) {
const base = '23456789CFGHJMPQRVWX';
var normalizedLat = (lat + 90) / 180;
var normalizedLon = (lon + 180) / 360;
final buffer = StringBuffer();
for (var i = 0; i < 8; i++) {
if (i == 4) {
buffer.write('+');
}
final latDigit = (normalizedLat * 20).floor() % 20;
final lonDigit = (normalizedLon * 20).floor() % 20;
buffer
..write(base[latDigit])
..write(base[lonDigit]);
normalizedLat = (normalizedLat * 20) % 1;
normalizedLon = (normalizedLon * 20) % 1;
}
return buffer.toString();
}

View File

@@ -0,0 +1,129 @@
import 'dart:typed_data';
import '../models/contact.dart';
class DecodedLogRxRoute {
final int payloadType;
final List<int> pathHashes;
const DecodedLogRxRoute({
required this.payloadType,
required this.pathHashes,
});
int? get originalSenderHash => pathHashes.isEmpty ? null : pathHashes.first;
}
class ResolvedNodeHash {
final int hash;
final String label;
final bool isOwnNode;
final bool isUniqueMatch;
final int matchCount;
const ResolvedNodeHash({
required this.hash,
required this.label,
required this.isOwnNode,
required this.isUniqueMatch,
required this.matchCount,
});
String get hexLabel => '0x${hash.toRadixString(16).padLeft(2, '0')}';
}
class LogRxRouteDecoder {
const LogRxRouteDecoder._();
static DecodedLogRxRoute? decode(Uint8List rawData) {
if (rawData.length < 5 || rawData[0] != 0x88) return null;
final rawPacketData = rawData.sublist(3);
if (rawPacketData.length < 2) return null;
final header = rawPacketData[0];
final routeType = header & 0x03;
final payloadType = (header >> 2) & 0x0F;
var index = 1;
if (routeType == 0x00 || routeType == 0x03) {
if (rawPacketData.length < index + 5) return null;
index += 4;
}
if (rawPacketData.length <= index) return null;
final pathLen = rawPacketData[index++];
if (rawPacketData.length < index + pathLen) return null;
return DecodedLogRxRoute(
payloadType: payloadType,
pathHashes: rawPacketData.sublist(index, index + pathLen),
);
}
static ResolvedNodeHash resolveHash(
int hash, {
required Iterable<Contact> contacts,
Uint8List? ownPublicKey,
String? ownName,
}) {
final ownHash = ownPublicKey != null && ownPublicKey.isNotEmpty
? ownPublicKey.first
: null;
if (ownHash == hash) {
final ownLabel = (ownName != null && ownName.trim().isNotEmpty)
? '$ownName (you)'
: 'You';
return ResolvedNodeHash(
hash: hash,
label: ownLabel,
isOwnNode: true,
isUniqueMatch: true,
matchCount: 1,
);
}
final matches = contacts.where((contact) {
return contact.publicKey.isNotEmpty && contact.publicKey.first == hash;
}).toList();
if (matches.isEmpty) {
return ResolvedNodeHash(
hash: hash,
label: 'Unknown',
isOwnNode: false,
isUniqueMatch: false,
matchCount: 0,
);
}
if (matches.length == 1) {
return ResolvedNodeHash(
hash: hash,
label: matches.first.displayName,
isOwnNode: false,
isUniqueMatch: true,
matchCount: 1,
);
}
final candidateNames = matches
.map((contact) => contact.displayName)
.where((name) => name.trim().isNotEmpty)
.take(2)
.join(', ');
final extraCount = matches.length - 2;
final label = candidateNames.isEmpty
? '${matches.length} contacts'
: extraCount > 0
? '$candidateNames +$extraCount'
: candidateNames;
return ResolvedNodeHash(
hash: hash,
label: label,
isOwnNode: false,
isUniqueMatch: false,
matchCount: matches.length,
);
}
}

View File

@@ -0,0 +1,149 @@
import '../models/message.dart';
import 'image_message_parser.dart';
import 'voice_message_parser.dart';
const int _defaultLoRaSf = 10;
const int _defaultLoRaCr = 5;
const int _defaultLoRaBwHz = 250000;
const int _defaultLoRaPreambleSymbols = 8;
const int _defaultLoRaCrcEnabled = 1;
const int _defaultLoRaExplicitHeader = 1;
const double _defaultAirtimeBudgetFactor = 1.0;
const int _meshPacketHeaderBytes = 2;
const int _textFrameBaseBytes = 10;
Duration estimateMessageTransmitDuration(
Message message, {
int? radioBw,
int? radioSf,
int? radioCr,
}) {
final imageEnvelope = ImageEnvelope.tryParse(message.text);
if (imageEnvelope != null) {
return estimateImageTransmitDuration(
fragmentCount: imageEnvelope.total,
sizeBytes: imageEnvelope.sizeBytes,
pathLen: message.pathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
}
final voiceEnvelope = VoiceEnvelope.tryParseText(message.text);
if (voiceEnvelope != null) {
return estimateVoiceTransmitDuration(
mode: voiceEnvelope.mode,
packetCount: voiceEnvelope.total,
durationMs: voiceEnvelope.durationMs,
pathLen: message.pathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
}
final voicePacket = VoicePacket.tryParseText(message.text);
if (voicePacket != null) {
return estimateVoiceTransmitDuration(
mode: voicePacket.mode,
packetCount: voicePacket.total,
durationMs: voicePacket.durationMs * voicePacket.total,
pathLen: message.pathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
}
final normalizedPathLen = _normalizedPathLen(message.pathLen);
final payloadBytes = _textFrameBaseBytes + message.text.length;
final hops = normalizedPathLen + 1;
final airtimeMs = _estimateLoRaAirtimeMs(
_meshPacketHeaderBytes + normalizedPathLen + payloadBytes,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
return Duration(
milliseconds: (airtimeMs * (1.0 + _defaultAirtimeBudgetFactor) * hops)
.round(),
);
}
int _normalizedPathLen(int pathLen) {
if (pathLen < 0 || pathLen >= 255) return 0;
return pathLen.clamp(0, 64).toInt();
}
double _estimateLoRaAirtimeMs(
int payloadLenBytes, {
int? radioBw,
int? radioSf,
int? radioCr,
}) {
final sf = _normalizeSf(radioSf);
final bw = _resolveBandwidthHz(radioBw).toDouble();
final cr = (_normalizeCr(radioCr) - 4).clamp(1, 4);
final ih = _defaultLoRaExplicitHeader == 1 ? 0 : 1;
final de = (sf >= 11 && _defaultLoRaBwHz <= 125000) ? 1 : 0;
final symbolMs = ((1 << sf) / bw) * 1000.0;
final preambleMs = (_defaultLoRaPreambleSymbols + 4.25) * symbolMs;
final num =
(8 * payloadLenBytes) -
(4 * sf) +
28 +
(16 * _defaultLoRaCrcEnabled) -
(20 * ih);
final den = 4 * (sf - (2 * de));
final payloadSymCoeff = den <= 0 ? 0 : (num / den).ceil();
final payloadSymbols =
8 + (payloadSymCoeff < 0 ? 0 : payloadSymCoeff) * (cr + 4);
final payloadMs = payloadSymbols * symbolMs;
return preambleMs + payloadMs;
}
int _normalizeSf(int? value) {
if (value == null) return _defaultLoRaSf;
if (value >= 5 && value <= 12) return value;
return _defaultLoRaSf;
}
int _normalizeCr(int? value) {
if (value == null) return _defaultLoRaCr;
if (value >= 5 && value <= 8) return value;
return _defaultLoRaCr;
}
int _resolveBandwidthHz(int? rawBw) {
if (rawBw == null) return _defaultLoRaBwHz;
if (rawBw > 1000) return rawBw;
switch (rawBw) {
case 0:
return 7800;
case 1:
return 10400;
case 2:
return 15600;
case 3:
return 20800;
case 4:
return 31250;
case 5:
return 41700;
case 6:
return 62500;
case 7:
return 125000;
case 8:
return 250000;
case 9:
return 500000;
default:
return _defaultLoRaBwHz;
}
}

View File

@@ -24,15 +24,30 @@ extension MessageLocalization on Message {
switch (deliveryStatus) {
case MessageDeliveryStatus.sending:
if (isContactMessage) {
if (retryAttempt > 0) {
return '${l10n.pending}${l10n.retryAttempt} $retryAttempt/3';
}
return l10n.pending;
}
return l10n.sending;
case MessageDeliveryStatus.sent:
return l10n.sent;
case MessageDeliveryStatus.delivered:
if (retryAttempt > 0 && roundTripTimeMs != null) {
return '${l10n.deliveredWithTime(roundTripTimeMs!)}${l10n.retryAttempt} $retryAttempt/3';
}
if (retryAttempt > 0) {
return '${l10n.delivered}${l10n.retryAttempt} $retryAttempt/3';
}
if (roundTripTimeMs != null) {
return l10n.deliveredWithTime(roundTripTimeMs!);
}
return l10n.delivered;
case MessageDeliveryStatus.failed:
if (retryAttempt > 0) {
return '${l10n.failed}${l10n.retryAttempt} $retryAttempt/3';
}
return l10n.failed;
case MessageDeliveryStatus.received:
return '';

View File

@@ -0,0 +1,87 @@
import 'dart:typed_data';
class RawRouteProbeRequest {
static const int _binaryMagic = 0x70; // 'p'
final int nonce;
final String requesterKey6;
const RawRouteProbeRequest({
required this.nonce,
required this.requesterKey6,
});
static RawRouteProbeRequest? tryParseBinary(Uint8List payload) {
if (payload.length != 11 || payload[0] != _binaryMagic) return null;
try {
final nonce =
(payload[1] << 24) |
(payload[2] << 16) |
(payload[3] << 8) |
payload[4];
final requesterKey6 = payload
.sublist(5, 11)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
return RawRouteProbeRequest(nonce: nonce, requesterKey6: requesterKey6);
} catch (_) {
return null;
}
}
Uint8List encodeBinary() {
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(requesterKey6)) {
throw ArgumentError.value(
requesterKey6,
'requesterKey6',
'Expected 12 hex chars',
);
}
final out = Uint8List(11);
out[0] = _binaryMagic;
out[1] = (nonce >> 24) & 0xFF;
out[2] = (nonce >> 16) & 0xFF;
out[3] = (nonce >> 8) & 0xFF;
out[4] = nonce & 0xFF;
for (var i = 0; i < 6; i++) {
out[5 + i] = int.parse(
requesterKey6.substring(i * 2, i * 2 + 2),
radix: 16,
);
}
return out;
}
}
class RawRouteProbeAck {
static const int _binaryMagic = 0x71; // 'q'
final int nonce;
const RawRouteProbeAck({required this.nonce});
static RawRouteProbeAck? tryParseBinary(Uint8List payload) {
if (payload.length != 5 || payload[0] != _binaryMagic) return null;
try {
final nonce =
(payload[1] << 24) |
(payload[2] << 16) |
(payload[3] << 8) |
payload[4];
return RawRouteProbeAck(nonce: nonce);
} catch (_) {
return null;
}
}
Uint8List encodeBinary() {
final out = Uint8List(5);
out[0] = _binaryMagic;
out[1] = (nonce >> 24) & 0xFF;
out[2] = (nonce >> 16) & 0xFF;
out[3] = (nonce >> 8) & 0xFF;
out[4] = nonce & 0xFF;
return out;
}
}

View File

@@ -4,12 +4,66 @@ import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import '../models/contact.dart';
import '../models/message.dart';
import '../models/message_contact_location.dart';
import '../l10n/app_localizations.dart';
/// Generates sample data for testing/demo purposes
class SampleDataGenerator {
static final Random _random = Random();
static MessageContactLocation _sampleSnapshot({
required LatLng location,
required DateTime receivedAt,
required String source,
}) {
return MessageContactLocation(
location: location,
source: source,
capturedAt: receivedAt,
sourceTimestamp: receivedAt.subtract(const Duration(minutes: 2)),
);
}
static LatLng _randomNearbyLocation(LatLng center, double spread) {
final latOffset = (_random.nextDouble() - 0.5) * spread;
final lonOffset = (_random.nextDouble() - 0.5) * spread;
return LatLng(center.latitude + latOffset, center.longitude + lonOffset);
}
static SampleMessageBatch generateAllMessages({
required LatLng centerLocation,
required AppLocalizations l10n,
int foundPersonCount = 2,
int fireCount = 1,
int stagingCount = 1,
int objectCount = 1,
int generalChannelMessages = 8,
int emergencyChannelMessages = 5,
}) {
final sarBatch = generateSarMarkerMessages(
centerLocation: centerLocation,
l10n: l10n,
foundPersonCount: foundPersonCount,
fireCount: fireCount,
stagingCount: stagingCount,
objectCount: objectCount,
);
final channelBatch = generateChannelMessages(
centerLocation: centerLocation,
l10n: l10n,
generalChannelMessages: generalChannelMessages,
emergencyChannelMessages: emergencyChannelMessages,
);
return SampleMessageBatch(
messages: [...sarBatch.messages, ...channelBatch.messages],
contactLocations: {
...sarBatch.contactLocations,
...channelBatch.contactLocations,
},
);
}
/// Generate sample contacts around a center location
static List<Contact> generateContacts({
required LatLng centerLocation,
@@ -113,7 +167,7 @@ class SampleDataGenerator {
}
/// Generate sample SAR markers around a center location
static List<Message> generateSarMarkerMessages({
static SampleMessageBatch generateSarMarkerMessages({
required LatLng centerLocation,
required AppLocalizations l10n,
int foundPersonCount = 2,
@@ -122,6 +176,7 @@ class SampleDataGenerator {
int objectCount = 1,
}) {
final messages = <Message>[];
final contactLocations = <String, MessageContactLocation>{};
final now = DateTime.now();
int messageId = 1;
@@ -137,7 +192,7 @@ class SampleDataGenerator {
);
final timestamp = now.subtract(Duration(minutes: 10 + i * 5));
messages.add(Message(
final message = Message(
id: 'sample_fp_$messageId',
messageType: MessageType.contact,
senderPublicKeyPrefix: senderKey.sublist(0, 6),
@@ -150,7 +205,13 @@ class SampleDataGenerator {
sarGpsCoordinates: LatLng(lat, lon),
sarCustomEmoji: '🧑',
senderName: l10n.sampleTeamMember,
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(message.sarGpsCoordinates!, 0.006),
receivedAt: timestamp,
source: 'telemetry',
);
messageId++;
}
@@ -166,7 +227,7 @@ class SampleDataGenerator {
);
final timestamp = now.subtract(Duration(minutes: 20 + i * 5));
messages.add(Message(
final message = Message(
id: 'sample_fire_$messageId',
messageType: MessageType.contact,
senderPublicKeyPrefix: senderKey.sublist(0, 6),
@@ -179,7 +240,13 @@ class SampleDataGenerator {
sarGpsCoordinates: LatLng(lat, lon),
sarCustomEmoji: '🔥',
senderName: l10n.sampleScout,
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(message.sarGpsCoordinates!, 0.008),
receivedAt: timestamp,
source: 'advert',
);
messageId++;
}
@@ -195,7 +262,7 @@ class SampleDataGenerator {
);
final timestamp = now.subtract(Duration(minutes: 30 + i * 5));
messages.add(Message(
final message = Message(
id: 'sample_staging_$messageId',
messageType: MessageType.contact,
senderPublicKeyPrefix: senderKey.sublist(0, 6),
@@ -208,7 +275,13 @@ class SampleDataGenerator {
sarGpsCoordinates: LatLng(lat, lon),
sarCustomEmoji: '🏕️',
senderName: l10n.sampleBase,
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(message.sarGpsCoordinates!, 0.01),
receivedAt: timestamp,
source: 'advert',
);
messageId++;
}
@@ -231,24 +304,34 @@ class SampleDataGenerator {
l10n.sampleObjectTrailMarker,
];
messages.add(Message(
final message = Message(
id: 'sample_object_$messageId',
messageType: MessageType.contact,
senderPublicKeyPrefix: senderKey.sublist(0, 6),
pathLen: 1,
textType: MessageTextType.plain,
senderTimestamp: timestamp.millisecondsSinceEpoch ~/ 1000,
text: 'S:📦:${lat.toStringAsFixed(5)},${lon.toStringAsFixed(5)}${notes[i % notes.length]}',
text:
'S:📦:${lat.toStringAsFixed(5)},${lon.toStringAsFixed(5)}${notes[i % notes.length]}',
receivedAt: timestamp,
isSarMarker: true,
sarGpsCoordinates: LatLng(lat, lon),
sarCustomEmoji: '📦',
senderName: l10n.sampleSearcher,
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(message.sarGpsCoordinates!, 0.007),
receivedAt: timestamp,
source: 'telemetry',
);
messageId++;
}
return messages;
return SampleMessageBatch(
messages: messages,
contactLocations: contactLocations,
);
}
/// Generate sample map drawings
@@ -272,7 +355,9 @@ class SampleDataGenerator {
'id': 'sample_line_${now.millisecondsSinceEpoch}',
'color': Colors.blue.toARGB32(),
'createdAt': now.subtract(const Duration(minutes: 15)).toIso8601String(),
'points': linePoints.map((p) => {'lat': p.latitude, 'lon': p.longitude}).toList(),
'points': linePoints
.map((p) => {'lat': p.latitude, 'lon': p.longitude})
.toList(),
'sender': l10n.sampleTeamMember,
});
@@ -297,7 +382,7 @@ class SampleDataGenerator {
}
/// Generate sample channel messages for public channels
static List<Message> generateChannelMessages({
static SampleMessageBatch generateChannelMessages({
LatLng? centerLocation,
required AppLocalizations l10n,
int generalChannelMessages = 8,
@@ -306,6 +391,7 @@ class SampleDataGenerator {
// Use provided location or default to Ljubljana, Slovenia
final center = centerLocation ?? const LatLng(46.0569, 14.5058);
final messages = <Message>[];
final contactLocations = <String, MessageContactLocation>{};
final now = DateTime.now();
int messageId = 1000; // Start with high ID to avoid conflicts
@@ -352,7 +438,11 @@ class SampleDataGenerator {
];
// Generate General channel messages
for (int i = 0; i < generalChannelMessages && i < generalMessages.length; i++) {
for (
int i = 0;
i < generalChannelMessages && i < generalMessages.length;
i++
) {
final senderKey = Uint8List.fromList(
List.generate(32, (_) => _random.nextInt(256)),
);
@@ -361,7 +451,7 @@ class SampleDataGenerator {
final minutesAgo = 120 - (i * 15) - _random.nextInt(10);
final timestamp = now.subtract(Duration(minutes: minutesAgo));
messages.add(Message(
final message = Message(
id: 'sample_general_$messageId',
messageType: MessageType.channel,
channelIdx: 0, // General channel
@@ -372,12 +462,22 @@ class SampleDataGenerator {
text: generalMessages[i],
receivedAt: timestamp,
senderName: teamNames[_random.nextInt(teamNames.length)],
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(center, 0.018),
receivedAt: timestamp,
source: i.isEven ? 'telemetry' : 'advert',
);
messageId++;
}
// Generate Emergency channel messages
for (int i = 0; i < emergencyChannelMessages && i < emergencyMessages.length; i++) {
for (
int i = 0;
i < emergencyChannelMessages && i < emergencyMessages.length;
i++
) {
final senderKey = Uint8List.fromList(
List.generate(32, (_) => _random.nextInt(256)),
);
@@ -386,7 +486,7 @@ class SampleDataGenerator {
final minutesAgo = 60 - (i * 10) - _random.nextInt(5);
final timestamp = now.subtract(Duration(minutes: minutesAgo));
messages.add(Message(
final message = Message(
id: 'sample_emergency_$messageId',
messageType: MessageType.channel,
channelIdx: 1, // Emergency channel
@@ -397,10 +497,29 @@ class SampleDataGenerator {
text: emergencyMessages[i],
receivedAt: timestamp,
senderName: teamNames[_random.nextInt(teamNames.length)],
));
);
messages.add(message);
contactLocations[message.id] = _sampleSnapshot(
location: _randomNearbyLocation(center, 0.012),
receivedAt: timestamp,
source: i.isEven ? 'advert' : 'telemetry',
);
messageId++;
}
return messages;
return SampleMessageBatch(
messages: messages,
contactLocations: contactLocations,
);
}
}
class SampleMessageBatch {
final List<Message> messages;
final Map<String, MessageContactLocation> contactLocations;
const SampleMessageBatch({
required this.messages,
required this.contactLocations,
});
}

View File

@@ -0,0 +1,163 @@
enum TicTacToeEventType { start, move }
class TicTacToeEvent {
final TicTacToeEventType type;
final String gameId;
final String playerKey6;
final int? cell;
final int timestampSec;
const TicTacToeEvent({
required this.type,
required this.gameId,
required this.playerKey6,
this.cell,
required this.timestampSec,
});
}
class TicTacToeMessageParser {
static const String _prefix = 'TTT1:';
static bool isTicTacToe(String text) => text.startsWith(_prefix);
static TicTacToeEvent? tryParse(String text) {
if (!isTicTacToe(text)) return null;
final body = text.substring(_prefix.length);
final parts = body.split(':');
if (parts.length < 4) return null;
final action = parts[0];
final gameId = parts[1].toLowerCase();
if (!RegExp(r'^[0-9a-f]{8}$').hasMatch(gameId)) return null;
if (action == 'S' && parts.length == 4) {
final starterKey6 = parts[2].toLowerCase();
final ts = int.tryParse(parts[3]);
if (!RegExp(r'^[0-9a-f]{12}$').hasMatch(starterKey6)) return null;
if (ts == null || ts <= 0) return null;
return TicTacToeEvent(
type: TicTacToeEventType.start,
gameId: gameId,
playerKey6: starterKey6,
timestampSec: ts,
);
}
if (action == 'M' && parts.length == 5) {
final cell = int.tryParse(parts[2]);
final playerKey6 = parts[3].toLowerCase();
final ts = int.tryParse(parts[4]);
if (cell == null || cell < 0 || cell > 8) return null;
if (!RegExp(r'^[0-9a-f]{12}$').hasMatch(playerKey6)) return null;
if (ts == null || ts <= 0) return null;
return TicTacToeEvent(
type: TicTacToeEventType.move,
gameId: gameId,
playerKey6: playerKey6,
cell: cell,
timestampSec: ts,
);
}
return null;
}
static String encodeStart({
required String gameId,
required String starterKey6,
required int timestampSec,
}) {
return '$_prefix'
'S:${gameId.toLowerCase()}:${starterKey6.toLowerCase()}:$timestampSec';
}
static String encodeMove({
required String gameId,
required int cell,
required String playerKey6,
required int timestampSec,
}) {
return '$_prefix'
'M:${gameId.toLowerCase()}:$cell:${playerKey6.toLowerCase()}:$timestampSec';
}
}
class TicTacToeGameState {
final String gameId;
final String xPlayerKey6;
final String oPlayerKey6;
final List<String?> board; // 'X' / 'O' / null
final String nextSymbol;
final String? winnerSymbol;
const TicTacToeGameState({
required this.gameId,
required this.xPlayerKey6,
required this.oPlayerKey6,
required this.board,
required this.nextSymbol,
this.winnerSymbol,
});
bool get isDraw =>
winnerSymbol == null && board.every((cell) => cell != null);
bool get isFinished => winnerSymbol != null || isDraw;
}
TicTacToeGameState buildTicTacToeState({
required String gameId,
required String xPlayerKey6,
required String oPlayerKey6,
required List<TicTacToeEvent> events,
}) {
final board = List<String?>.filled(9, null);
var next = 'X';
String? winner;
final sorted = [...events]
..sort((a, b) => a.timestampSec.compareTo(b.timestampSec));
for (final event in sorted) {
if (event.type != TicTacToeEventType.move) continue;
if (winner != null) break;
final expectedKey = next == 'X' ? xPlayerKey6 : oPlayerKey6;
final cell = event.cell;
if (cell == null) continue;
if (event.playerKey6 != expectedKey) continue;
if (board[cell] != null) continue;
board[cell] = next;
winner = _computeWinner(board);
next = next == 'X' ? 'O' : 'X';
}
return TicTacToeGameState(
gameId: gameId,
xPlayerKey6: xPlayerKey6,
oPlayerKey6: oPlayerKey6,
board: board,
nextSymbol: next,
winnerSymbol: winner,
);
}
String? _computeWinner(List<String?> board) {
const lines = <List<int>>[
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (final line in lines) {
final a = board[line[0]];
if (a == null) continue;
if (a == board[line[1]] && a == board[line[2]]) return a;
}
return null;
}

View File

@@ -0,0 +1,157 @@
import 'dart:typed_data';
import '../models/contact.dart';
import '../providers/contacts_provider.dart';
enum TransmissionTargetFailure { unknownContact, unknownRoute, tooFar, unreachable }
class TransmissionTargetResolution {
final Contact? target;
final TransmissionTargetFailure? failure;
final int maxHops;
const TransmissionTargetResolution({
required this.target,
required this.failure,
required this.maxHops,
});
int get hops => target?.outPathLen ?? -1;
bool get isValid => target != null && failure == null;
}
class TransmissionTargetResolver {
const TransmissionTargetResolver._();
static Contact? resolveLocalTarget({
required ContactsProvider contactsProvider,
required bool isSentByMe,
Uint8List? recipientPublicKey,
Uint8List? senderPublicKeyPrefix,
String? senderKey6FromEnvelope,
String? senderName,
}) {
if (isSentByMe) {
final recipient = _findByRecipientKey(contactsProvider, recipientPublicKey);
if (recipient != null) return recipient;
}
final byEnvelope = _findByEnvelopeKey6(contactsProvider, senderKey6FromEnvelope);
if (byEnvelope != null) return byEnvelope;
final byPrefix = _findByPrefix(contactsProvider, senderPublicKeyPrefix);
if (byPrefix != null) return byPrefix;
return _findByName(contactsProvider, senderName);
}
static Future<TransmissionTargetResolution> resolveFetchTarget({
required ContactsProvider contactsProvider,
required Future<void> Function() refreshContacts,
required bool isSentByMe,
Uint8List? recipientPublicKey,
Uint8List? senderPublicKeyPrefix,
String? senderKey6FromEnvelope,
String? senderName,
required int maxFetchHops,
}) async {
var target = resolveLocalTarget(
contactsProvider: contactsProvider,
isSentByMe: isSentByMe,
recipientPublicKey: recipientPublicKey,
senderPublicKeyPrefix: senderPublicKeyPrefix,
senderKey6FromEnvelope: senderKey6FromEnvelope,
senderName: senderName,
);
if (target == null || target.outPathLen < 0 || target.outPathLen > maxFetchHops) {
await refreshContacts();
target = resolveLocalTarget(
contactsProvider: contactsProvider,
isSentByMe: isSentByMe,
recipientPublicKey: recipientPublicKey,
senderPublicKeyPrefix: senderPublicKeyPrefix,
senderKey6FromEnvelope: senderKey6FromEnvelope,
senderName: senderName,
);
}
if (target == null) {
return TransmissionTargetResolution(
target: null,
failure: TransmissionTargetFailure.unknownContact,
maxHops: maxFetchHops,
);
}
if (target.outPathLen < 0) {
return TransmissionTargetResolution(
target: target,
failure: TransmissionTargetFailure.unknownRoute,
maxHops: maxFetchHops,
);
}
if (target.outPathLen > maxFetchHops) {
return TransmissionTargetResolution(
target: target,
failure: TransmissionTargetFailure.tooFar,
maxHops: maxFetchHops,
);
}
return TransmissionTargetResolution(
target: target,
failure: null,
maxHops: maxFetchHops,
);
}
static Contact? _findByRecipientKey(
ContactsProvider contactsProvider,
Uint8List? recipientKey,
) {
if (recipientKey == null || recipientKey.isEmpty) return null;
final byKey = contactsProvider.findContactByKey(recipientKey);
if (byKey != null) return byKey;
if (recipientKey.length >= 6) {
return contactsProvider.findContactByPrefix(
Uint8List.fromList(recipientKey.sublist(0, 6)),
);
}
return null;
}
static Contact? _findByEnvelopeKey6(
ContactsProvider contactsProvider,
String? senderKey6FromEnvelope,
) {
if (senderKey6FromEnvelope == null || senderKey6FromEnvelope.isEmpty) {
return null;
}
return contactsProvider.findContactByPrefixHex(senderKey6FromEnvelope);
}
static Contact? _findByPrefix(
ContactsProvider contactsProvider,
Uint8List? senderPublicKeyPrefix,
) {
if (senderPublicKeyPrefix == null || senderPublicKeyPrefix.length < 6) {
return null;
}
return contactsProvider.findContactByPrefix(
Uint8List.fromList(senderPublicKeyPrefix.sublist(0, 6)),
);
}
static Contact? _findByName(
ContactsProvider contactsProvider,
String? senderName,
) {
final normalized = senderName?.trim();
if (normalized == null || normalized.isEmpty) return null;
for (final contact in contactsProvider.contacts) {
if (contact.advName.trim().toLowerCase() == normalized.toLowerCase()) {
return contact;
}
}
return null;
}
}

View File

@@ -181,11 +181,11 @@ class VoicePacket {
/// Lightweight public/direct message envelope advertising voice availability.
///
/// Text format:
/// VE1:{sid}:{mode}:{total}:{durMs}:{senderKey6}:{ts}:{ver}
/// VE2:{sid}:{mode}:{total}:{durS}:{senderKey6}:{ts}
/// Example:
/// VE1:00112233:1:4:3200:aabbccddeeff:1234567890:1
/// VE2:00112233:1:4:4:aabbccddeeff:kf12oi
class VoiceEnvelope {
static const String _prefix = 'VE1:';
static const String _prefix = 'VE2:';
final String sessionId;
final VoicePacketMode mode;
@@ -202,7 +202,7 @@ class VoiceEnvelope {
required this.durationMs,
required this.senderKey6,
required this.timestampSec,
this.version = 1,
this.version = 2,
});
static bool isVoiceEnvelopeText(String text) => text.startsWith(_prefix);
@@ -210,43 +210,41 @@ class VoiceEnvelope {
static VoiceEnvelope? tryParseText(String text) {
if (!isVoiceEnvelopeText(text)) return null;
final body = text.substring(_prefix.length);
return _tryParseCompact(body);
return _tryParse(body);
}
static VoiceEnvelope? _tryParseCompact(String body) {
static VoiceEnvelope? _tryParse(String body) {
final parts = body.split(':');
if (parts.length != 7) return null;
if (parts.length != 6) return null;
try {
final sid = parts[0];
final mode = int.tryParse(parts[1]);
final total = int.tryParse(parts[2]);
final durMs = int.tryParse(parts[3]);
final sid = _decodeSessionId(parts[0]);
final mode = _parseInt(parts[1], base36: true);
final total = _parseInt(parts[2], base36: true);
final durS = _parseInt(parts[3], base36: true);
final senderKey6 = parts[4];
final ts = int.tryParse(parts[5]);
final ver = int.tryParse(parts[6]);
final ts = _parseInt(parts[5], base36: true);
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sid)) {
if (sid == null) {
return null;
}
if (mode == null || mode < 0 || mode >= VoicePacketMode.values.length) {
return null;
}
if (total == null || total < 1 || total > 255) return null;
if (durMs == null || durMs < 0 || durMs > 10 * 60 * 1000) return null;
if (durS == null || durS < 0 || durS > 10 * 60) return null;
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(senderKey6)) {
return null;
}
if (ts == null || ts <= 0) return null;
if (ver == null || ver != 1) return null;
return VoiceEnvelope(
sessionId: sid.toLowerCase(),
sessionId: sid,
mode: VoicePacketMode.fromId(mode),
total: total,
durationMs: durMs,
durationMs: durS * 1000,
senderKey6: senderKey6.toLowerCase(),
timestampSec: ts,
version: ver,
version: 2,
);
} catch (_) {
return null;
@@ -254,7 +252,8 @@ class VoiceEnvelope {
}
String encodeText() {
return '$_prefix${sessionId.toLowerCase()}:${mode.id}:$total:$durationMs:${senderKey6.toLowerCase()}:$timestampSec:$version';
final durationSec = (durationMs / 1000).ceil().clamp(0, 10 * 60);
return '$_prefix${_encodeSessionId(sessionId)}:${_toBase36(mode.id)}:${_toBase36(total)}:${_toBase36(durationSec)}:${senderKey6.toLowerCase()}:${_toBase36(timestampSec)}';
}
}
@@ -415,11 +414,12 @@ int _resolveBandwidthHz(int? rawBw) {
/// Direct control-plane request to fetch voice packets for a session.
///
/// Text format:
/// VR1:{sid}:{want}:{requesterKey6}:{ts}:{ver}
/// VR2:{sid}:{want}:{requesterKey6}:{ts}
/// Example:
/// VR1:00112233:a:aabbccddeeff:1234567890:1
/// VR2:00112233:a:aabbccddeeff:kf12oi
class VoiceFetchRequest {
static const String _prefix = 'VR1:';
static const String _prefix = 'VR2:';
static const int _binaryMagic = 0x72; // 'r'
final String sessionId;
final String want;
@@ -434,42 +434,82 @@ class VoiceFetchRequest {
this.missingIndices = const [],
required this.requesterKey6,
required this.timestampSec,
this.version = 1,
this.version = 2,
});
static bool isVoiceFetchRequestText(String text) => text.startsWith(_prefix);
static bool isVoiceFetchRequestText(String text) =>
text.startsWith(_prefix);
static bool isVoiceFetchRequestBinary(Uint8List payload) =>
payload.isNotEmpty && payload[0] == _binaryMagic;
static VoiceFetchRequest? tryParseText(String text) {
if (!isVoiceFetchRequestText(text)) return null;
final body = text.substring(_prefix.length);
return _tryParseCompact(body);
return _tryParse(body);
}
static VoiceFetchRequest? _tryParseCompact(String body) {
final parts = body.split(':');
if (parts.length != 5) return null;
static VoiceFetchRequest? tryParseBinary(Uint8List payload) {
if (!isVoiceFetchRequestBinary(payload)) return null;
if (payload.length < 17) return null; // magic+sid+flags+key6+ts+count
try {
final sid = parts[0];
final sidBytes = payload.sublist(1, 5);
final sid = sidBytes
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final flags = payload[5];
final requesterKey6 = payload
.sublist(6, 12)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final ts =
(payload[12] << 24) |
(payload[13] << 16) |
(payload[14] << 8) |
payload[15];
final missingCount = payload[16];
if (payload.length != 17 + missingCount) return null;
final wantMissing = (flags & 0x01) == 0x01;
final missing = <int>[];
for (var i = 0; i < missingCount; i++) {
missing.add(payload[17 + i]);
}
return VoiceFetchRequest(
sessionId: sid,
want: wantMissing ? 'missing' : 'all',
missingIndices: missing,
requesterKey6: requesterKey6,
timestampSec: ts,
version: 2,
);
} catch (_) {
return null;
}
}
static VoiceFetchRequest? _tryParse(String body) {
final parts = body.split(':');
if (parts.length != 4) return null;
try {
final sid = _decodeSessionId(parts[0]);
final wantToken = parts[1];
final requesterKey6 = parts[2];
final ts = int.tryParse(parts[3]);
final ver = int.tryParse(parts[4]);
final ts = _parseInt(parts[3], base36: true);
final normalizedWant = wantToken == 'a'
? 'all'
: (wantToken.startsWith('m-') ? 'missing' : wantToken);
: ((wantToken.startsWith('m'))
? 'missing'
: wantToken);
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sid)) {
if (sid == null) {
return null;
}
final missingIndices = <int>[];
if (normalizedWant == 'missing') {
final encoded = wantToken.substring(2);
final encoded = wantToken.substring(1);
if (encoded.isEmpty) return null;
for (final raw in encoded.split(',')) {
final idx = int.tryParse(raw);
if (idx == null || idx < 0 || idx > 254) return null;
missingIndices.add(idx);
}
missingIndices.addAll(_decodeMissingIndicesCompact(encoded));
if (missingIndices.isEmpty) return null;
} else if (normalizedWant != 'all') {
return null;
@@ -478,15 +518,14 @@ class VoiceFetchRequest {
return null;
}
if (ts == null || ts <= 0) return null;
if (ver == null || ver != 1) return null;
return VoiceFetchRequest(
sessionId: sid.toLowerCase(),
sessionId: sid,
want: normalizedWant,
missingIndices: missingIndices,
requesterKey6: requesterKey6.toLowerCase(),
timestampSec: ts,
version: ver,
version: 2,
);
} catch (_) {
return null;
@@ -495,10 +534,168 @@ class VoiceFetchRequest {
String encodeText() {
final wantToken = want == 'missing' && missingIndices.isNotEmpty
? 'm-${missingIndices.join(',')}'
? 'm${_encodeMissingIndicesCompact(missingIndices)}'
: (want == 'all' ? 'a' : want);
return '$_prefix${sessionId.toLowerCase()}:$wantToken:${requesterKey6.toLowerCase()}:$timestampSec:$version';
return '$_prefix${_encodeSessionId(sessionId)}:$wantToken:${requesterKey6.toLowerCase()}:${_toBase36(timestampSec)}';
}
Uint8List encodeBinary() {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionId)) {
throw ArgumentError.value(sessionId, 'sessionId', 'Expected 8 hex chars');
}
if (!RegExp(r'^[0-9a-fA-F]{12}$').hasMatch(requesterKey6)) {
throw ArgumentError.value(
requesterKey6,
'requesterKey6',
'Expected 12 hex chars',
);
}
final useMissing = want == 'missing' && missingIndices.isNotEmpty;
final missing = useMissing
? missingIndices.where((v) => v >= 0 && v <= 254).toList()
: <int>[];
final out = Uint8List(17 + missing.length);
out[0] = _binaryMagic;
for (var i = 0; i < 4; i++) {
out[1 + i] = int.parse(sessionId.substring(i * 2, i * 2 + 2), radix: 16);
}
out[5] = useMissing ? 0x01 : 0x00;
for (var i = 0; i < 6; i++) {
out[6 + i] = int.parse(
requesterKey6.substring(i * 2, i * 2 + 2),
radix: 16,
);
}
out[12] = (timestampSec >> 24) & 0xFF;
out[13] = (timestampSec >> 16) & 0xFF;
out[14] = (timestampSec >> 8) & 0xFF;
out[15] = timestampSec & 0xFF;
out[16] = missing.length;
for (var i = 0; i < missing.length; i++) {
out[17 + i] = missing[i];
}
return out;
}
}
/// Per-fragment ACK for raw voice payload packets.
///
/// Binary format:
/// [0x76 'v'][sessionId:4B][index:1B]
class VoiceFragmentAck {
static const int _binaryMagic = 0x76; // 'v'
final String sessionId; // 8 hex chars
final int index; // 0..254
const VoiceFragmentAck({required this.sessionId, required this.index});
static bool isVoiceFragmentAckBinary(Uint8List payload) =>
payload.length == 6 && payload[0] == _binaryMagic;
static VoiceFragmentAck? tryParseBinary(Uint8List payload) {
if (!isVoiceFragmentAckBinary(payload)) return null;
try {
final sid = payload
.sublist(1, 5)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
final idx = payload[5];
return VoiceFragmentAck(sessionId: sid, index: idx);
} catch (_) {
return null;
}
}
Uint8List encodeBinary() {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionId)) {
throw ArgumentError.value(sessionId, 'sessionId', 'Expected 8 hex chars');
}
if (index < 0 || index > 254) {
throw ArgumentError.value(index, 'index', 'Expected 0..254');
}
final out = Uint8List(6);
out[0] = _binaryMagic;
for (var i = 0; i < 4; i++) {
out[1 + i] = int.parse(sessionId.substring(i * 2, i * 2 + 2), radix: 16);
}
out[5] = index;
return out;
}
}
int? _parseInt(String token, {required bool base36}) =>
int.tryParse(token, radix: base36 ? 36 : 10);
String _toBase36(int value) => value.toRadixString(36);
String _encodeSessionId(String sessionIdHex) {
if (!RegExp(r'^[0-9a-fA-F]{8}$').hasMatch(sessionIdHex)) {
throw ArgumentError.value(sessionIdHex, 'sessionIdHex', 'Expected 8 hex chars');
}
final value = int.parse(sessionIdHex, radix: 16);
return value.toRadixString(36);
}
String? _decodeSessionId(String token) {
if (!RegExp(r'^[0-9a-z]{1,7}$').hasMatch(token)) return null;
final value = int.tryParse(token, radix: 36);
if (value == null || value < 0 || value > 0xFFFFFFFF) return null;
return value.toRadixString(16).padLeft(8, '0');
}
String _encodeMissingIndicesCompact(List<int> indices) {
final sorted = indices
.where((v) => v >= 0 && v <= 254)
.toSet()
.toList()
..sort();
if (sorted.isEmpty) return '';
final chunks = <String>[];
var start = sorted.first;
var prev = sorted.first;
for (var i = 1; i < sorted.length; i++) {
final curr = sorted[i];
if (curr == prev + 1) {
prev = curr;
continue;
}
chunks.add(
start == prev ? _toBase36(start) : '${_toBase36(start)}-${_toBase36(prev)}',
);
start = curr;
prev = curr;
}
chunks.add(
start == prev ? _toBase36(start) : '${_toBase36(start)}-${_toBase36(prev)}',
);
return chunks.join('.');
}
List<int> _decodeMissingIndicesCompact(String encoded) {
final out = <int>[];
for (final token in encoded.split('.')) {
if (token.isEmpty) continue;
if (!token.contains('-')) {
final value = int.tryParse(token, radix: 36);
if (value == null || value < 0 || value > 254) return const [];
out.add(value);
continue;
}
final parts = token.split('-');
if (parts.length != 2) return const [];
final start = int.tryParse(parts[0], radix: 36);
final end = int.tryParse(parts[1], radix: 36);
if (start == null || end == null || start < 0 || end > 254 || start > end) {
return const [];
}
for (var i = start; i <= end; i++) {
out.add(i);
}
}
return out;
}
/// Builds a compact visual waveform from real voice packet bytes.

View File

@@ -0,0 +1,129 @@
import 'package:flutter/material.dart';
import '../../models/contact.dart';
import '../../services/trail_color_service.dart';
import '../../utils/avatar_label_helper.dart';
class ContactAvatar extends StatelessWidget {
final Contact contact;
final double radius;
final String? displayName;
const ContactAvatar({
super.key,
required this.contact,
this.radius = 20,
this.displayName,
});
@override
Widget build(BuildContext context) {
final backgroundColor = _getBackgroundColor(context);
final foregroundColor = _getForegroundColor(backgroundColor);
final emoji = contact.roleEmoji;
if (emoji != null && emoji.isNotEmpty) {
return _buildAvatarFrame(
backgroundColor: backgroundColor,
child: Text(emoji, style: TextStyle(fontSize: radius * 1.05)),
);
}
if (_shouldUseLabelFallback) {
return _buildAvatarFrame(
backgroundColor: backgroundColor,
child: Text(
AvatarLabelHelper.buildLabel(displayName ?? contact.displayName),
style: TextStyle(
color: foregroundColor,
fontSize: radius * 0.68,
fontWeight: FontWeight.w700,
letterSpacing: -0.4,
),
),
);
}
return _buildAvatarFrame(
backgroundColor: backgroundColor,
child: Icon(
_getTypeIcon(contact.type),
color: foregroundColor,
size: radius,
),
);
}
Widget _buildAvatarFrame({
required Color backgroundColor,
required Widget child,
}) {
if (_usesSquareShape) {
return Container(
width: radius * 2,
height: radius * 2,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(radius * 0.6),
),
alignment: Alignment.center,
child: child,
);
}
return CircleAvatar(
radius: radius,
backgroundColor: backgroundColor,
child: child,
);
}
bool get _shouldUseLabelFallback =>
contact.type == ContactType.chat ||
contact.type == ContactType.channel ||
contact.type == ContactType.room;
bool get _usesSquareShape =>
contact.type == ContactType.channel || contact.type == ContactType.room;
Color _getBackgroundColor(BuildContext context) {
if (_shouldUseLabelFallback || (contact.roleEmoji?.isNotEmpty ?? false)) {
return TrailColorService.getTrailColor(contact);
}
switch (contact.type) {
case ContactType.none:
return Theme.of(context).colorScheme.surfaceContainerHighest;
case ContactType.chat:
return Colors.blue;
case ContactType.repeater:
return Colors.orange;
case ContactType.room:
return Colors.purple;
case ContactType.channel:
return Colors.teal;
}
}
Color _getForegroundColor(Color backgroundColor) {
return ThemeData.estimateBrightnessForColor(backgroundColor) ==
Brightness.dark
? Colors.white
: Colors.black87;
}
IconData _getTypeIcon(ContactType type) {
switch (type) {
case ContactType.none:
return Icons.help_outline;
case ContactType.chat:
return Icons.person;
case ContactType.repeater:
return Icons.router;
case ContactType.room:
return Icons.meeting_room;
case ContactType.channel:
return Icons.public;
}
}
}

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:latlong2/latlong.dart';
import '../../l10n/app_localizations.dart';
import '../../utils/location_formats.dart';
/// Reusable location display widget with tap-to-show modal
/// Shows coordinates in a compact format with ability to view all formats
@@ -35,9 +36,9 @@ class LocationDisplay extends StatelessWidget {
Text(
'${location.latitude.toStringAsFixed(5)}, ${location.longitude.toStringAsFixed(5)}',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontFamily: 'monospace',
fontWeight: FontWeight.w600,
),
fontFamily: 'monospace',
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 6),
Icon(
@@ -54,9 +55,9 @@ class LocationDisplay extends StatelessWidget {
// Non-compact version (just text)
return Text(
'${location.latitude.toStringAsFixed(5)}, ${location.longitude.toStringAsFixed(5)}',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontFamily: 'monospace',
),
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(fontFamily: 'monospace'),
);
}
@@ -79,10 +80,7 @@ class LocationDisplay extends StatelessWidget {
children: [
const Text(
'Location Formats',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
IconButton(
icon: const Icon(Icons.close),
@@ -121,7 +119,7 @@ class LocationDisplay extends StatelessWidget {
_buildFormatRow(
context,
'Plus Code',
_convertToPlusCode(location.latitude, location.longitude),
formatPlusCode(location.latitude, location.longitude),
),
const SizedBox(height: 8),
],
@@ -140,9 +138,9 @@ class LocationDisplay extends StatelessWidget {
Text(
label,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: Colors.grey,
fontWeight: FontWeight.w500,
),
color: Colors.grey,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 4),
InkWell(
@@ -150,7 +148,9 @@ class LocationDisplay extends StatelessWidget {
Clipboard.setData(ClipboardData(text: value));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.copiedToClipboard(label)),
content: Text(
AppLocalizations.of(context)!.copiedToClipboard(label),
),
duration: const Duration(seconds: 2),
),
);
@@ -168,9 +168,9 @@ class LocationDisplay extends StatelessWidget {
child: Text(
value,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontFamily: 'monospace',
fontWeight: FontWeight.w500,
),
fontFamily: 'monospace',
fontWeight: FontWeight.w500,
),
),
),
Icon(
@@ -242,31 +242,4 @@ class LocationDisplay extends StatelessWidget {
// Full MGRS would require UTM conversion library
return '$zone$letter (approximate)';
}
/// Convert to Google Plus Code format
/// Simplified implementation - returns approximate code
String _convertToPlusCode(double lat, double lon) {
// This is a simplified version - full Plus Code requires the open_location_code package
const base = '23456789CFGHJMPQRVWX';
// Normalize coordinates
lat = (lat + 90) / 180; // 0 to 1
lon = (lon + 180) / 360; // 0 to 1
String code = '';
for (int i = 0; i < 8; i++) {
if (i == 4) code += '+';
int latDigit = (lat * 20).floor() % 20;
int lonDigit = (lon * 20).floor() % 20;
code += base[latDigit];
code += base[lonDigit];
lat = (lat * 20) % 1;
lon = (lon * 20) % 1;
}
return code;
}
}

View File

@@ -16,14 +16,24 @@ class ConnectionDialog extends StatefulWidget {
class _ConnectionDialogState extends State<ConnectionDialog>
with SingleTickerProviderStateMixin {
late TabController _tabController;
late final ConnectionProvider _connectionProvider;
final NetworkScannerService _networkScanner = NetworkScannerService();
final List<DiscoveredServer> _discoveredServers = [];
int _scannedCount = 0;
int _totalToScan = 0;
String? _connectingToServerUrl; // Track which server is being connected to
int _lastTabIndex = 0;
String?
_connectingToServerKey; // Track which server is being connected to (ip:port)
// Named listener method for proper cleanup
void _onTabChanged() {
if (_tabController.index == _lastTabIndex) return;
_lastTabIndex = _tabController.index;
if (_tabController.index == 0) {
_refreshBleDevices();
}
if (_tabController.index == 1) {
// Switched to network tab
if (_networkScanner.hasCachedResults && _discoveredServers.isEmpty) {
@@ -46,13 +56,17 @@ class _ConnectionDialogState extends State<ConnectionDialog>
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
// Start BLE scan by default
final connectionProvider = Provider.of<ConnectionProvider>(
_connectionProvider = Provider.of<ConnectionProvider>(
context,
listen: false,
);
connectionProvider.startScan();
// Defer scan startup until after the first frame so Provider listeners
// are not notified while this dialog is still being built.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_refreshBleDevices();
});
// Set up network scanner callbacks
_networkScanner.onServerDiscovered = (server) {
@@ -81,11 +95,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
@override
void dispose() {
final connectionProvider = Provider.of<ConnectionProvider>(
context,
listen: false,
);
connectionProvider.stopScan();
_connectionProvider.stopScan();
_networkScanner.stopScan();
// Remove listener before disposing to prevent memory leaks
_tabController.removeListener(_onTabChanged);
@@ -103,6 +113,12 @@ class _ConnectionDialogState extends State<ConnectionDialog>
_networkScanner.scan();
}
Future<void> _refreshBleDevices() async {
await _connectionProvider.stopScan();
if (!mounted) return;
await _connectionProvider.startScan();
}
Color _getSignalColor(int rssi) {
if (rssi >= -60) return Colors.green;
if (rssi >= -75) return Colors.orange;
@@ -220,10 +236,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
Icons.refresh,
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
onPressed: () {
connectionProvider.stopScan();
connectionProvider.startScan();
},
onPressed: _refreshBleDevices,
),
],
),
@@ -257,10 +270,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
),
const SizedBox(height: 8),
TextButton.icon(
onPressed: () {
connectionProvider.stopScan();
connectionProvider.startScan();
},
onPressed: _refreshBleDevices,
icon: const Icon(Icons.refresh),
label: Text(AppLocalizations.of(context)!.scanAgain),
),
@@ -361,61 +371,16 @@ class _ConnectionDialogState extends State<ConnectionDialog>
}
Widget _buildNetworkServersTab() {
final connectionProvider = context.watch<ConnectionProvider>();
final bool showingCachedResults =
!_networkScanner.isScanning &&
_networkScanner.hasCachedResults &&
_discoveredServers.isNotEmpty;
final bool isConnectingToSse = connectionProvider.isSseClientConnecting;
final int sseReconnectAttempt =
connectionProvider.sseClientReconnectionAttempt;
final int sseMaxReconnects =
connectionProvider.sseClientMaxReconnectionAttempts;
return Column(
children: [
// SSE Reconnection banner (show when reconnecting)
if (isConnectingToSse && sseReconnectAttempt > 0)
Container(
margin: const EdgeInsets.fromLTRB(16, 16, 16, 8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.tertiaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context).colorScheme.onTertiaryContainer,
),
),
const SizedBox(width: 12),
Expanded(
child: Text(
'Reconnecting to server... (Attempt $sseReconnectAttempt/$sseMaxReconnects)',
style: TextStyle(
color: Theme.of(context).colorScheme.onTertiaryContainer,
fontSize: 13,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
// Info banner
Container(
margin: EdgeInsets.fromLTRB(
16,
isConnectingToSse && sseReconnectAttempt > 0 ? 8 : 16,
16,
16,
),
margin: const EdgeInsets.fromLTRB(16, 16, 16, 16),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
@@ -432,7 +397,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
child: Text(
showingCachedResults
? 'Showing cached results. Tap refresh to rescan.'
: 'Scanning local network for shared MeshCore devices on port 12929',
: 'Scanning local network for MeshCore WiFi devices on port 5000',
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimaryContainer,
fontSize: 13,
@@ -505,10 +470,11 @@ class _ConnectionDialogState extends State<ConnectionDialog>
itemCount: _discoveredServers.length,
itemBuilder: (context, index) {
final server = _discoveredServers[index];
final serverKey = '${server.ipAddress}:${server.port}';
final isConnectingToThisServer =
_connectingToServerUrl == server.serverUrl;
_connectingToServerKey == serverKey;
final isAnyConnectionInProgress =
isConnectingToSse || _connectingToServerUrl != null;
_connectingToServerKey != null;
return Container(
margin: const EdgeInsets.symmetric(
@@ -593,7 +559,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
// Mark this server as connecting
setState(() {
_connectingToServerUrl = server.serverUrl;
_connectingToServerKey = serverKey;
});
try {
@@ -607,8 +573,9 @@ class _ConnectionDialogState extends State<ConnectionDialog>
);
}
await connectionProvider.connectToSseServer(
serverUrl: server.serverUrl,
await connectionProvider.connectTcp(
server.ipAddress,
server.port,
);
await appProvider.initialize();
@@ -619,7 +586,7 @@ class _ConnectionDialogState extends State<ConnectionDialog>
// Clear connecting state on error
if (mounted) {
setState(() {
_connectingToServerUrl = null;
_connectingToServerKey = null;
});
// Clean up error message (remove "Exception: " prefix)

View File

@@ -11,6 +11,7 @@ import '../../providers/map_provider.dart';
import '../../providers/app_provider.dart';
import 'direct_message_sheet.dart';
import 'room_login_sheet.dart';
import '../../utils/location_formats.dart';
import '../../utils/toast_logger.dart';
import '../../utils/battery_display_helper.dart';
import '../../l10n/app_localizations.dart';
@@ -69,6 +70,9 @@ class ContactTile extends StatelessWidget {
// Get room login state if this is a room
final connectionProvider = context.watch<ConnectionProvider>();
final isPingInProgress = connectionProvider.isPingInProgress(
contact.publicKey,
);
final roomLoginState = contact.type == ContactType.room
? connectionProvider.getRoomLoginState(contact.publicKeyPrefix)
: null;
@@ -187,6 +191,17 @@ class ContactTile extends StatelessWidget {
),
),
],
if (isPingInProgress) ...[
const SizedBox(width: 6),
SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context).colorScheme.primary,
),
),
],
],
),
subtitle: isSimpleMode
@@ -457,39 +472,43 @@ class ContactTile extends StatelessWidget {
_showContactDetails(context, contact);
}
},
onLongPress: () async {
final connectionProvider = context.read<ConnectionProvider>();
onLongPress: isPingInProgress
? null
: () async {
final connectionProvider = context.read<ConnectionProvider>();
// Determine if we should use flooding (no path) or direct (has path)
final hasPath = contact.hasPath;
// Determine if we should use flooding (no path) or direct (has path)
final hasPath = contact.hasPath;
// Use smart ping with automatic fallback
final result = await connectionProvider.smartPing(
contactPublicKey: contact.publicKey,
hasPath: hasPath,
onRetryWithFlooding: () {
// Called when retrying with flooding after direct timeout
if (context.mounted) {
ToastLogger.warning(
context,
AppLocalizations.of(
context,
)!.directPingTimeout(contact.displayName),
// Use smart ping with automatic fallback
final result = await connectionProvider.smartPing(
contactPublicKey: contact.publicKey,
hasPath: hasPath,
onRetryWithFlooding: () {
// Called when retrying with flooding after direct timeout
if (context.mounted) {
ToastLogger.warning(
context,
AppLocalizations.of(
context,
)!.directPingTimeout(contact.displayName),
);
}
},
);
}
},
);
// Show final result
if (context.mounted) {
if (!result.success) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.pingFailed(contact.displayName),
);
}
}
},
// Show final result
if (context.mounted) {
if (!result.success) {
ToastLogger.error(
context,
AppLocalizations.of(
context,
)!.pingFailed(contact.displayName),
);
}
}
},
),
);
}
@@ -602,8 +621,12 @@ class ContactTile extends StatelessWidget {
minChildSize: 0.4,
maxChildSize: 0.9,
expand: false,
builder: (context, scrollController) => Column(
children: [
builder: (context, scrollController) {
final isPingInProgress = context
.watch<ConnectionProvider>()
.isPingInProgress(contact.publicKey);
return Column(
children: [
// Handle bar
Container(
margin: const EdgeInsets.only(top: 8, bottom: 16),
@@ -827,7 +850,7 @@ class ContactTile extends StatelessWidget {
_detailRowWithCopy(
context,
'Plus Code',
_convertToPlusCode(
formatPlusCode(
contact.displayLocation!.latitude,
contact.displayLocation!.longitude,
),
@@ -846,15 +869,25 @@ class ContactTile extends StatelessWidget {
),
),
TextButton.icon(
onPressed: () {
final connectionProvider = context
.read<ConnectionProvider>();
connectionProvider.requestTelemetry(
contact.publicKey,
zeroHop: true,
);
},
icon: const Icon(Icons.refresh, size: 18),
onPressed: isPingInProgress
? null
: () {
final connectionProvider = context
.read<ConnectionProvider>();
connectionProvider.requestTelemetry(
contact.publicKey,
zeroHop: true,
);
},
icon: isPingInProgress
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.refresh, size: 18),
label: Text(AppLocalizations.of(context)!.refresh),
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(
@@ -990,8 +1023,9 @@ class ContactTile extends StatelessWidget {
],
),
),
],
),
],
);
},
),
);
}
@@ -1113,34 +1147,6 @@ class ContactTile extends StatelessWidget {
return '$zone$letter (approximate)';
}
/// Convert to Google Plus Code format
/// Simplified implementation - returns approximate code
String _convertToPlusCode(double lat, double lon) {
// This is a simplified version - full Plus Code requires the open_location_code package
// For now, return a placeholder that shows it's not fully implemented
const base = '23456789CFGHJMPQRVWX';
// Normalize coordinates
lat = (lat + 90) / 180; // 0 to 1
lon = (lon + 180) / 360; // 0 to 1
String code = '';
for (int i = 0; i < 8; i++) {
if (i == 4) code += '+';
int latDigit = (lat * 20).floor() % 20;
int lonDigit = (lon * 20).floor() % 20;
code += base[latDigit];
code += base[lonDigit];
lat = (lat * 20) % 1;
lon = (lon * 20) % 1;
}
return code;
}
IconData _getTypeIcon(ContactType type) {
switch (type) {
case ContactType.chat:

View File

@@ -0,0 +1,394 @@
import 'package:flutter/material.dart';
import 'package:meshcore_client/meshcore_client.dart';
class SpectrumScanPanel extends StatelessWidget {
final ThemeData theme;
final bool scanSupported;
final bool isRunning;
final double rangeMinMhz;
final double rangeMaxMhz;
final RangeValues rangeValues;
final double bandwidthKhz;
final int? selectedFrequencyKhz;
final List<SpectrumScanCandidate> graphCandidates;
final List<SpectrumScanCandidate> selectableCandidates;
final ValueChanged<RangeValues> onRangeChanged;
final ValueChanged<int?> onCandidateChanged;
final VoidCallback onRunScan;
final VoidCallback onApplySelected;
const SpectrumScanPanel({
super.key,
required this.theme,
required this.scanSupported,
required this.isRunning,
required this.rangeMinMhz,
required this.rangeMaxMhz,
required this.rangeValues,
required this.bandwidthKhz,
required this.selectedFrequencyKhz,
required this.graphCandidates,
required this.selectableCandidates,
required this.onRangeChanged,
required this.onCandidateChanged,
required this.onRunScan,
required this.onApplySelected,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(
alpha: 0.45,
),
borderRadius: BorderRadius.circular(18),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.tune, color: theme.colorScheme.primary),
const SizedBox(width: 10),
Expanded(
child: Text(
'Power Scan',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
FilledButton.icon(
onPressed: scanSupported && !isRunning ? onRunScan : null,
icon: isRunning
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.radar),
label: Text(
scanSupported
? (isRunning ? 'Scanning' : 'Scan')
: 'Unavailable',
),
),
],
),
const SizedBox(height: 8),
Text(
scanSupported
? 'Full range with bandwidth footprint. Firmware enforces hardware band limits and pauses the mesh while scanning.'
: 'Full range with bandwidth footprint. This companion does not support spectrum scan mode, so scanning is disabled.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 14),
_FrequencyRangePreview(
minMhz: rangeMinMhz,
maxMhz: rangeMaxMhz,
selectedRange: rangeValues,
selectedBandwidthKhz: bandwidthKhz,
selectedFrequencyKhz: selectedFrequencyKhz,
candidates: graphCandidates,
),
const SizedBox(height: 10),
Wrap(
spacing: 14,
runSpacing: 6,
children: [
_LegendChip(
color: theme.colorScheme.primary,
label: 'Quiet',
),
const _LegendChip(color: Colors.orange, label: 'Moderate'),
_LegendChip(
color: theme.colorScheme.error,
label: 'Busy',
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${rangeValues.start.toStringAsFixed(3)} MHz',
style: theme.textTheme.labelMedium,
),
Text(
'${rangeValues.end.toStringAsFixed(3)} MHz',
style: theme.textTheme.labelMedium,
),
],
),
RangeSlider(
values: rangeValues,
min: rangeMinMhz,
max: rangeMaxMhz,
divisions: (((rangeMaxMhz - rangeMinMhz) * 20).round()).clamp(
1,
400,
),
labels: RangeLabels(
rangeValues.start.toStringAsFixed(3),
rangeValues.end.toStringAsFixed(3),
),
onChanged: onRangeChanged,
),
if (selectableCandidates.isEmpty) ...[
const SizedBox(height: 6),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
decoration: BoxDecoration(
color: theme.colorScheme.surface.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: Text(
scanSupported
? 'No scan results yet. Adjust the range and run a scan to populate candidate frequencies.'
: 'Spectrum preview only. This companion can display the configured span, but cannot scan for open channels.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
] else ...[
const SizedBox(height: 10),
DropdownButtonFormField<int>(
initialValue: selectedFrequencyKhz,
isExpanded: true,
decoration: const InputDecoration(
labelText: 'Candidate frequency',
border: OutlineInputBorder(),
helperText: 'Best frequencies for the current bandwidth',
),
items: selectableCandidates.map((candidate) {
return DropdownMenuItem<int>(
value: candidate.centerFrequencyKhz,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${candidate.centerFrequencyMhz.toStringAsFixed(3)} MHz',
overflow: TextOverflow.ellipsis,
),
Text(
'${candidate.occupancyPercent}% occupied | peak ${candidate.peakRssiDbm} dBm',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
],
),
);
}).toList(),
selectedItemBuilder: (context) {
return selectableCandidates.map((candidate) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
'${candidate.centerFrequencyMhz.toStringAsFixed(3)} MHz',
overflow: TextOverflow.ellipsis,
),
);
}).toList();
},
onChanged: onCandidateChanged,
),
const SizedBox(height: 10),
Align(
alignment: Alignment.centerRight,
child: OutlinedButton.icon(
onPressed: selectedFrequencyKhz == null
? null
: onApplySelected,
icon: const Icon(Icons.north_east),
label: const Text('Use selected frequency'),
),
),
],
],
),
);
}
}
class _LegendChip extends StatelessWidget {
final Color color;
final String label;
const _LegendChip({required this.color, required this.label});
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
),
const SizedBox(width: 6),
Text(label, style: Theme.of(context).textTheme.labelMedium),
],
);
}
}
class _FrequencyRangePreview extends StatelessWidget {
final double minMhz;
final double maxMhz;
final RangeValues selectedRange;
final double selectedBandwidthKhz;
final int? selectedFrequencyKhz;
final List<SpectrumScanCandidate> candidates;
const _FrequencyRangePreview({
required this.minMhz,
required this.maxMhz,
required this.selectedRange,
required this.selectedBandwidthKhz,
required this.selectedFrequencyKhz,
required this.candidates,
});
double _positionFor(double mhz) {
final span = maxMhz - minMhz;
if (span <= 0) return 0;
return ((mhz - minMhz) / span).clamp(0.0, 1.0);
}
Color _candidateColor(BuildContext context, int occupancyPercent) {
final scheme = Theme.of(context).colorScheme;
if (occupancyPercent <= 10) return scheme.primary;
if (occupancyPercent <= 35) return Colors.orange;
return scheme.error;
}
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final spanMhz = maxMhz - minMhz;
final selectedFreqMhz = selectedFrequencyKhz != null
? selectedFrequencyKhz! / 1000.0
: null;
final bwMhz = selectedBandwidthKhz / 1000.0;
return LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth;
final rangeLeft = _positionFor(selectedRange.start) * width;
final rangeRight = _positionFor(selectedRange.end) * width;
double? bwLeft;
double? bwWidth;
if (selectedFreqMhz != null && spanMhz > 0) {
bwLeft = _positionFor(selectedFreqMhz - (bwMhz / 2)) * width;
final bwRight = _positionFor(selectedFreqMhz + (bwMhz / 2)) * width;
bwWidth = (bwRight - bwLeft).clamp(4.0, width);
}
return Container(
height: 108,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
gradient: LinearGradient(
colors: [
scheme.surface,
scheme.surfaceContainerHighest.withValues(alpha: 0.9),
],
),
border: Border.all(color: scheme.outlineVariant),
),
child: Stack(
children: [
Positioned.fill(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 12,
),
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
gradient: LinearGradient(
colors: [
scheme.primary.withValues(alpha: 0.12),
scheme.tertiary.withValues(alpha: 0.08),
scheme.primary.withValues(alpha: 0.12),
],
),
),
),
),
),
Positioned(
left: rangeLeft,
top: 12,
width: (rangeRight - rangeLeft).clamp(8.0, width),
height: 56,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: scheme.primary.withValues(alpha: 0.20),
border: Border.all(color: scheme.primary),
),
),
),
if (bwLeft != null && bwWidth != null)
Positioned(
left: bwLeft,
top: 28,
width: bwWidth,
height: 24,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(999),
color: scheme.tertiary.withValues(alpha: 0.32),
border: Border.all(color: scheme.tertiary),
),
),
),
for (final candidate in candidates)
Positioned(
left: (_positionFor(candidate.centerFrequencyMhz) * width)
.clamp(10.0, width - 18.0),
top: 72,
child: Column(
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _candidateColor(
context,
candidate.occupancyPercent,
),
),
),
const SizedBox(height: 4),
Text(
candidate.centerFrequencyMhz.toStringAsFixed(3),
style: Theme.of(context).textTheme.labelSmall,
),
],
),
),
],
),
);
},
);
}
}

View File

@@ -849,6 +849,7 @@ class DrawingToolbar extends StatelessWidget {
contactPublicKey: room.publicKey,
text: message,
messageId: messageId,
contact: room,
);
debugPrint(' ✅ Sent successfully');

View File

@@ -1,18 +1,21 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_avif/flutter_avif.dart';
import 'package:provider/provider.dart';
import '../../models/contact.dart';
import '../../models/message.dart';
import '../../providers/app_provider.dart';
import '../../providers/connection_provider.dart';
import '../../providers/contacts_provider.dart';
import '../../providers/image_provider.dart' as ip;
import '../../utils/image_message_parser.dart';
import '../../utils/transmission_target_resolver.dart';
import 'transfer_timeout.dart';
/// A message bubble that shows a received or sent image.
///
/// On first render the image is not yet fetched (only the IE1 envelope is
/// known). The user taps the thumbnail placeholder → IR1 fetch request is
/// On first render the image is not yet fetched (only the IE2 envelope is
/// known). The user taps the thumbnail placeholder → IR2 fetch request is
/// sent → binary fragments stream in → bubble rebuilds with the full image.
class ImageMessageBubble extends StatefulWidget {
final Message message;
@@ -29,8 +32,16 @@ class ImageMessageBubble extends StatefulWidget {
}
class _ImageMessageBubbleState extends State<ImageMessageBubble> {
static const int _maxFetchHops = 3;
bool _isRequesting = false;
String? _errorText;
Timer? _requestTimeoutTimer;
@override
void dispose() {
_requestTimeoutTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
@@ -48,12 +59,32 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
return Consumer<ip.ImageProvider>(
builder: (context, imageProvider, _) {
final contactsProvider = context.read<ContactsProvider>();
final session = imageProvider.session(envelope.sessionId);
final sender = TransmissionTargetResolver.resolveLocalTarget(
contactsProvider: contactsProvider,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope.senderKey6,
senderName: widget.message.senderName,
);
final effectivePathLen = sender != null && sender.outPathLen >= 0
? sender.outPathLen
: widget.message.pathLen;
final isComplete = imageProvider.isComplete(envelope.sessionId);
final eta = imageProvider.estimateRemainingTransferTime(
envelope.sessionId,
);
if (_isRequesting && isComplete) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _isRequesting = false);
if (mounted) {
setState(() {
_isRequesting = false;
_errorText = null;
});
}
});
}
@@ -82,6 +113,10 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
received: received,
total: total,
envelope: envelope,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
pathLen: effectivePathLen,
),
),
const SizedBox(height: 4),
@@ -93,12 +128,13 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
received: received,
total: total,
envelope: envelope,
pathLen: widget.message.pathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
error: _errorText,
isSentByMe: widget.isSentByMe,
eta: eta,
pathLen: effectivePathLen,
),
style: TextStyle(
fontSize: 11,
@@ -123,6 +159,10 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
required int received,
required int total,
required ImageEnvelope envelope,
required int? radioBw,
required int? radioSf,
required int? radioCr,
required int pathLen,
}) {
if (isComplete && imageBytes != null) {
return AspectRatio(
@@ -154,12 +194,48 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
'$received/$total',
style: const TextStyle(color: Colors.white, fontSize: 11),
),
Positioned(
top: 8,
right: 8,
child: IconButton(
onPressed: () => _cancelReceive(envelope.sessionId),
icon: const Icon(Icons.close, size: 20),
color: Colors.white70,
tooltip: 'Cancel image receive',
),
),
] else if (_errorText != null) ...[
const Icon(Icons.broken_image, color: Colors.red, size: 36),
Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.broken_image, color: Colors.red, size: 36),
const SizedBox(height: 8),
TextButton.icon(
onPressed: () => _requestAndFetch(
envelope,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
pathLen: pathLen,
),
icon: const Icon(Icons.refresh, size: 18),
label: const Text('Retry'),
style: TextButton.styleFrom(
foregroundColor: Colors.white70,
),
),
],
),
] else ...[
// Tap-to-load icon.
IconButton(
onPressed: () => _requestAndFetch(envelope),
onPressed: () => _requestAndFetch(
envelope,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
pathLen: pathLen,
),
icon: const Icon(Icons.download_rounded, size: 40),
color: Colors.white70,
tooltip: 'Load image',
@@ -171,18 +247,137 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
);
}
Future<void> _requestAndFetch(ImageEnvelope envelope) async {
Future<void> _requestAndFetch(
ImageEnvelope envelope, {
int? radioBw,
int? radioSf,
int? radioCr,
int pathLen = 0,
}) async {
if (_isRequesting) return;
final sender = _resolveSender(envelope);
if (sender == null) {
setState(() => _errorText = 'Sender not reachable');
setState(() {
_isRequesting = true;
_errorText = null;
});
final conn = context.read<ConnectionProvider>();
final imageProvider = context.read<ip.ImageProvider>();
imageProvider.resumeIncomingSession(envelope.sessionId);
final contactsProvider = context.read<ContactsProvider>();
final appProvider = context.read<AppProvider>();
var resolution = await TransmissionTargetResolver.resolveFetchTarget(
contactsProvider: contactsProvider,
refreshContacts: conn.getContacts,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope.senderKey6,
senderName: widget.message.senderName,
maxFetchHops: _maxFetchHops,
);
if (!mounted) return;
if (resolution.failure == TransmissionTargetFailure.unknownContact) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender contact is unknown. Sync contacts first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unknownRoute) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender route is unknown. Sync contacts/path first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.tooFar) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Message is too far (${resolution.hops} hops, max ${resolution.maxHops}).',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unreachable) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender route did not respond to a path check. Sync contacts/path and try again.',
);
return;
}
final conn = context.read<ConnectionProvider>();
var sender = resolution.target!;
var routeVerified = await appProvider.verifyRawTransportRoute(sender);
if (!mounted) return;
if (!routeVerified) {
await conn.getContacts();
if (!mounted) return;
resolution = await TransmissionTargetResolver.resolveFetchTarget(
contactsProvider: contactsProvider,
refreshContacts: conn.getContacts,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope.senderKey6,
senderName: widget.message.senderName,
maxFetchHops: _maxFetchHops,
);
if (!mounted) return;
if (resolution.failure == TransmissionTargetFailure.unknownContact) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender contact is unknown. Sync contacts first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unknownRoute) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender route is unknown. Sync contacts/path first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.tooFar) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Message is too far (${resolution.hops} hops, max ${resolution.maxHops}).',
);
return;
}
sender = resolution.target!;
routeVerified = await appProvider.verifyRawTransportRoute(sender);
if (!mounted) return;
if (!routeVerified) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Sender route did not respond on the raw transport path.',
);
return;
}
}
if (sender.outPathLen >= 2) {
_showToast(
'Image fetch over ${sender.outPathLen} hops may take a while.',
);
}
setState(() => _errorText = null);
final deviceKey = conn.deviceInfo.publicKey;
if (deviceKey == null || deviceKey.length < 6) {
setState(() => _errorText = 'Device key unavailable');
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch image',
'Device key is unavailable.',
);
return;
}
@@ -190,40 +385,119 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
.sublist(0, 6)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join();
final request = ImageFetchRequest(
sessionId: envelope.sessionId,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
setState(() {
_isRequesting = true;
_errorText = null;
});
// If we already have some fragments, request only what's missing.
final missing = imageProvider.missingFragmentIndices(envelope.sessionId);
final isPartialResume =
missing.isNotEmpty && missing.length < envelope.total;
final request = isPartialResume
? ImageFetchRequest(
sessionId: envelope.sessionId,
want: 'missing',
missingIndices: missing,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
)
: ImageFetchRequest(
sessionId: envelope.sessionId,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
final sent = await conn.sendTextMessage(
contactPublicKey: sender.publicKey,
text: request.encode(),
contact: sender,
);
if (!sent && mounted) {
setState(() {
_isRequesting = false;
_errorText = 'Image unavailable right now';
});
final payload = request.encodeBinary();
try {
debugPrint(
'📷 [ImageMessageBubble] Outgoing image fetch request: session=${envelope.sessionId} want=${isPartialResume ? 'missing' : 'all'} target=${sender.advName} hops=${sender.outPathLen}',
);
await conn.sendRawVoicePacket(
contactPath: sender.outPath,
contactPathLen: sender.outPathLen,
payload: payload,
);
} catch (_) {
if (mounted) {
_showToast('Image fetch failed to send request');
setState(() {
_isRequesting = false;
_errorText = 'Image unavailable right now';
});
}
return;
}
if (!mounted) return;
// Timeout = 2× estimated LoRa airtime (min 30s).
final effectivePathLen = sender.outPathLen >= 0
? sender.outPathLen
: pathLen;
final txEstimate = estimateImageTransmitDuration(
fragmentCount: missing.isEmpty ? envelope.total : missing.length,
sizeBytes: missing.isEmpty
? envelope.sizeBytes
: (envelope.sizeBytes * missing.length / envelope.total).round(),
pathLen: effectivePathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
_requestTimeoutTimer?.cancel();
_requestTimeoutTimer = TransferTimeout.start(
txEstimate: txEstimate,
onTimeout: () {
if (mounted &&
_isRequesting &&
!imageProvider.isComplete(envelope.sessionId)) {
_showToast('Image fetch timed out');
setState(() {
_isRequesting = false;
_errorText = 'Image fetch timed out';
});
}
},
);
}
Contact? _resolveSender(ImageEnvelope envelope) {
final contactsProvider = context.read<ContactsProvider>();
final senderPrefix = widget.message.senderPublicKeyPrefix;
if (senderPrefix != null && senderPrefix.length >= 6) {
final c = contactsProvider.findContactByPrefix(
Uint8List.fromList(senderPrefix.sublist(0, 6)),
);
if (c != null) return c;
}
return contactsProvider.findContactByPrefixHex(envelope.senderKey6);
void _showToast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), duration: const Duration(seconds: 3)),
);
}
void _cancelReceive(String sessionId) {
if (!mounted) return;
_requestTimeoutTimer?.cancel();
context.read<ip.ImageProvider>().cancelIncomingSession(sessionId);
_showToast('Image receive canceled');
setState(() {
_isRequesting = false;
_errorText = 'Image receive canceled';
});
}
void _clearRequestState() {
if (!mounted) return;
setState(() {
_isRequesting = false;
});
}
Future<void> _showBlockingAlert(String title, String message) async {
if (!mounted) return;
_showToast('$title: $message');
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(title),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('OK'),
),
],
),
);
}
static String _statusText({
@@ -238,6 +512,7 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
required int? radioCr,
required String? error,
required bool isSentByMe,
required Duration? eta,
}) {
final txEstimate = estimateImageTransmitDuration(
fragmentCount: envelope.total,
@@ -250,7 +525,10 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
final txEstimateLabel = _formatTransmitEstimate(txEstimate);
if (error != null) return error;
if (isRequesting) return '📥 Loading… $received/$total · $txEstimateLabel';
if (isRequesting) {
final etaLabel = _formatEta(eta);
return '📥 Loading… $received/$total · $etaLabel · $txEstimateLabel';
}
if (isComplete) {
final base =
'🖼️ ${envelope.width}×${envelope.height} ${envelope.format.label}';
@@ -268,6 +546,14 @@ class _ImageMessageBubbleState extends State<ImageMessageBubble> {
return '~${minutes}m ${seconds}s tx';
}
static String _formatEta(Duration? eta) {
if (eta == null || eta <= Duration.zero) return 'ETA --';
if (eta.inSeconds < 60) return 'ETA ~${eta.inSeconds}s';
final minutes = eta.inMinutes;
final seconds = eta.inSeconds % 60;
return 'ETA ~${minutes}m ${seconds}s';
}
void _showFullScreen(BuildContext context, Uint8List imageBytes) {
showGeneralDialog<void>(
context: context,

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,160 @@
import 'package:flutter/material.dart';
import '../../models/contact.dart';
import '../../models/message.dart';
import '../../utils/avatar_label_helper.dart';
import '../../utils/message_extensions.dart';
import '../common/contact_avatar.dart';
Widget buildMessageHeaderAvatar(
BuildContext context, {
required bool isOwnMessage,
required bool isChannelMessage,
required dynamic senderContact,
required String displayName,
}) {
if (isOwnMessage) {
return CircleAvatar(
radius: 10.5,
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
child: Icon(
Icons.account_circle,
size: 16,
color: Theme.of(context).colorScheme.primary,
),
);
}
if (senderContact is Contact) {
return ContactAvatar(
contact: senderContact,
radius: 10.5,
displayName: displayName,
);
}
final background = isChannelMessage
? Colors.teal.withValues(alpha: 0.16)
: Theme.of(context).colorScheme.surfaceContainerHighest;
final foreground = isChannelMessage
? Colors.teal.shade800
: Theme.of(context).colorScheme.onSurfaceVariant;
return CircleAvatar(
radius: 10.5,
backgroundColor: background,
child: Text(
AvatarLabelHelper.buildLabel(displayName),
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w700,
color: foreground,
letterSpacing: -0.2,
),
),
);
}
Widget buildBubbleMetaFooter(
BuildContext context, {
required Message message,
required bool isSarMarker,
}) {
final metaColor = Theme.of(
context,
).textTheme.labelSmall?.color?.withValues(alpha: 0.68);
final items = <Widget>[];
if (!isSarMarker && message.pathLen < 255) {
items.addAll([
Icon(Icons.alt_route, size: 11, color: metaColor),
const SizedBox(width: 3),
Text(
message.pathLen == 0 ? 'direct' : '${message.pathLen}hop',
style: Theme.of(
context,
).textTheme.labelSmall?.copyWith(color: metaColor),
),
Text(
'',
style: Theme.of(
context,
).textTheme.labelSmall?.copyWith(color: metaColor),
),
]);
}
items.add(
Text(
message.getLocalizedTimeAgo(context),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: metaColor,
fontWeight: FontWeight.w500,
),
),
);
return Padding(
padding: const EdgeInsets.only(left: 6, right: 6, top: 1, bottom: 18),
child: Align(
alignment: Alignment.centerRight,
child: Row(mainAxisSize: MainAxisSize.min, children: items),
),
);
}
Widget buildChannelHeaderPill(
BuildContext context, {
required String label,
IconData icon = Icons.campaign_outlined,
}) {
final labelColor = Theme.of(
context,
).textTheme.labelSmall?.color?.withValues(alpha: 0.82);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: 11,
color: Theme.of(
context,
).textTheme.labelSmall?.color?.withValues(alpha: 0.7),
),
const SizedBox(width: 5),
Flexible(
child: Text(
label,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: labelColor,
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
Widget buildDirectHeaderCounterpart(
BuildContext context, {
required String label,
}) {
return buildChannelHeaderPill(
context,
label: label,
icon: Icons.alternate_email,
);
}

View File

@@ -0,0 +1,382 @@
import 'package:flutter/material.dart';
import '../../models/message.dart';
import '../../models/message_reception_details.dart';
IconData getDeliveryStatusIcon(MessageDeliveryStatus status) {
switch (status) {
case MessageDeliveryStatus.sending:
return Icons.schedule;
case MessageDeliveryStatus.sent:
return Icons.done;
case MessageDeliveryStatus.delivered:
return Icons.done_all;
case MessageDeliveryStatus.failed:
return Icons.error_outline;
case MessageDeliveryStatus.received:
return Icons.inbox;
}
}
Color getDeliveryStatusColor(MessageDeliveryStatus status) {
switch (status) {
case MessageDeliveryStatus.sending:
return Colors.orange;
case MessageDeliveryStatus.sent:
return Colors.blue;
case MessageDeliveryStatus.delivered:
return Colors.green;
case MessageDeliveryStatus.failed:
return Colors.red;
case MessageDeliveryStatus.received:
return Colors.grey;
}
}
Widget buildChannelEchoStatus(BuildContext context, Message message) {
final hasEcho = message.echoCount > 0;
if (!hasEcho) {
return const SizedBox.shrink();
}
final statusColor = getDeliveryStatusColor(message.deliveryStatus);
final rssi = message.lastEchoRssiDbm;
final snr = message.lastEchoSnrRaw != null
? message.lastEchoSnrRaw!.toSigned(8) / 4.0
: null;
final quality = linkQualityLabel(rssi, snr);
final qualityColor = linkQualityColor(quality);
return Wrap(
spacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_techChip(
context,
icon: Icons.hub_outlined,
label: 'x${message.echoCount}',
color: statusColor,
),
if (message.expectedAckTag != null)
_techChip(
context,
icon: Icons.tag,
label:
'ACK ${message.expectedAckTag!.toRadixString(16).toUpperCase()}',
color: Colors.indigo,
),
_techChip(context, icon: Icons.bolt, label: quality, color: qualityColor),
if (message.lastEchoRssiDbm != null)
_signalCapsule(
context,
icon: Icons.network_cell,
label: message.lastEchoRssiDbm!.toString(),
filled: rssiScore(message.lastEchoRssiDbm!),
color: Colors.blueGrey,
),
if (message.lastEchoSnrRaw != null)
_signalCapsule(
context,
icon: Icons.graphic_eq,
label: (message.lastEchoSnrRaw!.toSigned(8) / 4.0).toStringAsFixed(1),
filled: snrScore(message.lastEchoSnrRaw!.toSigned(8) / 4.0),
color: Colors.teal,
),
],
);
}
bool shouldShowSentChannelStats(
Message message, {
required bool showReceivedStats,
}) {
if (!message.isSentMessage || !message.isChannelMessage) {
return false;
}
final hasSignalData =
message.echoCount > 0 ||
message.lastEchoRssiDbm != null ||
message.lastEchoSnrRaw != null ||
message.expectedAckTag != null;
return showReceivedStats && hasSignalData;
}
Widget buildReceivedSignalStatus(
BuildContext context,
Message message, {
MessageReceptionDetails? receptionDetails,
required int? rssiDbm,
required double? snrDb,
}) {
final hopLabel = hopDisplayLabel(message);
return Wrap(
spacing: 4,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_techChip(
context,
icon: Icons.alt_route,
label: hopLabel,
color: Colors.indigo,
),
if (receptionDetails?.senderToReceiptMs != null)
_techChip(
context,
icon: Icons.schedule,
label: _formatMs(receptionDetails!.senderToReceiptMs!),
color: Colors.deepPurple,
),
if (receptionDetails?.estimatedTransmitMs != null)
_techChip(
context,
icon: Icons.timelapse,
label: '~${_formatMs(receptionDetails!.estimatedTransmitMs!)} tx',
color: Colors.blue,
),
if (receptionDetails?.postTransmitDelayMs != null)
_techChip(
context,
icon: Icons.hourglass_bottom,
label: '+${_formatMs(receptionDetails!.postTransmitDelayMs!)} lag',
color: Colors.orange,
),
if (receptionDetails?.pathBytesHex != null)
_techChip(
context,
icon: Icons.route,
label: receptionDetails!.pathBytesHex!,
color: Colors.brown,
),
if (rssiDbm != null || snrDb != null) ...[
_techChip(
context,
icon: Icons.bolt,
label: linkQualityLabel(rssiDbm, snrDb),
color: linkQualityColor(linkQualityLabel(rssiDbm, snrDb)),
),
if (rssiDbm != null)
_signalCapsule(
context,
icon: Icons.network_cell,
label: '$rssiDbm',
filled: rssiScore(rssiDbm),
color: Colors.blueGrey,
),
if (snrDb != null)
_signalCapsule(
context,
icon: Icons.graphic_eq,
label: snrDb.toStringAsFixed(1),
filled: snrScore(snrDb),
color: Colors.teal,
),
],
],
);
}
Widget buildSentDirectSignalStatus(
BuildContext context,
Message message, {
required int roundTripTimeMs,
required Duration txEstimate,
}) {
final estimatedTransmitMs = sanitizeEstimatedTransmitMs(
estimatedTransmitMs: txEstimate > Duration.zero
? txEstimate.inMilliseconds
: null,
senderToReceiptMs: roundTripTimeMs,
);
final postTransmitDelayMs = estimatedTransmitMs != null
? (roundTripTimeMs - estimatedTransmitMs).clamp(0, 86400000).toInt()
: null;
return Wrap(
spacing: 4,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_techChip(
context,
icon: Icons.alt_route,
label: hopDisplayLabel(message),
color: Colors.indigo,
),
_techChip(
context,
icon: Icons.schedule,
label: _formatMs(roundTripTimeMs),
color: Colors.deepPurple,
),
if (estimatedTransmitMs != null)
_techChip(
context,
icon: Icons.timelapse,
label: '~${_formatMs(estimatedTransmitMs)} tx',
color: Colors.blue,
),
if (postTransmitDelayMs != null)
_techChip(
context,
icon: Icons.hourglass_bottom,
label: '+${_formatMs(postTransmitDelayMs)} lag',
color: Colors.orange,
),
if (message.retryAttempt > 0)
_techChip(
context,
icon: Icons.refresh,
label: 'retry ${message.retryAttempt}/3',
color: Colors.redAccent,
),
if (message.suggestedTimeoutMs != null)
_techChip(
context,
icon: Icons.timer_outlined,
label: 'timeout ${_formatMs(message.suggestedTimeoutMs!)}',
color: Colors.blueGrey,
),
if (message.usedFloodFallback)
_techChip(
context,
icon: Icons.waves,
label: 'flood fallback',
color: Colors.teal,
)
else if (message.expectedAckTag != null)
_techChip(
context,
icon: Icons.route,
label: 'direct ACK',
color: Colors.indigo,
),
],
);
}
String _formatMs(int value) {
if (value >= 60000) {
final minutes = value ~/ 60000;
final seconds = (value % 60000) ~/ 1000;
return '${minutes}m ${seconds}s';
}
if (value >= 1000) {
return '${(value / 1000).toStringAsFixed(value >= 10000 ? 0 : 1)}s';
}
return '${value}ms';
}
String hopDisplayLabel(Message message) {
if (message.pathLen == 0) return 'Direct';
if (message.pathLen >= 255 && message.isContactMessage) return 'Direct';
if (message.pathLen >= 255) return 'Unknown';
return '${message.pathLen} hop${message.pathLen == 1 ? '' : 's'}';
}
Widget _techChip(
BuildContext context, {
required IconData icon,
required String label,
required Color color,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 10, color: color),
const SizedBox(width: 2),
Text(
label,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: color,
fontWeight: FontWeight.w600,
fontSize: 10,
),
),
],
),
);
}
Widget _signalCapsule(
BuildContext context, {
required IconData icon,
required String label,
required int filled,
required Color color,
}) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 10, color: color),
const SizedBox(width: 2),
Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(5, (i) {
final active = i < filled;
return Container(
width: 3,
height: (4 + i).toDouble(),
margin: const EdgeInsets.symmetric(horizontal: 0.5),
decoration: BoxDecoration(
color: active ? color : color.withValues(alpha: 0.18),
borderRadius: BorderRadius.circular(1),
),
);
}),
),
const SizedBox(width: 2),
Text(
label,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: color,
fontWeight: FontWeight.w600,
fontSize: 10,
),
),
],
),
);
}
int rssiScore(int rssiDbm) => ((rssiDbm + 120) / 10).round().clamp(0, 5);
int snrScore(double snrDb) => ((snrDb + 5.0) / 5.0).round().clamp(0, 5);
String linkQualityLabel(int? rssiDbm, double? snrDb) {
var score = 0;
if (rssiDbm != null) score += rssiScore(rssiDbm);
if (snrDb != null) score += snrScore(snrDb);
if (score >= 8) return 'Excellent';
if (score >= 6) return 'Good';
if (score >= 4) return 'Fair';
return 'Weak';
}
Color linkQualityColor(String quality) {
switch (quality) {
case 'Excellent':
return Colors.green;
case 'Good':
return Colors.lightGreen;
case 'Fair':
return Colors.orange;
default:
return Colors.redAccent;
}
}

View File

@@ -0,0 +1,463 @@
// ignore_for_file: use_null_aware_elements
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart' as flutter_map;
import 'package:latlong2/latlong.dart';
import 'package:provider/provider.dart';
import '../../models/ble_packet_log.dart';
import '../../models/message.dart';
import '../../providers/connection_provider.dart';
import '../../services/mesh_map_nodes_service.dart';
class MessageTraceSheet extends StatefulWidget {
final Message message;
const MessageTraceSheet({super.key, required this.message});
@override
State<MessageTraceSheet> createState() => _MessageTraceSheetState();
}
class _MessageTraceSheetState extends State<MessageTraceSheet> {
late final Future<_TraceResult> _future;
@override
void initState() {
super.initState();
_future = _loadTrace();
}
Future<_TraceResult> _loadTrace() async {
final connectionProvider = context.read<ConnectionProvider>();
final nodes = await MeshMapNodesService.fetchNodes(
cacheTtl: MeshMapNodesService.traceCacheTtl,
);
final packetPath = _extractPathFromPacketLogs(
logs: connectionProvider.bleService.packetLogs,
message: widget.message,
);
final senderPrefix = _toPrefixHex(widget.message.senderPublicKeyPrefix);
final recipientPrefix = widget.message.recipientPublicKey != null
? _toPrefixHex(widget.message.recipientPublicKey)
: _toPrefixHex(connectionProvider.deviceInfo.publicKey);
final senderNode = _bestNodeForPrefix(nodes, senderPrefix);
final recipientNode = _bestNodeForPrefix(nodes, recipientPrefix);
if (packetPath != null && packetPath.isNotEmpty) {
final matched = _matchNodesFromPathHashes(
nodes: nodes,
pathHashes: packetPath,
senderPrefix: senderPrefix,
recipientPrefix: recipientPrefix,
);
return _TraceResult(
mode: TraceMode.packetPath,
sender: senderNode,
recipient: recipientNode,
pathHashes: packetPath,
matchedPathNodes: matched,
);
}
// Fallback when packet path is unavailable.
final inferred = _inferRelaysFromHopCount(
nodes: nodes,
sender: senderNode,
recipient: recipientNode,
relayCount: math.max(0, widget.message.pathLen),
);
final matchedPathNodes = <MeshMapNode?>[
if (senderNode != null) senderNode,
...inferred,
if (recipientNode != null) recipientNode,
];
return _TraceResult(
mode: TraceMode.hopCountInference,
sender: senderNode,
recipient: recipientNode,
pathHashes: const [],
matchedPathNodes: matchedPathNodes,
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: FutureBuilder<_TraceResult>(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const SizedBox(
height: 360,
child: Center(child: CircularProgressIndicator()),
);
}
if (snapshot.hasError) {
return SizedBox(
height: 360,
child: Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text('Failed to load trace: ${snapshot.error}'),
),
),
);
}
final trace = snapshot.data!;
final mapPoints = trace.matchedPathNodes
.whereType<MeshMapNode>()
.map((n) => LatLng(n.latitude, n.longitude))
.toList();
final hasMapPath = mapPoints.length >= 2;
final relayNodes = _relayNodes(trace.matchedPathNodes);
return SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 12),
Center(
child: Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: Theme.of(context).dividerColor,
borderRadius: BorderRadius.circular(2),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
child: Text(
'Trace',
style: Theme.of(context).textTheme.titleLarge,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
trace.mode == TraceMode.packetPath
? 'Route from packet path bytes'
: 'Route inferred from hop count (${widget.message.pathLen})',
style: Theme.of(context).textTheme.bodySmall,
),
),
const SizedBox(height: 10),
Expanded(
child: ListView(
padding: const EdgeInsets.only(bottom: 16),
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SizedBox(
height: 240,
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).dividerColor,
),
),
child: hasMapPath
? flutter_map.FlutterMap(
options: flutter_map.MapOptions(
initialCameraFit:
flutter_map.CameraFit.bounds(
bounds:
flutter_map
.LatLngBounds.fromPoints(
mapPoints,
),
padding: const EdgeInsets.all(28),
),
),
children: [
flutter_map.TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName:
'com.meshcore.sar',
),
flutter_map.PolylineLayer(
polylines: [
flutter_map.Polyline(
points: mapPoints,
strokeWidth: 4,
color: Theme.of(
context,
).colorScheme.primary,
),
],
),
flutter_map.MarkerLayer(
markers: trace.matchedPathNodes
.whereType<MeshMapNode>()
.toList()
.asMap()
.entries
.map(
(entry) => flutter_map.Marker(
point: LatLng(
entry.value.latitude,
entry.value.longitude,
),
width: 34,
height: 34,
child: CircleAvatar(
radius: 16,
backgroundColor:
entry.key == 0
? Colors.green
: (entry.key ==
trace.matchedPathNodes
.whereType<
MeshMapNode
>()
.length -
1
? Colors.red
: Colors.blue),
child: Text(
'${entry.key + 1}',
style: const TextStyle(
color: Colors.white,
fontWeight:
FontWeight.bold,
fontSize: 11,
),
),
),
),
)
.toList(),
),
],
)
: const Center(
child: Text(
'Not enough geolocated nodes to draw path',
),
),
),
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Relays (${relayNodes.length})',
style: Theme.of(context).textTheme.titleMedium,
),
),
if (relayNodes.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Text(
'No relay nodes could be matched for this message.',
),
),
...relayNodes.map(
(node) => ListTile(
leading: const Icon(Icons.router),
title: Text(node.name),
subtitle: Text(
'${node.publicKey.substring(0, math.min(12, node.publicKey.length))}'
'${node.latitude.toStringAsFixed(5)}, ${node.longitude.toStringAsFixed(5)}',
),
),
),
],
),
),
],
),
);
},
),
);
}
List<MeshMapNode> _relayNodes(List<MeshMapNode?> path) {
final concrete = path.whereType<MeshMapNode>().toList();
if (concrete.length <= 2) return const [];
return concrete.sublist(1, concrete.length - 1);
}
String? _toPrefixHex(List<int>? key) {
if (key == null || key.isEmpty) return null;
final take = key.length < 6 ? key.length : 6;
return key
.take(take)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toLowerCase();
}
MeshMapNode? _bestNodeForPrefix(List<MeshMapNode> nodes, String? prefixHex) {
if (prefixHex == null || prefixHex.isEmpty) return null;
final matches =
nodes.where((n) => n.publicKey.startsWith(prefixHex)).toList()
..sort((a, b) => b.updatedAtMs.compareTo(a.updatedAtMs));
return matches.isEmpty ? null : matches.first;
}
List<int>? _extractPathFromPacketLogs({
required List<BlePacketLog> logs,
required Message message,
}) {
if (message.pathLen <= 0 || message.pathLen >= 255) return null;
final expectedPayloadType = message.messageType == MessageType.channel
? 0x05
: 0x02;
BlePacketLog? bestLog;
var bestDeltaMs = 999999999;
for (final log in logs) {
if (log.responseCode != 0x88) continue; // pushLogRxData
if (log.rawData.length < 6) continue;
final raw = log.rawData;
final header = raw[3];
final payloadType = (header >> 2) & 0x0F;
final pathLen = raw[4];
if (payloadType != expectedPayloadType) continue;
if (pathLen != message.pathLen) continue;
if (raw.length < 5 + pathLen) continue;
final deltaMs =
(log.timestamp.difference(message.receivedAt).inMilliseconds).abs();
if (deltaMs < bestDeltaMs) {
bestDeltaMs = deltaMs;
bestLog = log;
}
}
if (bestLog == null || bestDeltaMs > 30000) return null;
final raw = bestLog.rawData;
final pathLen = raw[4];
return raw.sublist(5, 5 + pathLen);
}
List<MeshMapNode?> _matchNodesFromPathHashes({
required List<MeshMapNode> nodes,
required List<int> pathHashes,
required String? senderPrefix,
required String? recipientPrefix,
}) {
final result = <MeshMapNode?>[];
for (var i = 0; i < pathHashes.length; i++) {
final hashHex = pathHashes[i].toRadixString(16).padLeft(2, '0');
final candidates = nodes
.where((n) => n.publicKey.startsWith(hashHex))
.toList();
if (candidates.isEmpty) {
result.add(null);
continue;
}
List<MeshMapNode> filtered = candidates;
if (i == 0 && senderPrefix != null) {
final senderMatches = filtered
.where((n) => n.publicKey.startsWith(senderPrefix))
.toList();
if (senderMatches.isNotEmpty) filtered = senderMatches;
} else if (i == pathHashes.length - 1 && recipientPrefix != null) {
final recipientMatches = filtered
.where((n) => n.publicKey.startsWith(recipientPrefix))
.toList();
if (recipientMatches.isNotEmpty) filtered = recipientMatches;
}
filtered.sort((a, b) => b.updatedAtMs.compareTo(a.updatedAtMs));
result.add(filtered.first);
}
return result;
}
List<MeshMapNode> _inferRelaysFromHopCount({
required List<MeshMapNode> nodes,
required MeshMapNode? sender,
required MeshMapNode? recipient,
required int relayCount,
}) {
if (relayCount <= 0 || sender == null || recipient == null) return const [];
final candidates = nodes.where((n) {
if (sender.publicKey == n.publicKey ||
recipient.publicKey == n.publicKey) {
return false;
}
return true;
}).toList();
final ranked = candidates
..sort((a, b) {
final da = _distanceToSegmentMeters(
p: LatLng(a.latitude, a.longitude),
a: LatLng(sender.latitude, sender.longitude),
b: LatLng(recipient.latitude, recipient.longitude),
);
final db = _distanceToSegmentMeters(
p: LatLng(b.latitude, b.longitude),
a: LatLng(sender.latitude, sender.longitude),
b: LatLng(recipient.latitude, recipient.longitude),
);
return da.compareTo(db);
});
return ranked.take(relayCount).toList();
}
double _distanceToSegmentMeters({
required LatLng p,
required LatLng a,
required LatLng b,
}) {
final ax = a.longitude;
final ay = a.latitude;
final bx = b.longitude;
final by = b.latitude;
final px = p.longitude;
final py = p.latitude;
final abx = bx - ax;
final aby = by - ay;
final apx = px - ax;
final apy = py - ay;
final ab2 = abx * abx + aby * aby;
if (ab2 == 0) {
return const Distance().as(LengthUnit.Meter, a, p);
}
var t = (apx * abx + apy * aby) / ab2;
t = t.clamp(0.0, 1.0);
final closest = LatLng(ay + aby * t, ax + abx * t);
return const Distance().as(LengthUnit.Meter, closest, p);
}
}
enum TraceMode { packetPath, hopCountInference }
class _TraceResult {
final TraceMode mode;
final MeshMapNode? sender;
final MeshMapNode? recipient;
final List<int> pathHashes;
final List<MeshMapNode?> matchedPathNodes;
const _TraceResult({
required this.mode,
required this.sender,
required this.recipient,
required this.pathHashes,
required this.matchedPathNodes,
});
}

View File

@@ -0,0 +1,432 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../l10n/app_localizations.dart';
class MessagesComposer extends StatelessWidget {
final TextEditingController textController;
final FocusNode focusNode;
final TextInputFormatter messageByteLimiter;
final int messageByteCount;
final int maxMessageBytes;
final bool isRecording;
final bool isSendingVoice;
final bool voiceSupported;
final double bottomPadding;
final String destinationLabel;
final Widget destinationAvatar;
final VoidCallback onShowComposerActions;
final VoidCallback onShowRecipientSelector;
final Future<void> Function() onStartVoiceRecording;
final Future<void> Function() onStopAndSendVoice;
final Future<void> Function() onSendMessage;
const MessagesComposer({
super.key,
required this.textController,
required this.focusNode,
required this.messageByteLimiter,
required this.messageByteCount,
required this.maxMessageBytes,
required this.isRecording,
required this.isSendingVoice,
required this.voiceSupported,
required this.bottomPadding,
required this.destinationLabel,
required this.destinationAvatar,
required this.onShowComposerActions,
required this.onShowRecipientSelector,
required this.onStartVoiceRecording,
required this.onStopAndSendVoice,
required this.onSendMessage,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(color: Colors.transparent),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SafeArea(
top: false,
child: Padding(
padding: EdgeInsets.fromLTRB(10, 4, 10, bottomPadding),
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(28),
border: Border.all(
color: Theme.of(
context,
).dividerColor.withValues(alpha: 0.35),
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 18,
offset: const Offset(0, 6),
),
],
),
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
_ComposerActionButton(
isRecording: isRecording,
onPressed: isRecording
? onStopAndSendVoice
: onShowComposerActions,
),
const SizedBox(width: 8),
Expanded(
child: _DestinationSelector(
destinationLabel: destinationLabel,
destinationAvatar: destinationAvatar,
onTap: onShowRecipientSelector,
),
),
],
),
const SizedBox(height: 8),
ListenableBuilder(
listenable: Listenable.merge([
textController,
focusNode,
]),
builder: (context, _) {
final canSendText =
!isRecording &&
!isSendingVoice &&
textController.text.trim().isNotEmpty;
final semanticsLabel = isRecording
? 'Recording... release to send voice'
: (isSendingVoice
? 'Sending voice...'
: voiceSupported
? 'Send (long press to record voice)'
: 'Send');
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: _MessageInput(
textController: textController,
focusNode: focusNode,
messageByteLimiter: messageByteLimiter,
),
),
const SizedBox(width: 8),
_SendButton(
canSendText: canSendText,
isRecording: isRecording,
isSendingVoice: isSendingVoice,
voiceSupported: voiceSupported,
semanticsLabel: semanticsLabel,
messageByteCount: messageByteCount,
maxMessageBytes: maxMessageBytes,
onSendMessage: onSendMessage,
onStartVoiceRecording: onStartVoiceRecording,
onStopAndSendVoice: onStopAndSendVoice,
),
],
);
},
),
],
),
),
),
),
),
],
),
);
}
}
class _ComposerActionButton extends StatelessWidget {
final bool isRecording;
final VoidCallback onPressed;
const _ComposerActionButton({
required this.isRecording,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return Container(
width: 42,
height: 42,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).dividerColor.withValues(alpha: 0.35),
),
),
child: IconButton(
icon: Icon(isRecording ? Icons.stop : Icons.add, size: 22),
tooltip: isRecording ? 'Stop recording' : 'More actions',
onPressed: onPressed,
color: isRecording ? Colors.red : Theme.of(context).colorScheme.primary,
),
);
}
}
class _DestinationSelector extends StatelessWidget {
final String destinationLabel;
final Widget destinationAvatar;
final VoidCallback onTap;
const _DestinationSelector({
required this.destinationLabel,
required this.destinationAvatar,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(20),
onTap: onTap,
child: Ink(
height: 42,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Theme.of(context).dividerColor.withValues(alpha: 0.35),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Row(
children: [
destinationAvatar,
const SizedBox(width: 10),
Expanded(
child: Text(
destinationLabel,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
Icon(
Icons.expand_more_rounded,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
],
),
),
),
),
);
}
}
class _MessageInput extends StatelessWidget {
final TextEditingController textController;
final FocusNode focusNode;
final TextInputFormatter messageByteLimiter;
const _MessageInput({
required this.textController,
required this.focusNode,
required this.messageByteLimiter,
});
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
constraints: const BoxConstraints(minHeight: 46, maxHeight: 132),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: focusNode.hasFocus
? Theme.of(context).colorScheme.primary
: Theme.of(context).dividerColor.withValues(alpha: 0.35),
width: focusNode.hasFocus ? 1.4 : 1,
),
boxShadow: focusNode.hasFocus
? [
BoxShadow(
color: Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.10),
blurRadius: 12,
offset: const Offset(0, 4),
),
]
: null,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: TextField(
controller: textController,
focusNode: focusNode,
minLines: 1,
maxLines: 4,
keyboardType: TextInputType.multiline,
inputFormatters: [messageByteLimiter],
style: const TextStyle(fontSize: 15),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
hintText: AppLocalizations.of(context)!.typeYourMessage,
hintStyle: TextStyle(
fontSize: 15,
color: Theme.of(
context,
).colorScheme.onSurfaceVariant.withValues(alpha: 0.9),
),
filled: false,
fillColor: Colors.transparent,
border: InputBorder.none,
isCollapsed: true,
),
textInputAction: TextInputAction.newline,
),
),
);
}
}
class _SendButton extends StatelessWidget {
final bool canSendText;
final bool isRecording;
final bool isSendingVoice;
final bool voiceSupported;
final String semanticsLabel;
final int messageByteCount;
final int maxMessageBytes;
final Future<void> Function() onSendMessage;
final Future<void> Function() onStartVoiceRecording;
final Future<void> Function() onStopAndSendVoice;
const _SendButton({
required this.canSendText,
required this.isRecording,
required this.isSendingVoice,
required this.voiceSupported,
required this.semanticsLabel,
required this.messageByteCount,
required this.maxMessageBytes,
required this.onSendMessage,
required this.onStartVoiceRecording,
required this.onStopAndSendVoice,
});
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
enabled: canSendText || (voiceSupported && !isSendingVoice),
label: semanticsLabel,
onTap: canSendText ? onSendMessage : null,
onLongPress: (voiceSupported && !isSendingVoice)
? () {
if (isRecording) {
onStopAndSendVoice();
return;
}
onStartVoiceRecording();
}
: null,
child: Tooltip(
message: semanticsLabel,
excludeFromSemantics: true,
child: GestureDetector(
excludeFromSemantics: true,
onTap: canSendText ? onSendMessage : null,
onLongPressStart: (voiceSupported && !isSendingVoice)
? (_) => onStartVoiceRecording()
: null,
onLongPressEnd: (voiceSupported && isRecording)
? (_) => onStopAndSendVoice()
: null,
onLongPressCancel: (voiceSupported && isRecording)
? onStopAndSendVoice
: null,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 180),
width: 46,
height: 46,
decoration: BoxDecoration(
color: canSendText || isRecording
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.surface,
shape: BoxShape.circle,
border: Border.all(
color: canSendText || isRecording
? Colors.transparent
: Theme.of(
context,
).dividerColor.withValues(alpha: 0.35),
),
boxShadow: canSendText || isRecording
? [
BoxShadow(
color: Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.22),
blurRadius: 14,
offset: const Offset(0, 6),
),
]
: null,
),
child: isSendingVoice
? Center(
child: CircularProgressIndicator(
strokeWidth: 2,
color: Theme.of(context).colorScheme.onPrimary,
),
)
: Icon(
isRecording ? Icons.mic_rounded : Icons.send_rounded,
size: 22,
color: canSendText || isRecording
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Text(
'$messageByteCount/$maxMessageBytes',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: messageByteCount > maxMessageBytes * 0.9
? Colors.orange.shade800
: Theme.of(
context,
).colorScheme.onSurfaceVariant.withValues(alpha: 0.9),
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import '../../models/message.dart';
import '../../widgets/messages/message_bubble.dart';
class MessagesContent extends StatelessWidget {
static const double defaultPadding = 8;
final List<Message> messages;
final ScrollController scrollController;
final String? highlightedMessageId;
final double bottomContentPadding;
final Future<void> Function() onRefresh;
final VoidCallback? onNavigateToMap;
final ValueChanged<Message>? onMessageTap;
const MessagesContent({
super.key,
required this.messages,
required this.scrollController,
required this.highlightedMessageId,
this.bottomContentPadding = 0,
required this.onRefresh,
this.onNavigateToMap,
this.onMessageTap,
});
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: onRefresh,
child: messages.isEmpty
? LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraints.maxHeight),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.message_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(height: 16),
Text(
AppLocalizations.of(context)!.noMessagesYet,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(context)!.pullDownToSync,
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
],
),
),
),
),
)
: ListView.builder(
controller: scrollController,
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
reverse: true,
padding: EdgeInsets.fromLTRB(
defaultPadding,
defaultPadding,
defaultPadding,
defaultPadding + bottomContentPadding,
),
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return MessageBubble(
key: ValueKey(message.id),
message: message,
isHighlighted: message.id == highlightedMessageId,
onNavigateToMap: onNavigateToMap,
onTap: onMessageTap == null
? null
: () => onMessageTap!(message),
);
},
),
);
}
}

View File

@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../../models/contact.dart';
import '../../l10n/app_localizations.dart';
import '../common/contact_avatar.dart';
/// Bottom sheet for selecting message recipient (channel, contact, or room)
class RecipientSelectorSheet extends StatefulWidget {
@@ -168,7 +169,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
...filteredChannels.map((channel) {
return _buildRecipientTile(
context: context,
icon: Icons.public,
contact: channel,
title: channel.getLocalizedDisplayName(context),
subtitle: channel.isPublicChannel
? l10n.broadcastToAllNearby
@@ -215,10 +216,9 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
...filteredContacts.map((contact) {
return _buildRecipientTile(
context: context,
icon: Icons.person,
contact: contact,
title: contact.displayName,
subtitle: contact.publicKeyShort,
emoji: contact.roleEmoji,
isSelected: _isSelected('contact', contact),
onTap: () {
widget.onSelect('contact', contact);
@@ -261,10 +261,9 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
...filteredRooms.map((room) {
return _buildRecipientTile(
context: context,
icon: Icons.meeting_room,
contact: room,
title: room.displayName,
subtitle: room.publicKeyShort,
emoji: room.roleEmoji,
isSelected: _isSelected('room', room),
onTap: () {
widget.onSelect('room', room);
@@ -275,7 +274,9 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
],
// Empty state
if (widget.contacts.isEmpty && widget.rooms.isEmpty && widget.channels.isEmpty) ...[
if (widget.contacts.isEmpty &&
widget.rooms.isEmpty &&
widget.channels.isEmpty) ...[
Padding(
padding: const EdgeInsets.all(32),
child: Column(
@@ -310,36 +311,16 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
Widget _buildRecipientTile({
required BuildContext context,
required IconData icon,
required Contact contact,
required String title,
required String subtitle,
String? emoji,
required bool isSelected,
required VoidCallback onTap,
}) {
return ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.primaryContainer
: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(20),
),
child: Icon(
icon,
color: isSelected
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
leading: ContactAvatar(contact: contact, radius: 20, displayName: title),
title: Row(
children: [
if (emoji != null && emoji.isNotEmpty) ...[
Text(emoji, style: const TextStyle(fontSize: 16)),
const SizedBox(width: 8),
],
Expanded(
child: Text(
title,

View File

@@ -0,0 +1,107 @@
import 'package:flutter/material.dart';
import '../../models/message.dart';
import '../../utils/message_extensions.dart';
class SystemMessageBubble extends StatelessWidget {
final Message message;
const SystemMessageBubble({super.key, required this.message});
Color _getLevelColor(String? level) {
switch (level?.toLowerCase()) {
case 'success':
return Colors.green;
case 'warning':
return Colors.orange;
case 'error':
return Colors.red;
case 'info':
default:
return Colors.blue.shade300;
}
}
IconData _getLevelIcon(String? level) {
switch (level?.toLowerCase()) {
case 'success':
return Icons.check_circle_outline;
case 'warning':
return Icons.warning_amber_outlined;
case 'error':
return Icons.error_outline;
case 'info':
default:
return Icons.info_outline;
}
}
@override
Widget build(BuildContext context) {
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final level = message.senderName ?? 'info';
final levelColor = _getLevelColor(level);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: levelColor.withValues(alpha: isDarkMode ? 0.18 : 0.08),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: levelColor.withValues(alpha: isDarkMode ? 0.3 : 0.16),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(_getLevelIcon(level), size: 16, color: levelColor),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
level.toUpperCase(),
style: Theme.of(context).textTheme.labelSmall
?.copyWith(
color: levelColor,
fontWeight: FontWeight.bold,
letterSpacing: 0.4,
),
),
),
Text(
message.getLocalizedTimeAgo(context),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(
context,
).textTheme.bodySmall?.color?.withValues(alpha: 0.6),
),
),
],
),
const SizedBox(height: 4),
Text(
message.text,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
height: 1.3,
color: Theme.of(
context,
).textTheme.bodySmall?.color?.withValues(alpha: 0.8),
),
),
],
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,295 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/contact.dart';
import '../../models/message.dart';
import '../../providers/connection_provider.dart';
import '../../providers/contacts_provider.dart';
import '../../providers/messages_provider.dart';
import '../../utils/tictactoe_message_parser.dart';
import '../../utils/toast_logger.dart';
class TicTacToeMessageBubble extends StatelessWidget {
final Message message;
final bool isSentByMe;
const TicTacToeMessageBubble({
super.key,
required this.message,
required this.isSentByMe,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final event = TicTacToeMessageParser.tryParse(message.text);
if (event == null) {
return const SizedBox.shrink();
}
final conn = context.watch<ConnectionProvider>();
final contacts = context.read<ContactsProvider>();
final messages = context.watch<MessagesProvider>().messages;
final selfKey = conn.deviceInfo.publicKey;
if (selfKey == null || selfKey.length < 6) {
return const Text('Tic-Tac-Toe unavailable');
}
final selfKey6 = _key6Hex(selfKey);
final opponent = _resolveOpponentContact(
message: message,
contactsProvider: contacts,
isSentByMe: isSentByMe,
);
if (opponent == null) {
return const Text('Tic-Tac-Toe: opponent unknown');
}
final opponentKey6 = _key6Hex(opponent.publicKey);
final gameEvents = <TicTacToeEvent>[];
TicTacToeEvent? start;
for (final m in messages) {
if (!m.isContactMessage) continue;
final parsed = TicTacToeMessageParser.tryParse(m.text);
if (parsed == null || parsed.gameId != event.gameId) continue;
if (!_isSameDmThread(
message: m,
selfKey: selfKey,
opponentKey6: opponentKey6,
)) {
continue;
}
if (parsed.type == TicTacToeEventType.start) {
start ??= parsed;
} else {
gameEvents.add(parsed);
}
}
start ??= event.type == TicTacToeEventType.start ? event : null;
if (start == null) {
return const Text('Tic-Tac-Toe: waiting for start');
}
final xPlayer = start.playerKey6;
final oPlayer = xPlayer == selfKey6 ? opponentKey6 : selfKey6;
final state = buildTicTacToeState(
gameId: event.gameId,
xPlayerKey6: xPlayer,
oPlayerKey6: oPlayer,
events: gameEvents,
);
final mySymbol = selfKey6 == state.xPlayerKey6 ? 'X' : 'O';
final isMyTurn = !state.isFinished && state.nextSymbol == mySymbol;
final titleColor = isSentByMe
? colorScheme.onPrimaryContainer
: colorScheme.onSurface;
final statusColor = isSentByMe
? colorScheme.onPrimaryContainer.withValues(alpha: 0.85)
: colorScheme.onSurface.withValues(alpha: 0.85);
return ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 230),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Tic-Tac-Toe · Game ${state.gameId}',
style: Theme.of(context).textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.bold,
color: titleColor,
),
),
const SizedBox(height: 8),
_BoardGrid(
board: state.board,
enabled: isMyTurn,
isSentByMe: isSentByMe,
onTapCell: (idx) => _onCellTap(
context: context,
idx: idx,
state: state,
selfKey6: selfKey6,
opponent: opponent,
connectionProvider: conn,
),
),
const SizedBox(height: 8),
Text(
_statusText(state: state, mySymbol: mySymbol),
style: Theme.of(
context,
).textTheme.labelSmall?.copyWith(color: statusColor),
),
],
),
);
}
Future<void> _onCellTap({
required BuildContext context,
required int idx,
required TicTacToeGameState state,
required String selfKey6,
required Contact opponent,
required ConnectionProvider connectionProvider,
}) async {
if (idx < 0 || idx > 8 || state.board[idx] != null) return;
if (!connectionProvider.deviceInfo.isConnected) {
ToastLogger.error(context, 'Not connected to device');
return;
}
final messagesProvider = context.read<MessagesProvider>();
final text = TicTacToeMessageParser.encodeMove(
gameId: state.gameId,
cell: idx,
playerKey6: selfKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
final messageId = '${DateTime.now().millisecondsSinceEpoch}_ttt_move';
final senderPublicKeyPrefix = connectionProvider.deviceInfo.publicKey!
.sublist(0, 6);
final sentMessage = Message(
id: messageId,
messageType: MessageType.contact,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
text: text,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: opponent.publicKey,
);
messagesProvider.addSentMessage(sentMessage, contact: opponent);
final sent = await connectionProvider.sendTextMessage(
contactPublicKey: opponent.publicKey,
text: text,
messageId: messageId,
contact: opponent,
);
if (!sent) {
messagesProvider.markMessageFailed(messageId);
if (!context.mounted) return;
ToastLogger.error(context, 'Failed to send Tic-Tac-Toe move');
}
}
static String _statusText({
required TicTacToeGameState state,
required String mySymbol,
}) {
if (state.winnerSymbol != null) {
return state.winnerSymbol == mySymbol ? 'You won' : 'Opponent won';
}
if (state.isDraw) return 'Draw';
return state.nextSymbol == mySymbol ? 'Your turn' : 'Opponent turn';
}
static String _key6Hex(Uint8List key) => key
.sublist(0, math.min(6, key.length))
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join('')
.toLowerCase();
static Contact? _resolveOpponentContact({
required Message message,
required ContactsProvider contactsProvider,
required bool isSentByMe,
}) {
if (isSentByMe && message.recipientPublicKey != null) {
return contactsProvider.findContactByKey(message.recipientPublicKey!);
}
final sender = message.senderPublicKeyPrefix;
if (sender == null || sender.length < 6) return null;
return contactsProvider.findContactByPrefix(
Uint8List.fromList(sender.sublist(0, 6)),
);
}
static bool _isSameDmThread({
required Message message,
required Uint8List selfKey,
required String opponentKey6,
}) {
final isOwn = message.isSentMessage || message.isFromSelf(selfKey);
if (isOwn) {
final recipient = message.recipientPublicKey;
if (recipient == null || recipient.length < 6) return false;
return _key6Hex(recipient) == opponentKey6;
}
final sender = message.senderPublicKeyPrefix;
if (sender == null || sender.length < 6) return false;
return _key6Hex(sender) == opponentKey6;
}
}
class _BoardGrid extends StatelessWidget {
final List<String?> board;
final bool enabled;
final bool isSentByMe;
final ValueChanged<int> onTapCell;
const _BoardGrid({
required this.board,
required this.enabled,
required this.isSentByMe,
required this.onTapCell,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final cellBackground = isSentByMe
? colorScheme.primaryContainer.withValues(alpha: 0.35)
: colorScheme.surface;
final cellBorder = isSentByMe
? colorScheme.primary.withValues(alpha: 0.45)
: colorScheme.outline.withValues(alpha: 0.35);
return SizedBox(
width: 180,
height: 180,
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 4,
mainAxisSpacing: 4,
),
itemCount: 9,
itemBuilder: (context, idx) {
final value = board[idx];
return InkWell(
onTap: enabled && value == null ? () => onTapCell(idx) : null,
borderRadius: BorderRadius.circular(8),
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: cellBackground,
border: Border.all(color: cellBorder),
),
child: Text(
value ?? '',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w900,
color: value == 'X'
? colorScheme.primary
: value == 'O'
? colorScheme.tertiary
: null,
),
),
),
);
},
),
);
}
}

View File

@@ -0,0 +1,24 @@
import 'dart:async';
/// Calculates a transfer timeout as 2× the estimated LoRa airtime,
/// with a minimum of 30 seconds.
///
/// Used by [ImageMessageBubble] and [VoiceMessageBubble] to reset the
/// "loading" spinner when a transfer stalls, allowing the user to retry.
class TransferTimeout {
static const Duration _minimum = Duration(seconds: 30);
/// Start a one-shot timer based on [txEstimate] × 2 (min 30s).
///
/// [onTimeout] is called on the UI thread when the timer fires.
/// Returns the [Timer] so the caller can cancel it (e.g. on dispose or
/// when the transfer completes).
static Timer start({
required Duration txEstimate,
required void Function() onTimeout,
}) {
final timeout = txEstimate * 2;
final effective = timeout < _minimum ? _minimum : timeout;
return Timer(effective, onTimeout);
}
}

View File

@@ -1,13 +1,15 @@
import 'dart:typed_data';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../l10n/app_localizations.dart';
import '../../models/contact.dart';
import '../../models/message.dart';
import '../../providers/app_provider.dart';
import '../../providers/connection_provider.dart';
import '../../providers/contacts_provider.dart';
import '../../providers/voice_provider.dart';
import '../../utils/transmission_target_resolver.dart';
import '../../utils/voice_message_parser.dart';
import 'transfer_timeout.dart';
/// A message bubble that shows a voice recording with play/stop controls.
class VoiceMessageBubble extends StatefulWidget {
@@ -25,9 +27,17 @@ class VoiceMessageBubble extends StatefulWidget {
}
class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
static const int _maxFetchHops = 3;
bool _isRequesting = false;
bool _autoPlayWhenReady = false;
String? _errorText;
Timer? _requestTimeoutTimer;
@override
void dispose() {
_requestTimeoutTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
@@ -45,8 +55,20 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
return Consumer<VoiceProvider>(
builder: (context, voiceProvider, _) {
final contactsProvider = context.read<ContactsProvider>();
final session = voiceProvider.session(voiceId);
final envelope = VoiceEnvelope.tryParseText(widget.message.text);
final sender = TransmissionTargetResolver.resolveLocalTarget(
contactsProvider: contactsProvider,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope?.senderKey6,
senderName: widget.message.senderName,
);
final effectivePathLen = sender != null && sender.outPathLen >= 0
? sender.outPathLen
: widget.message.pathLen;
final isPlaying = voiceProvider.isPlaying(voiceId);
final isComplete = voiceProvider.isComplete(voiceId);
@@ -55,6 +77,7 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
if (!mounted) return;
setState(() {
_isRequesting = false;
_errorText = null;
});
});
}
@@ -86,12 +109,13 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
session: session,
envelope: envelope,
messageText: widget.message.text,
pathLen: widget.message.pathLen,
pathLen: effectivePathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
);
final txEstimateLabel = _formatTransmitEstimate(txEstimate);
final eta = voiceProvider.estimateRemainingTransferTime(voiceId);
return Row(
mainAxisSize: MainAxisSize.min,
@@ -102,11 +126,22 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
await voiceProvider.stop();
return;
}
if (_isRequesting) {
_cancelReceive(voiceId);
return;
}
if (isComplete) {
await voiceProvider.play(voiceId);
return;
}
await _requestAndPlayVoice(voiceId);
await _requestAndPlayVoice(
voiceId,
envelope: envelope,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
pathLen: effectivePathLen,
);
},
borderRadius: BorderRadius.circular(24),
child: Container(
@@ -121,7 +156,7 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
child: Icon(
isPlaying
? Icons.stop
: (_isRequesting ? Icons.downloading : Icons.play_arrow),
: (_isRequesting ? Icons.close : Icons.play_arrow),
size: 28,
color: widget.isSentByMe
? Theme.of(context).colorScheme.onPrimaryContainer
@@ -158,6 +193,7 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
requestingLabel: AppLocalizations.of(
context,
)!.requestingVoice,
eta: eta,
),
style: TextStyle(
fontSize: 11,
@@ -174,18 +210,138 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
);
}
Future<void> _requestAndPlayVoice(String sessionId) async {
Future<void> _requestAndPlayVoice(
String sessionId, {
VoiceEnvelope? envelope,
int? radioBw,
int? radioSf,
int? radioCr,
int pathLen = 0,
}) async {
if (_isRequesting) return;
final sender = _resolveSenderContact();
if (sender == null) {
_setUnavailable();
setState(() {
_isRequesting = true;
_autoPlayWhenReady = true;
_errorText = null;
});
final connectionProvider = context.read<ConnectionProvider>();
final voiceProvider = context.read<VoiceProvider>();
voiceProvider.resumeIncomingSession(sessionId);
final contactsProvider = context.read<ContactsProvider>();
final appProvider = context.read<AppProvider>();
var resolution = await TransmissionTargetResolver.resolveFetchTarget(
contactsProvider: contactsProvider,
refreshContacts: connectionProvider.getContacts,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope?.senderKey6,
senderName: widget.message.senderName,
maxFetchHops: _maxFetchHops,
);
if (!mounted) return;
if (resolution.failure == TransmissionTargetFailure.unknownContact) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender contact is unknown. Sync contacts first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unknownRoute) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender route is unknown. Sync contacts/path first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.tooFar) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Message is too far (${resolution.hops} hops, max ${resolution.maxHops}).',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unreachable) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender route did not respond to a path check. Sync contacts/path and try again.',
);
return;
}
final connectionProvider = context.read<ConnectionProvider>();
var sender = resolution.target!;
var routeVerified = await appProvider.verifyRawTransportRoute(sender);
if (!mounted) return;
if (!routeVerified) {
await connectionProvider.getContacts();
if (!mounted) return;
resolution = await TransmissionTargetResolver.resolveFetchTarget(
contactsProvider: contactsProvider,
refreshContacts: connectionProvider.getContacts,
isSentByMe: widget.isSentByMe,
recipientPublicKey: widget.message.recipientPublicKey,
senderPublicKeyPrefix: widget.message.senderPublicKeyPrefix,
senderKey6FromEnvelope: envelope?.senderKey6,
senderName: widget.message.senderName,
maxFetchHops: _maxFetchHops,
);
if (!mounted) return;
if (resolution.failure == TransmissionTargetFailure.unknownContact) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender contact is unknown. Sync contacts first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.unknownRoute) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender route is unknown. Sync contacts/path first.',
);
return;
}
if (resolution.failure == TransmissionTargetFailure.tooFar) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Message is too far (${resolution.hops} hops, max ${resolution.maxHops}).',
);
return;
}
sender = resolution.target!;
routeVerified = await appProvider.verifyRawTransportRoute(sender);
if (!mounted) return;
if (!routeVerified) {
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Sender route did not respond on the raw transport path.',
);
return;
}
}
if (sender.outPathLen >= 2) {
_showToast(
'Voice fetch over ${sender.outPathLen} hops may take a while.',
);
}
final deviceKey = connectionProvider.deviceInfo.publicKey;
if (deviceKey == null || deviceKey.length < 6) {
_setUnavailable();
_clearRequestState();
await _showBlockingAlert(
'Cannot fetch voice',
'Device key is unavailable.',
);
return;
}
@@ -193,31 +349,88 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
.sublist(0, 6)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join('');
final request = VoiceFetchRequest(
final missing = voiceProvider.missingPacketIndices(sessionId);
final totalPackets = sessionPacketCount(
voiceProvider: voiceProvider,
sessionId: sessionId,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
version: 1,
envelope: envelope,
);
final isPartialResume =
missing.isNotEmpty && totalPackets > 0 && missing.length < totalPackets;
final request = isPartialResume
? VoiceFetchRequest(
sessionId: sessionId,
want: 'missing',
missingIndices: missing,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
version: 2,
)
: VoiceFetchRequest(
sessionId: sessionId,
requesterKey6: requesterKey6,
timestampSec: DateTime.now().millisecondsSinceEpoch ~/ 1000,
version: 2,
);
setState(() {
_isRequesting = true;
_autoPlayWhenReady = true;
_errorText = null;
});
final sent = await connectionProvider.sendTextMessage(
contactPublicKey: sender.publicKey,
text: request.encodeText(),
contact: sender,
);
if (!sent) {
try {
debugPrint(
'🎙️ [VoiceMessageBubble] Outgoing voice fetch request: session=$sessionId want=${isPartialResume ? 'missing' : 'all'} target=${sender.advName} hops=${sender.outPathLen}',
);
await connectionProvider.sendRawVoicePacket(
contactPath: sender.outPath,
contactPathLen: sender.outPathLen,
payload: request.encodeBinary(),
);
} catch (_) {
_setUnavailable();
return;
}
// Timeout = 2× estimated LoRa airtime (min 30s).
final effectivePathLen = sender.outPathLen >= 0
? sender.outPathLen
: pathLen;
final estimatedDurationMs =
envelope != null &&
totalPackets > 0 &&
missing.isNotEmpty &&
missing.length < totalPackets
? ((envelope.durationMs * missing.length) / totalPackets).round()
: envelope?.durationMs;
final txEstimate = envelope != null
? estimateVoiceTransmitDuration(
packetCount: isPartialResume ? missing.length : envelope.total,
mode: envelope.mode,
durationMs: estimatedDurationMs ?? envelope.durationMs,
pathLen: effectivePathLen,
radioBw: radioBw,
radioSf: radioSf,
radioCr: radioCr,
)
: const Duration(seconds: 15);
_requestTimeoutTimer?.cancel();
_requestTimeoutTimer = TransferTimeout.start(
txEstimate: txEstimate,
onTimeout: () {
if (mounted && _isRequesting) {
_setUnavailable();
}
},
);
}
int sessionPacketCount({
required VoiceProvider voiceProvider,
required String sessionId,
required VoiceEnvelope? envelope,
}) {
return voiceProvider.session(sessionId)?.total ?? envelope?.total ?? 0;
}
void _setUnavailable() {
if (!mounted) return;
_showToast(AppLocalizations.of(context)!.voiceUnavailable);
setState(() {
_isRequesting = false;
_autoPlayWhenReady = false;
@@ -225,25 +438,49 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
});
}
Contact? _resolveSenderContact() {
final contactsProvider = context.read<ContactsProvider>();
final senderPrefix = widget.message.senderPublicKeyPrefix;
if (senderPrefix != null && senderPrefix.length >= 6) {
final contact = contactsProvider.findContactByPrefix(
Uint8List.fromList(senderPrefix.sublist(0, 6)),
);
if (contact != null) return contact;
}
void _clearRequestState() {
if (!mounted) return;
setState(() {
_isRequesting = false;
_autoPlayWhenReady = false;
});
}
final envelope = VoiceEnvelope.tryParseText(widget.message.text);
if (envelope != null) {
final contact = contactsProvider.findContactByPrefixHex(
envelope.senderKey6,
);
if (contact != null) return contact;
}
void _cancelReceive(String sessionId) {
if (!mounted) return;
_requestTimeoutTimer?.cancel();
context.read<VoiceProvider>().cancelIncomingSession(sessionId);
_showToast('Voice receive canceled');
setState(() {
_isRequesting = false;
_autoPlayWhenReady = false;
_errorText = 'Voice receive canceled';
});
}
return null;
void _showToast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), duration: const Duration(seconds: 3)),
);
}
Future<void> _showBlockingAlert(String title, String message) async {
if (!mounted) return;
_showToast('$title: $message');
await showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(title),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('OK'),
),
],
),
);
}
static String _formatDuration(double seconds) {
@@ -262,11 +499,12 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
required bool isRequesting,
required String? errorText,
required String requestingLabel,
required Duration? eta,
}) {
if (errorText != null) return errorText;
final progress = total > 0 ? ' ($received/$total)' : '';
if (isRequesting) {
return '$requestingLabel$progress · $txEstimateLabel';
return '$requestingLabel$progress · ${_formatEta(eta)} · $txEstimateLabel';
}
if (!isComplete && total > 0) {
return '🎙️ $durationLabel · $modeLabel$progress · $txEstimateLabel';
@@ -346,6 +584,14 @@ class _VoiceMessageBubbleState extends State<VoiceMessageBubble> {
final seconds = value.inSeconds % 60;
return '~${minutes}m ${seconds}s tx';
}
static String _formatEta(Duration? eta) {
if (eta == null || eta <= Duration.zero) return 'ETA --';
if (eta.inSeconds < 60) return 'ETA ~${eta.inSeconds}s';
final minutes = eta.inMinutes;
final seconds = eta.inSeconds % 60;
return 'ETA ~${minutes}m ${seconds}s';
}
}
/// Voice waveform rendered as a row of bars.

View File

@@ -16,6 +16,7 @@ import geolocator_apple
import nsd_macos
import objectbox_flutter_libs
import package_info_plus
import path_provider_foundation
import record_macos
import share_plus
import shared_preferences_foundation
@@ -34,6 +35,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
NsdMacosPlugin.register(with: registry.registrar(forPlugin: "NsdMacosPlugin"))
ObjectboxFlutterLibsPlugin.register(with: registry.registrar(forPlugin: "ObjectboxFlutterLibsPlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
RecordMacOsPlugin.register(with: registry.registrar(forPlugin: "RecordMacOsPlugin"))
SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))

View File

@@ -129,14 +129,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
codec2_flutter:
dependency: "direct main"
description:
@@ -243,7 +235,7 @@ packages:
source: hosted
version: "3.3.0"
fake_async:
dependency: transitive
dependency: "direct dev"
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
@@ -646,14 +638,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.5"
glob:
dependency: transitive
description:
name: glob
sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
url: "https://pub.dev"
source: hosted
version: "2.1.3"
gsettings:
dependency: transitive
description:
@@ -662,14 +646,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.8"
hooks:
dependency: transitive
description:
name: hooks
sha256: "7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
http:
dependency: "direct main"
description:
@@ -846,14 +822,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.6.2"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
@@ -883,7 +851,7 @@ packages:
description:
path: "."
ref: main
resolved-ref: "624e3d3cf6ea32d8245cc85d5b599f30ca910501"
resolved-ref: fb0a92a53b8e1ab23ffca50c2bffe819829843e6
url: "https://github.com/dz0ny/meshcore_client.git"
source: git
version: "0.1.0"
@@ -911,14 +879,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: "89e83885ba09da5fdf2cdacc8002a712ca238c28b7f717910b34bcd27b0d03ac"
url: "https://pub.dev"
source: hosted
version: "0.17.4"
nested:
dependency: transitive
description:
@@ -991,14 +951,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.3.1"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52"
url: "https://pub.dev"
source: hosted
version: "9.3.0"
package_info_plus:
dependency: "direct main"
description:
@@ -1040,13 +992,13 @@ packages:
source: hosted
version: "2.2.22"
path_provider_foundation:
dependency: transitive
dependency: "direct overridden"
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
version: "2.5.1"
path_provider_linux:
dependency: transitive
description:
@@ -1183,14 +1135,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
record:
dependency: "direct main"
description:
@@ -1702,5 +1646,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.10.3 <4.0.0"
flutter: ">=3.38.4"
dart: ">=3.10.0 <4.0.0"
flutter: ">=3.38.0"

View File

@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 2026.0302.1+4
version: 2026.0307.1+14
environment:
sdk: ^3.9.2
@@ -144,6 +144,10 @@ dev_dependencies:
# rules and activating additional ones.
flutter_lints: ^6.0.0
flutter_launcher_icons: "^0.14.4"
fake_async: ^1.3.3
dependency_overrides:
path_provider_foundation: 2.5.1
flutter_launcher_icons:
android: "launcher_icon"

View File

@@ -0,0 +1,50 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/message_reception_details.dart';
void main() {
test('drops impossible transmit estimate for received messages', () {
expect(
sanitizeEstimatedTransmitMs(
estimatedTransmitMs: 16 * 60 * 1000 + 54 * 1000,
senderToReceiptMs: 4200,
),
isNull,
);
});
test(
'keeps close transmit estimate despite second-level timestamp rounding',
() {
expect(
sanitizeEstimatedTransmitMs(
estimatedTransmitMs: 1800,
senderToReceiptMs: 900,
),
1800,
);
},
);
test('round trips reception details json', () {
final details = MessageReceptionDetails(
capturedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000),
packetLoggedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
rssiDbm: -92,
snrDb: 7.5,
pathBytes: const [0xAA, 0xBB, 0xCC],
senderToReceiptMs: 4200,
estimatedTransmitMs: 1800,
postTransmitDelayMs: 2400,
);
final decoded = MessageReceptionDetails.fromJson(details.toJson());
expect(decoded, isNotNull);
expect(decoded!.rssiDbm, -92);
expect(decoded.snrDb, 7.5);
expect(decoded.pathBytesHex, 'aa:bb:cc');
expect(decoded.senderToReceiptMs, 4200);
expect(decoded.estimatedTransmitMs, 1800);
expect(decoded.postTransmitDelayMs, 2400);
});
}

View File

@@ -194,5 +194,43 @@ void main() {
}
},
);
test('builds message snapshot from latest valid telemetry', () {
final telemetryData = CayenneLppParser.createGpsData(
latitude: 45.0001,
longitude: 13.9999,
);
provider.updateTelemetry(publicKey.sublist(0, 6), telemetryData);
final contact = provider.findContactByKey(publicKey)!;
final snapshot = provider.buildMessageContactLocationSnapshot(
contact,
capturedAt: DateTime.now(),
);
expect(snapshot, isNotNull);
expect(snapshot!.source, equals('telemetry'));
expect(snapshot.location.latitude, closeTo(45.0001, 0.0001));
expect(snapshot.location.longitude, closeTo(13.9999, 0.0001));
});
test('builds message snapshot from advert when telemetry is invalid', () {
final invalidTelemetry = CayenneLppParser.createGpsData(
latitude: 0.0,
longitude: 0.0,
);
provider.updateTelemetry(publicKey.sublist(0, 6), invalidTelemetry);
final contact = provider.findContactByKey(publicKey)!;
final snapshot = provider.buildMessageContactLocationSnapshot(
contact,
capturedAt: DateTime.now(),
);
expect(snapshot, isNotNull);
expect(snapshot!.source, equals('advert'));
expect(snapshot.location.latitude, closeTo(46.0569, 0.000001));
expect(snapshot.location.longitude, closeTo(14.5058, 0.000001));
});
});
}

View File

@@ -0,0 +1,37 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/helpers/fragment_ack_wait_registry.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('FragmentAckWaitRegistry', () {
test('completes multiple waiters registered for the same key', () async {
final registry = FragmentAckWaitRegistry();
final first = registry.waitFor(
'voice:1',
timeout: const Duration(milliseconds: 200),
);
final second = registry.waitFor(
'voice:1',
timeout: const Duration(milliseconds: 200),
);
expect(registry.complete('voice:1'), equals(2));
expect(await first, isTrue);
expect(await second, isTrue);
});
test('times out and cleans up a waiter when no ack arrives', () async {
final registry = FragmentAckWaitRegistry();
final completed = await registry.waitFor(
'voice:2',
timeout: const Duration(milliseconds: 20),
);
expect(completed, isFalse);
expect(registry.complete('voice:2'), equals(0));
});
});
}

View File

@@ -0,0 +1,37 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/helpers/message_delivery_tracker.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('MessageDeliveryTracker', () {
test('matches pending direct messages by contact', () {
final tracker = MessageDeliveryTracker();
final alice = Uint8List.fromList(List<int>.filled(32, 0xAA));
final bob = Uint8List.fromList(List<int>.filled(32, 0xBB));
tracker.trackPendingDirectMessage('alice-1', alice);
tracker.trackPendingDirectMessage('bob-1', bob);
tracker.trackPendingDirectMessage('alice-2', alice);
expect(tracker.popPendingDirectMessageId(alice), 'alice-1');
expect(tracker.popPendingDirectMessageId(bob), 'bob-1');
expect(tracker.popPendingDirectMessageId(alice), 'alice-2');
});
test('removeByMessageId clears pending queue state', () {
final tracker = MessageDeliveryTracker();
final alice = Uint8List.fromList(List<int>.filled(32, 0xAA));
tracker.trackPendingDirectMessage('alice-1', alice);
tracker.mapAckTagToMessageId(42, 'alice-1');
tracker.removeByMessageId('alice-1');
expect(tracker.getMessageIdForAck(42), isNull);
expect(tracker.popPendingDirectMessageId(alice), isNull);
});
});
}

View File

@@ -0,0 +1,104 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/providers/helpers/raw_session_retransmit.dart';
class _Fragment {
final int index;
final Uint8List payload;
_Fragment(this.index, this.payload);
}
Contact _buildContact({required int outPathLen}) {
return Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i)),
type: ContactType.chat,
flags: 0,
outPathLen: outPathLen,
outPath: Uint8List.fromList(List<int>.generate(8, (i) => i + 1)),
advName: 'Requester',
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: 0,
advLon: 0,
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('serveCachedSessionFragments', () {
test('returns false when sender callback is missing', () async {
final ok = await serveCachedSessionFragments<_Fragment>(
providerLabel: 'TestProvider',
sessionId: 'deadbeef',
requester: _buildContact(outPathLen: 1),
fragments: [
_Fragment(0, Uint8List.fromList([1])),
],
maxDirectPayloadHops: 3,
indexOf: (f) => f.index,
encodeBinary: (f) => f.payload,
sendRawPacket: null,
);
expect(ok, isFalse);
});
test('sends only requested indices', () async {
final sent = <Uint8List>[];
final ok = await serveCachedSessionFragments<_Fragment>(
providerLabel: 'TestProvider',
sessionId: 'deadbeef',
requester: _buildContact(outPathLen: 1),
fragments: [
_Fragment(0, Uint8List.fromList([10])),
_Fragment(1, Uint8List.fromList([20])),
_Fragment(2, Uint8List.fromList([30])),
],
maxDirectPayloadHops: 3,
indexOf: (f) => f.index,
encodeBinary: (f) => f.payload,
sendRawPacket:
({
required contactPath,
required contactPathLen,
required payload,
}) async {
sent.add(payload);
},
requestedIndices: {1, 2},
);
expect(ok, isTrue);
expect(sent.length, equals(2));
expect(sent[0], equals(Uint8List.fromList([20])));
expect(sent[1], equals(Uint8List.fromList([30])));
});
test('fails when no requested index matches cached fragments', () async {
final ok = await serveCachedSessionFragments<_Fragment>(
providerLabel: 'TestProvider',
sessionId: 'deadbeef',
requester: _buildContact(outPathLen: 1),
fragments: [
_Fragment(0, Uint8List.fromList([1])),
],
maxDirectPayloadHops: 3,
indexOf: (f) => f.index,
encodeBinary: (f) => f.payload,
sendRawPacket:
({
required contactPath,
required contactPathLen,
required payload,
}) async {},
requestedIndices: {99},
);
expect(ok, isFalse);
});
});
}

View File

@@ -0,0 +1,86 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/helpers/session_metadata_restore.dart';
import 'package:meshcore_sar_app/utils/image_message_parser.dart';
import 'package:meshcore_sar_app/utils/voice_message_parser.dart';
void main() {
group('restoreSessionMetadataFromMessages', () {
test(
'restores voice and image session senders from persisted envelopes',
() {
final voiceEnvelope = VoiceEnvelope(
sessionId: '00112233',
mode: VoicePacketMode.mode1200,
total: 4,
durationMs: 4000,
senderKey6: 'AABBCCDDEEFF',
timestampSec: 123456,
);
final imageEnvelope = ImageEnvelope(
sessionId: '195cb2fb',
format: ImageFormat.avif,
total: 7,
width: 118,
height: 256,
sizeBytes: 1069,
senderKey6: 'FE8B30EE05FC',
timestampSec: 123457,
);
final restored = restoreSessionMetadataFromMessages([
'plain text',
voiceEnvelope.encodeText(),
imageEnvelope.encode(),
]);
expect(
restored.voiceSenderKeyBySession,
equals({'00112233': 'aabbccddeeff'}),
);
expect(restored.imageEnvelopeBySession.keys, equals({'195cb2fb'}));
expect(
restored.imageEnvelopeBySession['195cb2fb']?.senderKey6,
equals('fe8b30ee05fc'),
);
},
);
test('keeps latest envelope when a session appears multiple times', () {
final first = ImageEnvelope(
sessionId: '195cb2fb',
format: ImageFormat.avif,
total: 7,
width: 100,
height: 100,
sizeBytes: 900,
senderKey6: '001122334455',
timestampSec: 100,
);
final second = ImageEnvelope(
sessionId: '195cb2fb',
format: ImageFormat.jpeg,
total: 8,
width: 118,
height: 256,
sizeBytes: 1069,
senderKey6: 'AABBCCDDEEFF',
timestampSec: 101,
);
final restored = restoreSessionMetadataFromMessages([
first.encode(),
second.encode(),
]);
expect(restored.imageEnvelopeBySession.length, equals(1));
expect(
restored.imageEnvelopeBySession['195cb2fb']?.senderKey6,
equals('aabbccddeeff'),
);
expect(
restored.imageEnvelopeBySession['195cb2fb']?.format,
equals(ImageFormat.jpeg),
);
});
});
}

View File

@@ -0,0 +1,52 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/image_provider.dart';
import 'package:meshcore_sar_app/utils/image_message_parser.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
SharedPreferences.setMockInitialValues({});
group('ImageProvider cancel receive', () {
test('ignores incoming fragments after cancel until resumed', () {
final provider = ImageProvider();
const sessionId = '01020304';
const envelope = ImageEnvelope(
sessionId: sessionId,
format: ImageFormat.avif,
total: 2,
width: 32,
height: 32,
sizeBytes: 4,
senderKey6: 'aabbccddeeff',
timestampSec: 1700000000,
);
final fragment = ImagePacket(
sessionId: sessionId,
format: ImageFormat.avif,
index: 0,
total: 2,
data: Uint8List.fromList([1, 2]),
);
provider.registerEnvelope(envelope);
provider.cancelIncomingSession(sessionId);
expect(provider.isReceiveCanceled(sessionId), isTrue);
expect(provider.session(sessionId), isNull);
provider.addFragment(fragment, width: 32, height: 32);
expect(provider.session(sessionId), isNull);
provider.resumeIncomingSession(sessionId);
provider.registerEnvelope(envelope);
provider.addFragment(fragment, width: 32, height: 32);
expect(provider.isReceiveCanceled(sessionId), isFalse);
expect(provider.session(sessionId)?.receivedCount, equals(1));
});
});
}

View File

@@ -0,0 +1,254 @@
import 'dart:typed_data';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/models/message.dart';
import 'package:meshcore_sar_app/providers/messages_provider.dart';
Contact _buildContact() {
return Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i)),
type: ContactType.chat,
flags: 0,
outPathLen: 1,
outPath: Uint8List.fromList([1, 2, 3, 4]),
advName: 'Teammate',
lastAdvert: 1700000000,
advLat: 0,
advLon: 0,
lastMod: 1700000000,
);
}
Message _buildDirectMessage(String id) {
return Message(
id: id,
messageType: MessageType.contact,
senderPublicKeyPrefix: Uint8List.fromList([0, 1, 2, 3, 4, 5]),
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'hello',
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: Uint8List.fromList(List<int>.generate(32, (i) => i)),
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('MessagesProvider retransmission', () {
test('direct messages become sent before delivery ACK arrives', () {
final provider = MessagesProvider();
provider.addSentMessage(
_buildDirectMessage('m1'),
contact: _buildContact(),
);
provider.markMessageSent('m1', 77, 250);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.sent,
);
expect(provider.messages.single.expectedAckTag, 77);
provider.markMessageDelivered(77, 180);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.delivered,
);
expect(provider.messages.single.roundTripTimeMs, 180);
});
test('direct messages stay sent after device accept until confirm arrives', () {
final provider = MessagesProvider();
provider.addSentMessage(
_buildDirectMessage('m1b'),
contact: _buildContact(),
);
provider.markMessageSent('m1b', 78, 250);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.sent,
);
expect(provider.messages.single.expectedAckTag, 78);
expect(provider.messages.single.roundTripTimeMs, isNull);
expect(provider.messages.single.deliveredAt, isNull);
});
test('channel messages are marked sent immediately', () {
final provider = MessagesProvider();
provider.addSentMessage(
Message(
id: 'c1',
messageType: MessageType.channel,
senderPublicKeyPrefix: Uint8List.fromList([0, 1, 2, 3, 4, 5]),
channelIdx: 0,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'broadcast',
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
),
);
provider.markMessageSent('c1', 0, 0);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.sent,
);
});
test('missing ACK schedules a delayed retransmission', () {
fakeAsync((async) {
final provider = MessagesProvider();
var retryCalls = 0;
provider.sendMessageCallback =
({
required contactPublicKey,
required text,
required messageId,
required contact,
retryAttempt = 0,
}) async {
retryCalls += 1;
return true;
};
provider.addSentMessage(
_buildDirectMessage('m2'),
contact: _buildContact(),
);
provider.markMessageSent('m2', 88, 10);
async.elapse(const Duration(milliseconds: 11));
async.flushMicrotasks();
expect(provider.messages.single.retryAttempt, 1);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.sending,
);
expect(retryCalls, 0);
async.elapse(const Duration(seconds: 4));
async.flushMicrotasks();
expect(retryCalls, 1);
});
});
test('uses calculated timeout when radio timeout is missing', () {
final provider = MessagesProvider();
provider.addSentMessage(
_buildDirectMessage('m3'),
contact: _buildContact(),
);
provider.markMessageSent('m3', 99, 0);
expect(provider.messages.single.suggestedTimeoutMs, isNotNull);
expect(
provider.messages.single.suggestedTimeoutMs!,
greaterThanOrEqualTo(4000),
);
});
test('older retry ack still marks message delivered', () {
final provider = MessagesProvider();
provider.addSentMessage(
_buildDirectMessage('m4'),
contact: _buildContact(),
);
provider.markMessageSent('m4', 111, 10);
provider.markMessageSent('m4', 112, 10);
provider.markMessageDelivered(111, 220);
expect(
provider.messages.single.deliveryStatus,
MessageDeliveryStatus.delivered,
);
expect(provider.messages.single.roundTripTimeMs, 220);
});
test('repeated max-retry failures request path reset', () async {
final provider = MessagesProvider();
final contact = _buildContact();
final resetRequests = <(String, int)>[];
provider.onDirectPathFailedCallback =
({required contact, required failureStreak}) async {
resetRequests.add((contact.advName, failureStreak));
};
provider.addSentMessage(
_buildDirectMessage('m5').copyWith(
retryAttempt: 3,
usedFloodFallback: true,
),
contact: contact,
);
provider.markMessageFailed('m5');
provider.addSentMessage(
_buildDirectMessage('m6').copyWith(
retryAttempt: 3,
usedFloodFallback: true,
),
contact: contact,
);
provider.markMessageFailed('m6');
await Future<void>.delayed(Duration.zero);
expect(resetRequests, [('Teammate', 2)]);
});
test('successful delivery clears path failure streak', () async {
final provider = MessagesProvider();
final contact = _buildContact();
final resetRequests = <int>[];
provider.onDirectPathFailedCallback =
({required contact, required failureStreak}) async {
resetRequests.add(failureStreak);
};
provider.addSentMessage(
_buildDirectMessage('m7').copyWith(
retryAttempt: 3,
usedFloodFallback: true,
),
contact: contact,
);
provider.markMessageFailed('m7');
provider.addSentMessage(
_buildDirectMessage('m8'),
contact: contact,
);
provider.markMessageSent('m8', 123, 10);
provider.markMessageDelivered(123, 150);
provider.addSentMessage(
_buildDirectMessage('m9').copyWith(
retryAttempt: 3,
usedFloodFallback: true,
),
contact: contact,
);
provider.markMessageFailed('m9');
await Future<void>.delayed(Duration.zero);
expect(resetRequests, isEmpty);
});
});
}

View File

@@ -1,14 +1,21 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/message.dart';
import 'package:meshcore_sar_app/models/message_contact_location.dart';
import 'package:meshcore_sar_app/providers/messages_provider.dart';
import 'package:meshcore_sar_app/utils/voice_message_parser.dart';
import 'package:latlong2/latlong.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('MessagesProvider voice detection', () {
test('marks VE1 envelope messages as voice', () {
setUp(() {
SharedPreferences.setMockInitialValues({});
});
test('marks VE2 envelope messages as voice', () {
final provider = MessagesProvider();
final envelope = VoiceEnvelope(
sessionId: 'deafbead',
@@ -65,5 +72,39 @@ void main() {
expect(stored.isVoice, isTrue);
expect(stored.voiceId, equals('00112233'));
});
test('persists received contact location snapshots', () async {
final provider = MessagesProvider();
final message = Message(
id: 'm3',
messageType: MessageType.contact,
pathLen: 1,
textType: MessageTextType.plain,
senderTimestamp: 1700000002,
text: 'status update',
receivedAt: DateTime.now(),
senderPublicKeyPrefix: Uint8List.fromList([0, 1, 2, 3, 4, 5]),
);
provider.addMessage(
message,
contactLocationSnapshot: MessageContactLocation(
location: const LatLng(46.0569, 14.5058),
source: 'advert',
capturedAt: DateTime.now(),
sourceTimestamp: DateTime.now(),
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
final restoredProvider = MessagesProvider();
await restoredProvider.initialize();
final snapshot = restoredProvider.getMessageContactLocation('m3');
expect(snapshot, isNotNull);
expect(snapshot!.source, equals('advert'));
expect(snapshot.location.latitude, closeTo(46.0569, 0.000001));
expect(snapshot.location.longitude, closeTo(14.5058, 0.000001));
});
});
}

View File

@@ -410,6 +410,24 @@ void main() {
expect(decoded.batteryMilliVolts, closeTo(3850, 1));
});
test('stops parsing at zero-padded telemetry tail', () {
final payload = Uint8List.fromList([
0x01, 0x74, 0x01, 0x5F, // voltage 3.51V
0x01, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
]);
final decoded = CayenneLppParser.parse(payload);
expect(decoded.batteryMilliVolts, closeTo(3510, 1));
expect(decoded.batteryPercentage, closeTo(42.5, 0.1));
expect(decoded.gpsLocation, isNotNull);
expect(decoded.gpsLocation!.latitude, 0.0);
expect(decoded.gpsLocation!.longitude, 0.0);
expect(decoded.extraSensorData?['digital_input_0'], isNull);
});
test('empty data returns empty telemetry', () {
final empty = Uint8List(0);
final decoded = CayenneLppParser.parse(empty);

View File

@@ -0,0 +1,26 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/utils/avatar_label_helper.dart';
void main() {
group('AvatarLabelHelper.buildLabel', () {
test('returns two initials for multi-word names', () {
expect(AvatarLabelHelper.buildLabel('John Smith'), 'JS');
});
test('returns first two characters for single-word names', () {
expect(AvatarLabelHelper.buildLabel('Alpha'), 'AL');
});
test('allows three compact characters for hash-prefixed names', () {
expect(AvatarLabelHelper.buildLabel('#ops'), '#OP');
});
test('removes spacing after hash-prefixed names', () {
expect(AvatarLabelHelper.buildLabel('# foo alpha'), '#FO');
});
test('keeps non-hash labels at two characters', () {
expect(AvatarLabelHelper.buildLabel('abc'), 'AB');
});
});
}

View File

@@ -0,0 +1,129 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/utils/image_message_parser.dart';
void main() {
group('ImageEnvelope', () {
test('encodes and parses IE2 with compressed session id', () {
final env = ImageEnvelope(
sessionId: '0000000a',
format: ImageFormat.avif,
total: 14,
width: 256,
height: 171,
sizeBytes: 2100,
senderKey6: 'aabbccddeeff',
timestampSec: 1700000000,
);
final text = env.encode();
expect(text.startsWith('IE2:'), isTrue);
expect(text.split(':')[1], equals('a'));
final parsed = ImageEnvelope.tryParse(text);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('0000000a'));
expect(parsed.format, equals(ImageFormat.avif));
expect(parsed.total, equals(14));
expect(parsed.width, equals(256));
expect(parsed.height, equals(171));
expect(parsed.sizeBytes, equals(2100));
expect(parsed.senderKey6, equals('aabbccddeeff'));
expect(parsed.version, equals(2));
});
test('rejects IE1 legacy prefix', () {
const legacy = 'IE1:deadbeef:0:7:128:128:1050:aabbccddeeff:1700000000:1';
expect(ImageEnvelope.tryParse(legacy), isNull);
});
});
group('ImageFetchRequest', () {
test('encodes and parses IR2 with compressed sid', () {
final req = ImageFetchRequest(
sessionId: '0000000a',
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final text = req.encode();
expect(text.startsWith('IR2:'), isTrue);
expect(text.split(':')[1], equals('a'));
final parsed = ImageFetchRequest.tryParse(text);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('0000000a'));
expect(parsed.want, equals('all'));
expect(parsed.requesterKey6, equals('ffeeddccbbaa'));
expect(parsed.version, equals(2));
});
test('encodes and parses compact missing index ranges', () {
final req = ImageFetchRequest(
sessionId: '0000000a',
want: 'missing',
missingIndices: const [0, 1, 2, 5, 6, 8],
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final text = req.encode();
expect(text, contains(':m0-2.5-6.8:'));
final parsed = ImageFetchRequest.tryParse(text);
expect(parsed, isNotNull);
expect(parsed!.want, equals('missing'));
expect(parsed.missingIndices, equals([0, 1, 2, 5, 6, 8]));
});
test('rejects IR1 legacy prefix', () {
const legacy = 'IR1:00112233:a:ffeeddccbbaa:1700000001:1';
expect(ImageFetchRequest.tryParse(legacy), isNull);
});
test('encodes and parses binary fetch request', () {
final req = ImageFetchRequest(
sessionId: '01020304',
want: 'missing',
missingIndices: const [0, 2, 5],
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final payload = req.encodeBinary();
expect(ImageFetchRequest.isRequestBinary(payload), isTrue);
final parsed = ImageFetchRequest.tryParseBinary(payload);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('01020304'));
expect(parsed.want, equals('missing'));
expect(parsed.missingIndices, equals([0, 2, 5]));
expect(parsed.requesterKey6, equals('ffeeddccbbaa'));
expect(parsed.version, equals(2));
});
});
group('ImageFragmentAck', () {
test('encodes and parses binary ack', () {
final ack = ImageFragmentAck(sessionId: '01020304', index: 9);
final payload = ack.encodeBinary();
expect(ImageFragmentAck.isImageFragmentAckBinary(payload), isTrue);
final parsed = ImageFragmentAck.tryParseBinary(payload);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('01020304'));
expect(parsed.index, equals(9));
});
});
group('safeImageDataBytesForPath', () {
test('caps direct-route fragments to conservative default size', () {
expect(safeImageDataBytesForPath(0), equals(ImagePacket.maxDataBytes));
});
test('shrinks for longer paths but never exceeds conservative default', () {
expect(
safeImageDataBytesForPath(2),
lessThanOrEqualTo(ImagePacket.maxDataBytes),
);
});
});
}

View File

@@ -0,0 +1,92 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/utils/log_rx_route_decoder.dart';
void main() {
group('LogRxRouteDecoder.decode', () {
test('parses route and sender from LOG_RX_DATA packet', () {
final packet = Uint8List.fromList([
0x88,
0x37,
0xae,
0x05,
0x04,
0xc2,
0xba,
0x5f,
0xde,
0x5c,
]);
final decoded = LogRxRouteDecoder.decode(packet);
expect(decoded, isNotNull);
expect(decoded!.payloadType, 0x01);
expect(decoded.pathHashes, [0xc2, 0xba, 0x5f, 0xde]);
expect(decoded.originalSenderHash, 0xc2);
});
});
group('LogRxRouteDecoder.resolveHash', () {
test('prefers own node when hash matches device key', () {
final resolved = LogRxRouteDecoder.resolveHash(
0xc2,
contacts: const [],
ownPublicKey: Uint8List.fromList([0xc2, 0x01, 0x02]),
ownName: 'Base',
);
expect(resolved.isOwnNode, isTrue);
expect(resolved.label, 'Base (you)');
});
test('resolves unique contact by first public key byte', () {
final resolved = LogRxRouteDecoder.resolveHash(
0xc2,
contacts: [_contact(name: 'Alpha', keyPrefix: 0xc2)],
);
expect(resolved.isUniqueMatch, isTrue);
expect(resolved.label, 'Alpha');
});
test('marks ambiguous matches without pretending certainty', () {
final resolved = LogRxRouteDecoder.resolveHash(
0xc2,
contacts: [
_contact(name: 'Alpha', keyPrefix: 0xc2),
_contact(name: 'Bravo', keyPrefix: 0xc2),
],
);
expect(resolved.isUniqueMatch, isFalse);
expect(resolved.matchCount, 2);
});
});
}
Contact _contact({required String name, required int keyPrefix}) {
return Contact(
publicKey: Uint8List.fromList([
keyPrefix,
0x11,
0x22,
0x33,
0x44,
0x55,
0x66,
0x77,
]),
type: ContactType.chat,
flags: 0,
outPathLen: 0,
outPath: Uint8List(0),
advName: name,
lastAdvert: 0,
advLat: 0,
advLon: 0,
lastMod: 0,
);
}

View File

@@ -6,74 +6,122 @@ void main() {
group('VoiceEnvelope', () {
test('encodes and parses valid envelope', () {
final env = VoiceEnvelope(
sessionId: 'deadbeef',
sessionId: '0000000a',
mode: VoicePacketMode.mode1200,
total: 4,
durationMs: 3200,
durationMs: 3000,
senderKey6: 'aabbccddeeff',
timestampSec: 1700000000,
);
final text = env.encodeText();
expect(VoiceEnvelope.isVoiceEnvelopeText(text), isTrue);
expect(text.startsWith('VE2:'), isTrue);
expect(text.split(':')[1], equals('a'));
final parsed = VoiceEnvelope.tryParseText(text);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('deadbeef'));
expect(parsed!.sessionId, equals('0000000a'));
expect(parsed.mode, equals(VoicePacketMode.mode1200));
expect(parsed.total, equals(4));
expect(parsed.durationMs, equals(3200));
expect(parsed.durationMs, equals(3000));
expect(parsed.senderKey6, equals('aabbccddeeff'));
expect(parsed.version, equals(1));
expect(parsed.version, equals(2));
});
test('rejects invalid envelope payload', () {
final text = 'VE1:nothex:1:2:1000:aabbccddeeff:1700000000:1';
final text = 'VE2:bad_sid:1:2:1000:aabbccddeeff:s44we8';
expect(VoiceEnvelope.tryParseText(text), isNull);
});
test('rejects legacy v1 envelope prefix', () {
const legacy = 'VE1:deadbeef:1:4:3200:aabbccddeeff:1700000000:1';
expect(VoiceEnvelope.tryParseText(legacy), isNull);
});
});
group('VoiceFetchRequest', () {
test('encodes and parses valid request', () {
final req = VoiceFetchRequest(
sessionId: '00112233',
sessionId: '0000000a',
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final text = req.encodeText();
expect(VoiceFetchRequest.isVoiceFetchRequestText(text), isTrue);
expect(text.startsWith('VR2:'), isTrue);
expect(text.split(':')[1], equals('a'));
final parsed = VoiceFetchRequest.tryParseText(text);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('00112233'));
expect(parsed!.sessionId, equals('0000000a'));
expect(parsed.want, equals('all'));
expect(parsed.requesterKey6, equals('ffeeddccbbaa'));
expect(parsed.version, equals(1));
expect(parsed.version, equals(2));
});
test('rejects invalid request payload', () {
expect(
VoiceFetchRequest.tryParseText(
'VR1:00112233:chunk:ffeeddccbbaa:1700000001:1',
'VR2:a:chunk:ffeeddccbbaa:s44we9',
),
isNull,
);
});
test('rejects legacy v1 request prefix', () {
const legacy = 'VR1:00112233:a:ffeeddccbbaa:1700000001:1';
expect(VoiceFetchRequest.tryParseText(legacy), isNull);
});
test('encodes and parses missing-packet request', () {
final req = VoiceFetchRequest(
sessionId: '00112233',
sessionId: '0000000a',
want: 'missing',
missingIndices: const [0, 3, 7],
missingIndices: const [0, 1, 2, 3, 7],
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final text = req.encodeText();
expect(text, contains(':m0-3.7:'));
final parsed = VoiceFetchRequest.tryParseText(text);
expect(parsed, isNotNull);
expect(parsed!.want, equals('missing'));
expect(parsed.missingIndices, equals([0, 3, 7]));
expect(parsed.missingIndices, equals([0, 1, 2, 3, 7]));
});
test('encodes and parses binary fetch request', () {
final req = VoiceFetchRequest(
sessionId: '01020304',
want: 'missing',
missingIndices: const [1, 4],
requesterKey6: 'ffeeddccbbaa',
timestampSec: 1700000001,
);
final payload = req.encodeBinary();
expect(VoiceFetchRequest.isVoiceFetchRequestBinary(payload), isTrue);
final parsed = VoiceFetchRequest.tryParseBinary(payload);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('01020304'));
expect(parsed.want, equals('missing'));
expect(parsed.missingIndices, equals([1, 4]));
expect(parsed.requesterKey6, equals('ffeeddccbbaa'));
expect(parsed.version, equals(2));
});
});
group('VoiceFragmentAck', () {
test('encodes and parses binary ack', () {
final ack = VoiceFragmentAck(sessionId: '01020304', index: 7);
final payload = ack.encodeBinary();
expect(VoiceFragmentAck.isVoiceFragmentAckBinary(payload), isTrue);
final parsed = VoiceFragmentAck.tryParseBinary(payload);
expect(parsed, isNotNull);
expect(parsed!.sessionId, equals('01020304'));
expect(parsed.index, equals(7));
});
});

View File

@@ -0,0 +1,106 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/widgets/common/contact_avatar.dart';
void main() {
Contact buildContact({
required String name,
required ContactType type,
int secondByte = 0,
}) {
final publicKey = Uint8List(32);
publicKey[1] = secondByte;
return Contact(
publicKey: publicKey,
type: type,
flags: 0,
outPathLen: 0,
outPath: Uint8List(0),
advName: name,
lastAdvert: 0,
advLat: 0,
advLon: 0,
lastMod: 0,
);
}
Future<void> pumpAvatar(WidgetTester tester, Contact contact) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: Center(child: ContactAvatar(contact: contact))),
),
);
}
testWidgets('renders label avatar for rooms', (tester) async {
await pumpAvatar(
tester,
buildContact(name: 'Operations Room', type: ContactType.room),
);
expect(find.text('OR'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
expect(find.byIcon(Icons.meeting_room), findsNothing);
});
testWidgets('renders hash label avatar for rooms', (tester) async {
await pumpAvatar(
tester,
buildContact(name: '#ops-room', type: ContactType.room),
);
expect(find.text('#OP'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
expect(find.byIcon(Icons.meeting_room), findsNothing);
});
testWidgets('renders compact hash label avatar when name includes spacing', (
tester,
) async {
await pumpAvatar(
tester,
buildContact(name: '# foo alpha', type: ContactType.room),
);
expect(find.text('#FO'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
expect(find.byIcon(Icons.meeting_room), findsNothing);
});
testWidgets('renders label avatar for channels', (tester) async {
await pumpAvatar(
tester,
buildContact(name: '#ops', type: ContactType.channel, secondByte: 3),
);
expect(find.text('#OP'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
expect(find.byIcon(Icons.public), findsNothing);
});
testWidgets('renders non-hash label avatar for channels', (tester) async {
await pumpAvatar(
tester,
buildContact(name: 'Command Net', type: ContactType.channel, secondByte: 3),
);
expect(find.text('CN'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
expect(find.byIcon(Icons.public), findsNothing);
});
testWidgets('renders round avatar for chat contacts', (tester) async {
await pumpAvatar(
tester,
buildContact(name: 'John Smith', type: ContactType.chat),
);
expect(find.text('JS'), findsOneWidget);
expect(find.byType(CircleAvatar), findsOneWidget);
expect(find.byIcon(Icons.person), findsNothing);
});
}