diff --git a/.github/workflows/release-signed.yml b/.github/workflows/release-signed.yml index 1529db28..f26b1ec2 100644 --- a/.github/workflows/release-signed.yml +++ b/.github/workflows/release-signed.yml @@ -292,17 +292,47 @@ jobs: run: | set -eu TAG="${GITHUB_REF_NAME}" + + # Whether a tag publishes as a full release or a prerelease is DERIVED + # from the tag, never hardcoded (#652). A bare vMAJOR.MINOR.PATCH is a + # full release; anything else is a prerelease. + # + # Defaulting the unrecognised shape to prerelease is deliberate. The + # legacy tags (observer-g2-rc3, v1.1.2-queuediag, v1.1.2-rc.1-b54-rxfed) + # belong there, and a tag whose shape we do not recognise can never + # publish itself as stable by accident. + # + # The flag is passed EXPLICITLY in both branches, including the + # =false form. gh only changes what it is told to change, so a retry + # that omitted the flag was what left a stale prerelease in place. + # + # --latest is deliberately NOT passed: `gh release create --help` + # documents the default as "automatic based on date and version", + # which is what we want. Forcing it would promote a back-ported patch + # tagged after a newer minor. + if printf '%s' "${TAG}" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then + PRERELEASE_FLAG="--prerelease=false" + else + PRERELEASE_FLAG="--prerelease" + fi + echo "Tag ${TAG} resolves to ${PRERELEASE_FLAG}" + if gh release view "${TAG}" >/dev/null 2>&1; then # Retry / re-run: refresh assets and notes, then ensure published. gh release upload "${TAG}" out/* --clobber - gh release edit "${TAG}" --notes-file "${NOTES}" --prerelease --draft=false + gh release edit "${TAG}" --notes-file "${NOTES}" "${PRERELEASE_FLAG}" --draft=false else gh release create "${TAG}" \ --draft \ --title "Offband Meshcore ${VERSION}" \ --notes-file "${NOTES}" \ - --prerelease + "${PRERELEASE_FLAG}" gh release upload "${TAG}" out/* - gh release edit "${TAG}" --draft=false + # The prerelease flag is restated here, not just on create, so both + # branches converge on ONE publish call that declares the complete + # final state. Relying on create+draft to have persisted the flag + # would make publication depend on behaviour we have not verified, + # which is the same class of assumption that caused #652. + gh release edit "${TAG}" "${PRERELEASE_FLAG}" --draft=false fi echo "Release ${TAG} published with $(ls out | wc -l) assets." diff --git a/.github/workflows/triage-user-issues.yml b/.github/workflows/triage-user-issues.yml index 635c5fc5..a0cddefb 100644 --- a/.github/workflows/triage-user-issues.yml +++ b/.github/workflows/triage-user-issues.yml @@ -6,7 +6,14 @@ name: Triage User-Submitted Issues # (label -> board) fires and sets Status=Backlog / Priority=Medium on board #2. # `type:` is intentionally left for manual triage (type is the judgment call). # -# Maintainer-opened issues (author_association OWNER/MEMBER/COLLABORATOR) are untouched. +# Only MISSING labels are applied. An issue that already carries a `priority:` or +# `board:` label keeps it — see #663, where defaulting on top of deliberate labels +# left issues holding two priorities and two board states at once. +# +# Untouched: issues opened by a maintainer (author_association OWNER/MEMBER/ +# COLLABORATOR) and issues opened by an account in INTERNAL_ACTORS. The actor +# allowlist exists because author_association alone is not trustworthy — a private +# org membership reports as NONE in the webhook payload (#663). # # Requires repo secret PROJECT_PAT (classic PAT, project+repo scope) — the same # secret sync-labels-to-board.yml uses. The PAT is also what lets the added labels @@ -37,9 +44,15 @@ jobs: github-token: ${{ secrets.PROJECT_PAT }} script: | const INTERNAL = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); + // author_association is not reliable on its own: the webhook payload reports + // NONE for an org member whose membership is private, even while REST reports + // MEMBER. That demoted every agent-filed issue from 2026-09-17 on (#663). + // Name the internal automation accounts outright so the gate stops depending + // on a visibility setting anyone can flip back. + const INTERNAL_ACTORS = new Set(['diffwireauto']); const isDispatch = context.eventName === 'workflow_dispatch'; - let issueNumber, association; + let issueNumber, association, author; if (isDispatch) { issueNumber = parseInt(context.payload.inputs.issue_number, 10); @@ -53,23 +66,45 @@ jobs: issue_number: issueNumber, }); association = issue.author_association; - core.info(`Manual dispatch for #${issueNumber} (author_association=${association}) — bypassing author gate for test`); + author = issue.user?.login ?? ''; + core.info(`Manual dispatch for #${issueNumber} (author ${author}, author_association=${association}) — bypassing author gate for test`); } else { issueNumber = context.payload.issue.number; association = context.payload.issue.author_association; - if (INTERNAL.has(association)) { - core.info(`#${issueNumber} opened by ${association} (maintainer) — skipping triage`); + author = context.payload.issue.user?.login ?? ''; + if (INTERNAL.has(association) || INTERNAL_ACTORS.has(author)) { + core.info(`#${issueNumber} opened by ${author} (${association}) — internal, skipping triage`); return; } - core.info(`#${issueNumber} opened by external author (${association}) — triaging`); + core.info(`#${issueNumber} opened by external author ${author} (${association}) — triaging`); + } + + // addLabels only adds. Defaulting a priority or board state onto an issue that + // already carries one leaves it holding two of each and lets the downstream + // label -> board sync pick a winner, so only fill in what is actually missing. + const { data: current } = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + }); + const existing = current.map((l) => l.name); + const hasPrefix = (prefix) => existing.some((n) => n.startsWith(prefix)); + + const labels = []; + if (!existing.includes('user-submitted')) labels.push('user-submitted'); + if (!hasPrefix('priority:')) labels.push('priority:P2'); + if (!hasPrefix('board:')) labels.push('board:backlog'); + + if (labels.length === 0) { + core.info(`#${issueNumber} is already flagged and triaged [${existing.join(', ')}] — nothing to apply.`); + return; } - const labels = ['user-submitted', 'priority:P2', 'board:backlog']; await github.rest.issues.addLabels({ owner: context.repo.owner, repo: context.repo.repo, issue_number: issueNumber, labels, }); - core.info(`Applied [${labels.join(', ')}] to #${issueNumber}.`); - core.info('sync-labels-to-board.yml will set Status=Backlog / Priority=Medium on board #2.'); + core.info(`Applied [${labels.join(', ')}] to #${issueNumber} (already had [${existing.join(', ') || 'none'}]).`); + core.info('sync-labels-to-board.yml will set Status/Priority on board #2 for any board:/priority: label added here.'); diff --git a/CHANGELOG.md b/CHANGELOG.md index 379c9ce3..02f15b87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,117 @@ All notable changes to Offband Meshcore. Pre-releases are tagged `-beta.N` / `-rc.N`. +## [1.6.0] - 2026-10-05 + +First stable release of the 1.5.0 line and the production successor to 1.4.0. A large +feature release: a full contacts overhaul, stock-compatible config and identity +export/import, region radio presets, and contact-sync recovery, on top of the +1.5.0-beta.1 groundwork (Experimental section, CoreScope, About). + +### Contacts + +- A received contact-share on a channel renders an **Add Contact** card/chip (#610). +- **Share your contact into a channel** from a + picker (#611). +- **Contact QR**: show your contact as a QR and scan one to add (#629). +- **Add a contact by public key**, typed or pasted, or from a key alone with no + advert (#627, #628). +- Parse and emit the **stock contact-share URI**, so contacts cross between Offband + and stock MeshCore (#625, #626). +- A contact shows **how far its identity is confirmed** (#630). +- Add, view, or block a **channel sender** from an avatar tap or long-press + (#565, #468). + +### Config and identity portability + +- **Stock-compatible config export and import** screens and services + (#572, #573, #574, #575, #576). +- **Connector identity export/import**, with an auto-add hop limit (#578). + +### Radio presets + +- A **region-grouped preset picker** labeled by source, crediting Liam Cottle / + MeshCore for the upstream presets (#727, #728, #729, #731). +- Apply a preset's path hash to a companion, observer, repeater, or room server + (#730, #735, #649), with the picker in repeater and room-server settings (#734). + +### Sync and reliability + +- Detect a **short contact sync** and recover it with paced, capped re-syncs and + by-key checks, with a banner reporting the recovered count and contacts confirmed + gone (#762, #763, #764, #674). +- **Apply a remote radio setting temporarily** (tempradio) (#662). +- Manage a **sensor like a repeater** (#745). +- Composer byte-budget logging so a debug log can evidence the BLE composer issue + anywhere (#793). + +### Experimental and UX (from the 1.5.0-beta.1 groundwork) + +- An **Experimental section** unlocked by a 7-tap on the Build row; disabling it + clears every experimental toggle (#509, #553). +- **OKIMesh CoreScope** (Experimental): per-packet observer counts from OKIMesh's + CoreScope service. Requires forthcoming Offband firmware and stays inert until + then (#549, #550). +- An **About screen** in its own Settings category (#526, #527). +- Notifications moved from a bottom SnackBar to a **top toast** (#638). + +### Bluetooth reliability + +- The composer is no longer locked by an unreported BLE MTU: the negotiated MTU is now + reported on Linux (#717) and Windows (via a vendored BLE plugin with live MTU + updates) (#686), and the floor that locked it on web is lifted (#718). A link that + truly cannot carry a message explains why instead of showing a dead field (#684). +- Bounded GATT-133 connect retry with human-readable errors (#698); an unconfirmed + disconnect retries and warns instead of being swallowed (#697); leaked GATT handles + are closed (#696). +- USB serial no longer drops bytes: mutexes initialize before the reader runs, and each + callback drains fully (#710, #711). + +### Fixes + +- Delivered direct messages are no longer marked failed: send correlation adopts the + radio's RESP_CODE_SENT ACK hash (#581). +- A short or unreadable contact sync never overwrites saved contacts, and a silent + stream ends on its own (#671, #673, #672). +- Names are no longer truncated mid-codepoint on the wire (#636). +- Late repeater replies go to the app log, not the user's screen (#589). +- Add-contact failures and unknown channel-sender names surface instead of a dead tap + (#565). +- CoreScope distinguishes not-found from unreachable (#678); web identity rebranded + (#608). + +### Known issues + +- Windows BLE Disconnect can leave the radio held by the OS until replug (#688). + +## [1.5.0-beta.1] - 2026-08-04 + +First beta of the 1.5.0 line, for the closed test track. Introduces an Experimental +section (with CoreScope), an About screen, and repeater CLI and broker fixes. + +### Added + +- **Experimental section**, unlocked by a hidden 7-tap on the Build row in settings. + Disabling it clears all experimental toggles (#509, #553). +- **OKIMesh CoreScope integration (Experimental).** Query how many OKIMesh CoreScope + observers heard each packet, over the 0xC6 protocol, with an observer/observations + badge, adaptive polling with backoff, and tap / long-press to refresh (#549, #550). + This is tied specifically to the OKIMesh CoreScope service, not a generic or + self-hosted backend. Requires forthcoming Offband firmware (0xC6, cap2 bit and + firmware ver code >= 22, tracked in #611); it stays inert on current firmware. +- **About screen** in its own top-level Settings category, with outbound links to + the website, Play listing, and donate page (#526, #527). + +### Fixed + +- Repeater CLI: late replies are surfaced instead of discarded, commands get their + own timeout budget, the armed timeout window is reported accurately, and a + prefixed reply only completes the command that owns the prefix (#528, #529, #531, + #532, #533). +- Broker: import never changes the broker enabled state, and a blank-field GET no + longer leaks the echoed key line (#469, #470). +- Channel "Send Again" is gated on `repeatCount == 0` rather than sent status + (#555). + ## [1.4.0] - 2026-07-30 A follow-up to the 1.3.0 production launch: settings for headless devices, a diff --git a/CLAUDE.md b/CLAUDE.md index dd5b75e0..2b3ef290 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -295,7 +295,7 @@ App version: `9.1.0+14` — Dart SDK constraint: `^3.9.2` - `LSApplicationQueriesSchemes`: `http`, `https` ### Web (`web/`) -PWA scaffold present but boilerplate (`manifest.json` and `index.html` are unmodified Flutter defaults). BLE is unsupported in browsers; TCP and Web Serial USB may work in Chrome only. `ChromeRequiredScreen` gates non-Chrome web users. Versioned releases are produced via `build_pipe` (`?v=` cache busting, no service worker). +The web client is live at `offband.app` (deployed by CI via Cloudflare Pages). **BLE works on web via Web Bluetooth (`flutter_blue_plus_web`), in Chromium browsers only**: Chrome/Edge on desktop and Android; iOS has no Web Bluetooth in any browser; Linux Chrome may require enabling `chrome://flags/#enable-web-bluetooth`. Connecting requires HTTPS and a user gesture (the browser's device-chooser dialog — no passive scan list). TCP is disabled on web (`scanner_screen.dart` gates it with `!PlatformInfo.isWeb`); Web Serial USB may work in Chrome only. `ChromeRequiredScreen` gates non-Chromium browsers. Versioned assets use `?v=` cache busting (no service worker). ### Desktop `linux/`, `windows/`, and `macos/` directories are present as Flutter scaffolds. No app-specific native config has been added; BLE on desktop has not been validated. diff --git a/assets/radio_presets/meshcore-upstream.json b/assets/radio_presets/meshcore-upstream.json new file mode 100644 index 00000000..f8dfb7e1 --- /dev/null +++ b/assets/radio_presets/meshcore-upstream.json @@ -0,0 +1,244 @@ +{ + "format": "meshcore-upstream-radio-presets", + "format_version": 1, + "source": "https://api.meshcore.nz/api/v1/config", + "credit": "Radio presets maintained by Liam Cottle for MeshCore (meshcore.nz), the list the stock MeshCore app shows. Mirrored unmodified from https://api.meshcore.nz/api/v1/config. Offband's own additions live in offband.json. Credit: https://github.com/OffbandMesh/config-profiles#credit", + "updated_at": "2026-10-01T07:48:36Z", + "suggested_radio_settings": { + "info_message": "These presets are suggested by the community.", + "entries": [ + { + "title": "Australia", + "description": "915.800MHz / SF10 / BW250 / CR5", + "frequency": "915.800", + "spreading_factor": "10", + "bandwidth": "250", + "coding_rate": "5" + }, + { + "title": "Australia (Narrow)", + "description": "916.575MHz / SF7 / BW62.5 / CR7", + "frequency": "916.575", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "7" + }, + { + "title": "Australia (Mid)", + "description": "915.075MHz / SF9 / BW125 / CR5", + "frequency": "915.075", + "spreading_factor": "9", + "bandwidth": "125", + "coding_rate": "5" + }, + { + "title": "Australia: SA, WA", + "description": "923.125MHz / SF8 / BW62.5 / CR8", + "frequency": "923.125", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8" + }, + { + "title": "Australia: QLD", + "description": "923.125MHz / SF8 / BW62.5 / CR5", + "frequency": "923.125", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "5" + }, + { + "title": "Brazil", + "description": "923.125MHz / SF8 / BW62.5 / CR8", + "frequency": "923.125", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8" + }, + { + "title": "Canada", + "description": "910.525MHz / SF7 / BW62.5 / CR5 / 3B", + "frequency": "910.525", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 3 + } + }, + { + "title": "Costa Rica", + "description": "910.525MHz / SF11 / BW125 / CR5", + "frequency": "910.525", + "spreading_factor": "11", + "bandwidth": "125", + "coding_rate": "5" + }, + { + "title": "EU/UK (Narrow)", + "description": "869.618MHz / SF8 / BW62.5 / CR8", + "frequency": "869.618", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8" + }, + { + "title": "EU/UK (Deprecated)", + "description": "869.525MHz / SF11 / BW250 / CR5", + "frequency": "869.525", + "spreading_factor": "11", + "bandwidth": "250", + "coding_rate": "5" + }, + { + "title": "Czech Republic (Narrow)", + "description": "869.432MHz / SF7 / BW62.5 / CR5 / 2B", + "frequency": "869.432", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 2 + } + }, + { + "title": "EU 433MHz (Long Range)", + "description": "433.650MHz / SF11 / BW250 / CR5", + "frequency": "433.650", + "spreading_factor": "11", + "bandwidth": "250", + "coding_rate": "5" + }, + { + "title": "EU 433MHz (Narrow)", + "description": "433.650MHz / SF8 / BW62.5 / CR8", + "frequency": "433.650", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8" + }, + { + "title": "Hungary", + "description": "869.618MHz / SF7 / BW62.5 / CR5 / 2B", + "frequency": "869.618", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 2 + } + }, + { + "title": "Netherlands", + "description": "869.618MHz / SF7 / BW62.5 / CR5", + "frequency": "869.618", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5" + }, + { + "title": "Netherlands (Limburg)", + "description": "869.618MHz / SF8 / BW62.5 / CR8 / 2B", + "frequency": "869.618", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8", + "network_settings": { + "path_hash_size": 2 + } + }, + { + "title": "New Zealand (Narrow)", + "description": "917.375MHz / SF7 / BW62.5 / CR5 / 2B", + "frequency": "917.375", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 2 + } + }, + { + "title": "New Zealand (Gisborne)", + "description": "917.375MHz / SF11 / BW250 / CR5 / 1B", + "frequency": "917.375", + "spreading_factor": "11", + "bandwidth": "250", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 1 + } + }, + { + "title": "Portugal 433", + "description": "433.375MHz / SF9 / BW62.5 / CR6", + "frequency": "433.375", + "spreading_factor": "9", + "bandwidth": "62.5", + "coding_rate": "6" + }, + { + "title": "Portugal 868", + "description": "869.618MHz / SF7 / BW62.5 / CR6", + "frequency": "869.618", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "6" + }, + { + "title": "Slovakia", + "description": "869.618MHz / SF7 / BW62.5 / CR5 / 2B", + "frequency": "869.618", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 2 + } + }, + { + "title": "Switzerland", + "description": "869.618MHz / SF8 / BW62.5 / CR8", + "frequency": "869.618", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "8" + }, + { + "title": "USA", + "description": "910.525MHz / SF7 / BW62.5 / CR5", + "frequency": "910.525", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5" + }, + { + "title": "USA - Southern California", + "description": "927.875MHz / SF7 / BW62.5 / CR5 / 3B", + "frequency": "927.875", + "spreading_factor": "7", + "bandwidth": "62.5", + "coding_rate": "5", + "network_settings": { + "path_hash_size": 3 + } + }, + { + "title": "Vietnam (Narrow)", + "description": "920.250MHz / SF8 / BW62.5 / CR5", + "frequency": "920.250", + "spreading_factor": "8", + "bandwidth": "62.5", + "coding_rate": "5" + }, + { + "title": "Vietnam (Deprecated)", + "description": "920.250MHz / SF11 / BW250 / CR5", + "frequency": "920.250", + "spreading_factor": "11", + "bandwidth": "250", + "coding_rate": "5" + } + ] + } +} diff --git a/assets/radio_presets/offband.json b/assets/radio_presets/offband.json new file mode 100644 index 00000000..3399b4aa --- /dev/null +++ b/assets/radio_presets/offband.json @@ -0,0 +1,407 @@ +{ + "format": "offband-radio-presets", + "format_version": 1, + "description": "Offband radio preset overlay. These entries are added to the MeshCore preset list mirrored in meshcore-upstream.json, and win over it when a title matches. Edit this file to add, change or retire a preset; the app picks the change up on its next refresh, with no app release. See SCHEMA.md.", + "presets": [ + { + "id": "usa-arizona", + "title": "USA - Arizona", + "region": "USA", + "frequency": 908.205, + "bandwidth": 62.5, + "spreading_factor": 9, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "SF9/CR8 per zjs81/meshcore-open#507 (Tucson / Phoenix alignment). Unconfirmed by an Arizona authority; owner decision 2026-10-01." + }, + { + "id": "usa-philly-mesh", + "title": "USA - Philly Mesh", + "region": "USA", + "frequency": 919.5, + "bandwidth": 500, + "spreading_factor": 10, + "coding_rate": 5, + "tx_power": 20, + "path_hash_size": 2, + "status": "published", + "notes": "phillymesh.net, 2026-10-01: 919.500 / 500 kHz / SF10 / CR 4/5 / path hash mode 1 (2-byte). Replaces their original 902.25 guidance. TX power not published; 20 dBm matches the US entries." + }, + { + "id": "usa-oki-mesh-500khz-test", + "title": "USA - OKI-Mesh 500kHz Test", + "region": "USA", + "frequency": 909.75, + "bandwidth": 500, + "spreading_factor": 10, + "coding_rate": 5, + "tx_power": 20, + "status": "published", + "notes": "docs.okimesh.org 500kHz-testing (test started 2026-09-23). OKI has not settled on a frequency; expect this to change. TX power not published; 20 dBm matches the US entries." + }, + { + "id": "russia-artyom-vvo", + "title": "Russia Artyom (VVO)", + "region": "Russia", + "frequency": 864.281, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-biysk-bsk", + "title": "Russia Biysk (BSK)", + "region": "Russia", + "frequency": 869.0, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 5, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-chelyabinsk-cek", + "title": "Russia Chelyabinsk (CEK)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-cherepovets-cee", + "title": "Russia Cherepovets (CEE)", + "region": "Russia", + "frequency": 868.57, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-irkutsk-ikt", + "title": "Russia Irkutsk (IKT)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-ivanovo-iwa", + "title": "Russia Ivanovo (IWA)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-izhevsk-ijk", + "title": "Russia Izhevsk (IJK)", + "region": "Russia", + "frequency": 868.732, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-kaluga-klf", + "title": "Russia Kaluga (KLF)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-kazan-kzn", + "title": "Russia Kazan (KZN)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-khabarovsk-khv", + "title": "Russia Khabarovsk (KHV)", + "region": "Russia", + "frequency": 864.281, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-kirov-kvx", + "title": "Russia Kirov (KVX)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-lipetsk-lpk", + "title": "Russia Lipetsk (LPK)", + "region": "Russia", + "frequency": 868.95, + "bandwidth": 62.5, + "spreading_factor": 9, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-moscow-mow", + "title": "Russia Moscow (MOW)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-nizhny-novgorod-goj", + "title": "Russia Nizhny Novgorod (GOJ)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-novosibirsk-ovb", + "title": "Russia Novosibirsk (OVB)", + "region": "Russia", + "frequency": 869.0, + "bandwidth": 62.5, + "spreading_factor": 9, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-rostov-on-don-rov", + "title": "Russia Rostov-on-Don (ROV)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 9, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-ryazan-rzn", + "title": "Russia Ryazan (RZN)", + "region": "Russia", + "frequency": 868.88, + "bandwidth": 62.5, + "spreading_factor": 9, + "coding_rate": 5, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-samara-kuf", + "title": "Russia Samara (KUF)", + "region": "Russia", + "frequency": 864.281, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-saratov-gsv", + "title": "Russia Saratov (GSV)", + "region": "Russia", + "frequency": 864.281, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-st-petersburg-led", + "title": "Russia St. Petersburg (LED)", + "region": "Russia", + "frequency": 868.856, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-tambov-tbw", + "title": "Russia Tambov (TBW)", + "region": "Russia", + "frequency": 868.95, + "bandwidth": 62.5, + "spreading_factor": 10, + "coding_rate": 5, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-tula-tya", + "title": "Russia Tula (TYA)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-tver-kld", + "title": "Russia Tver (KLD)", + "region": "Russia", + "frequency": 869.169, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-ufa-ufa", + "title": "Russia Ufa (UFA)", + "region": "Russia", + "frequency": 868.732, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 8, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-volgograd-vog", + "title": "Russia Volgograd (VOG)", + "region": "Russia", + "frequency": 869.525, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-voronezh-voz", + "title": "Russia Voronezh (VOZ)", + "region": "Russia", + "frequency": 868.731, + "bandwidth": 62.5, + "spreading_factor": 8, + "coding_rate": 6, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "russia-yekaterinburg-svx", + "title": "Russia Yekaterinburg (SVX)", + "region": "Russia", + "frequency": 869.046, + "bandwidth": 62.5, + "spreading_factor": 7, + "coding_rate": 7, + "tx_power": 20, + "status": "published", + "notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)." + }, + { + "id": "off-grid-433", + "title": "Off-Grid 433", + "region": "Off-Grid", + "frequency": 433.0, + "bandwidth": 250, + "spreading_factor": 11, + "coding_rate": 8, + "tx_power": 20, + "off_grid": true, + "status": "published", + "notes": "Client-repeat frequency, used by the companion's off-grid repeat mode." + }, + { + "id": "off-grid-869", + "title": "Off-Grid 869", + "region": "Off-Grid", + "frequency": 869.0, + "bandwidth": 250, + "spreading_factor": 11, + "coding_rate": 8, + "tx_power": 14, + "off_grid": true, + "status": "published", + "notes": "Client-repeat frequency, used by the companion's off-grid repeat mode." + }, + { + "id": "off-grid-918", + "title": "Off-Grid 918", + "region": "Off-Grid", + "frequency": 918.0, + "bandwidth": 250, + "spreading_factor": 11, + "coding_rate": 8, + "tx_power": 20, + "off_grid": true, + "status": "published", + "notes": "Client-repeat frequency, used by the companion's off-grid repeat mode." + } + ] +} diff --git a/discord/1.5.0-beta.1.md b/discord/1.5.0-beta.1.md new file mode 100644 index 00000000..bd2fd6ed --- /dev/null +++ b/discord/1.5.0-beta.1.md @@ -0,0 +1,15 @@ +🧪 **Testing build: Offband Meshcore 1.5.0-beta.1** is on the closed test track. + +This is the first beta of the 1.5.0 line. It's a testing build, so treat it as not-yet-stable, and your bug reports are exactly what make the production release solid. + +**What's new to poke at:** + +🔓 **Experimental section.** A hidden **7-tap on the Build row** in settings unlocks an Experimental area. Turning the section back off clears every experimental toggle. + +🛰️ **OKIMesh CoreScope (Experimental).** See how many **OKIMesh CoreScope** observers heard each packet, with an observer/observations badge and tap or long-press to refresh. This is tied specifically to OKIMesh's CoreScope, not a generic backend. **Heads-up:** it needs a **forthcoming Offband firmware** (not available for download yet) and stays inert until you're on it. It's here so it's ready to test the moment that firmware ships. + +ℹ️ **About screen.** About now has its own Settings category with links to the website, Play listing, and donate page. + +🛠️ **Fixes:** steadier repeater CLI (late replies, timeout budgets), broker import no longer touches the enabled state or leaks a key line, and channel "Send Again" gating. + +Not on the test track yet and want in? Ask here. Thanks for testing. 📡 diff --git a/discord/1.6.0.md b/discord/1.6.0.md new file mode 100644 index 00000000..47bbe4f2 --- /dev/null +++ b/discord/1.6.0.md @@ -0,0 +1,25 @@ +🚀 **Offband Meshcore 1.6.0 is out.** Our biggest update yet, and the stable successor to 1.4.0 on Google Play. Over 100 changes since the beta. The big ones: + +👥 **Contacts, reworked.** +- Tap a contact shared on a channel to **Add Contact**, or share your own contact into a channel. +- Add someone by **public key** (type/paste, or key-only before an advert), or by **QR** (show and scan). +- Full **cross-client with stock MeshCore**: contact shares move both ways. +- Each contact shows **how confirmed its identity is**, and you can add/view/block a channel sender right from their avatar. + +🧳 **Bring your setup with you.** Stock-compatible **config export/import** and **identity export/import**, so moving between radios (or in and out of stock) just works. + +📻 **Radio presets.** A region-grouped **preset picker** labeled by source (credit to Liam Cottle / MeshCore for the upstream presets). Apply a preset's path hash to a companion, observer, repeater, or room server, with region matching that won't mislabel a USA radio as Canada. + +🔁 **Sync that heals itself.** Offband now detects a short contact sync and recovers it automatically, tells you the recovered count and which contacts are genuinely gone, and (importantly) **never overwrites your saved contacts** on a short or unreadable sync. + +📶 **Bluetooth reliability, big pass.** The composer no longer locks up from an unreported BLE MTU: negotiated MTU is now reported on **Windows, Linux, and web**, and if a link truly can't carry a message it tells you why instead of going dead. Plus bounded GATT-133 retry with readable errors, disconnects that retry-and-warn instead of vanishing, and closed GATT handle leaks. + +✉️ **Messaging fixes.** Delivered DMs are no longer marked failed (send correlation now uses the radio's own ACK hash), and late repeater replies go to the log instead of your screen. + +➕ Plus an **About screen**, **top-of-screen notifications**, USB serial that doesn't drop bytes, and (experimental) **OKIMesh CoreScope** per-packet observer counts. + +**📥 Get it on Google Play:** search **Offband MeshCore**, or https://play.google.com/store/apps/details?id=app.offband.meshcore +💻 **Desktop (Windows / Linux) and Android APK:** https://github.com/OffbandMesh/meshcore-client/releases/tag/v1.6.0 +🌐 **Or run it in your browser:** https://offband.app + +💚 Thanks as always to the **OKIMesh community** (https://okimesh.org/). Offband is open source and always will be; if you'd like to help keep it going: https://offband.org/donate diff --git a/docs/assets/n30nex-neonpocket-rcc6-web-ui.png b/docs/assets/n30nex-neonpocket-rcc6-web-ui.png new file mode 100644 index 00000000..887dd927 Binary files /dev/null and b/docs/assets/n30nex-neonpocket-rcc6-web-ui.png differ diff --git a/docs/assets/n30nex-rcc6-field-terminal-concept.png b/docs/assets/n30nex-rcc6-field-terminal-concept.png new file mode 100644 index 00000000..bcee377c Binary files /dev/null and b/docs/assets/n30nex-rcc6-field-terminal-concept.png differ diff --git a/docs/assets/n30nex-rcc6-observapeater-dashboard.png b/docs/assets/n30nex-rcc6-observapeater-dashboard.png new file mode 100644 index 00000000..28decb30 Binary files /dev/null and b/docs/assets/n30nex-rcc6-observapeater-dashboard.png differ diff --git a/docs/assets/n30nex-rcc6-tft-device-ui.png b/docs/assets/n30nex-rcc6-tft-device-ui.png new file mode 100644 index 00000000..54856cf9 Binary files /dev/null and b/docs/assets/n30nex-rcc6-tft-device-ui.png differ diff --git a/docs/initiatives/standalone/647-mesh500-presets/OUTCOMES.md b/docs/initiatives/standalone/647-mesh500-presets/OUTCOMES.md new file mode 100644 index 00000000..4dd4cbbd --- /dev/null +++ b/docs/initiatives/standalone/647-mesh500-presets/OUTCOMES.md @@ -0,0 +1,40 @@ +# Feature #647: outcomes + +Written from what happened, including what failed. Plan: [PLAN.md](PLAN.md). All dates 2026-10-01. + +## In plain language + +Offband's radio presets now come from two files in the config repo: MeshCore's suggested settings (Liam Cottle's list, mirrored daily and credited) and our own overlay, which wins when both name the same preset. Regional entries like Philly Mesh, Arizona and the OKI 500 kHz test are there, grouped by region and labelled by source. Changing a preset is now an edit to `offband.json`, not an app release. The same presets can be applied to Companion and Observer radios, and to Repeaters, Room Servers and Sensors over stock admin commands, including a temporary option that reverts on its own. + +The owner tested the combined build on his phone and Windows and approved it. + +## What was delivered + +| Epic | PR | What | +|---|---|---| +| A (#721) | config-profiles#3, merged | `radio-presets/offband.json` (33 presets), `meshcore-upstream.json` (mirror with credit), validator, workflow (validate on change, mirror daily) | +| B (#726) | #744 | Preset model and parsers, bundled copies, refresh with last-good cache, merge (ours over Liam's), grouped picker with source labels, Companion/Observer apply incl. path hash (cmd 61), About credit, #747 (USA radio shown as Canada) | +| C (#733) | #746 | Picker on remote settings, `set radio`, `tempradio` (sent last, 1 to 35791 minutes, default 1440), `set path.hash.mode`, Sensor admin entry (#745) | +| D (#737) | this PR | D1 owner test (#738), this document (#739), plan amendment, #748 tests | + +## Evidence + +- **Owner D1 (#738):** approved. In his words, in substance: it matches what he expected; he sees Philly, USA and the MeshCore entries; it is clean and reads well; the source labels are understandable; grouping by region is an improvement. His notes cover the preset picker; the per-node-type checklist items were not itemized in his reply. +- **Build tested:** local `throwaway/647-combined` @ `e1d30482`, containing #744 `04025cb0` and #746 `9c17f8a5`, release-signed, installed on the S25 FE and Windows. +- **Automated, same build:** analyze clean, 1087 tests pass, live preset test passes against config-profiles `main`. +- **CI:** every check green on #744 and #746 at those heads. +- **Config repo:** both files return HTTP 200 on `main`; validate passed on the merge push; the dispatched mirror ran end to end (no commit, Liam's list unchanged). +- **Acceptance bar (PLAN §6):** tests cover coding rates, path hash bytes to mode, `tempradio` ordering and its cap, and an overlay edit reaching the app with no release. + +## What went wrong + +- **The plan had a gap.** D1 checked preset refresh, but Epic A's merge was a stop at the end of the chain, so the files 404'd on `main` and that check could not pass. The owner was handed builds showing "Couldn't update presets. Showing the saved list." twice, and a third untestable handoff. Fixed by merging Epic A before D1 (PLAN §10). +- **No test touched the real dependency.** Every preset test faked the network, so the 404 passed all tests and CI. Fixed by #748: a live test in the default suite, so CI now fails if the files go missing. +- **A test build was installed mid-chain** on the owner's phone and Windows, replacing his working build. Both were restored to his earlier build until the chain was done. Canon now says an install is testing and happens once, at the end. +- **ADB diagnosis** blamed his phone before reading adb's own log; the real cause was a wedged USB link (`write terminated: Input/output error`), cleared by reconnecting. + +## What's left + +- Merge #744, then #746, then this PR, in that order (plan grant, budget 3). +- Owner sign-off on Epic verifications (#725 for A) and Epic closure. +- Remove the `throwaway/647-combined` worktree after merge. diff --git a/docs/initiatives/standalone/647-mesh500-presets/PLAN.md b/docs/initiatives/standalone/647-mesh500-presets/PLAN.md new file mode 100644 index 00000000..32b2cc00 --- /dev/null +++ b/docs/initiatives/standalone/647-mesh500-presets/PLAN.md @@ -0,0 +1,168 @@ +# Feature PLAN: MESH 500 regional preset system + +| | | +|---|---| +| **Feature** | [#647](https://github.com/OffbandMesh/meshcore-client/issues/647) · Citadel `meshcore-open-mli` | +| **Serves** | No parent Initiative; a standalone Feature. | +| **Status** | Draft. Approved when this PR merges. | +| **Owner** | @Strycher | +| **Last updated** | 2026-10-01 | + +## At a glance + +- **What:** one radio preset list in the app, with regional defaults plus local meshes (Arizona, SoCal, OKI, Philly). Pick a preset and apply it to a Companion, Observer, Repeater, Room Server or Sensor. +- **Why now:** our presets are a hardcoded list that can only change with an app release, it has no 500 kHz option, and several of its values are wrong. Regions change their settings: Philly has moved frequency, and OKI's isn't settled. +- **How:** four Epics, in order: + - A: preset files in `config-profiles`; + - B: the catalog and picker in the app, applied to Companion and Observer; + - C: applying presets to remote nodes; + - D: integration testing. +- **Done when:** + - Editing a preset in `config-profiles` reaches users on their next refresh, with no app release (within about five minutes, GitHub's cache). + - Every node type can apply a preset using stock firmware commands only. + +## 1. Diagnosis + +Verified 2026-09-23 to 2026-10-01. Full write-ups are on #647 and #722. + +| # | Finding | Evidence | Effect | +|---|---|---|---| +| 1 | Presets are a hardcoded Dart list with no update path | `lib/models/radio_settings.dart:63` (46 entries) | Any preset change needs an app release | +| 2 | Our coding rates are wrong for several regions | zjs81#72 dropped the CR column and set all to CR 5; Liam's registry (archived Oct 2025 by openhop, live today) has EU/UK Narrow CR8, Switzerland CR8, Portugal 433 CR6, Australia Narrow CR7 | Users picking those presets get the wrong CR | +| 3 | No preset can carry path hash | `RadioSettings` has no field (`radio_settings.dart:47-52`); Liam's list publishes it in bytes on 8 entries | Presets that need path hash leave it unset | +| 4 | Liam's list is the de facto community source | Stock app (`app.meshcore.nz`) fetches `api.meshcore.nz/api/v1/config` and bundles nothing; official map and config tools use it; CORS is open | It's the base we build on, with credit | +| 5 | Liam's list lacks entries our users need | Live list: 26 entries, none at 500 kHz, no Philly, OKI, Arizona or Russia | We need our own overlay | +| 6 | Stock firmware has no preset list | `meshcore-dev/MeshCore` `e9412598`: only one build default (869.618 / 62.5 / SF8) | Presets are a client concern; no firmware work needed | +| 7 | Every apply path exists in stock firmware | Companion cmd 11 + cmd 61; CLI `set radio`, `tempradio`, `set path.hash.mode` (upstream `CommonCLI.cpp`) | No Offband-specific codes | +| 8 | Path hash is published in bytes; firmware takes a zero-based mode | `sendFlood(..., path_hash_mode + 1)`; 2 bytes = mode 1 | A straight copy of the number puts the node off the mesh | +| 9 | `tempradio` retunes 2 s after replying; its timer overflows past ~35,791 minutes | `simple_repeater/MyMesh.cpp:1026-1034` | Must be sent last in a save, and the duration capped | +| 10 | The app has no admin path for Sensors | A Sensor contact only opens a chat (`contacts_screen.dart:981-987`); stock sensor firmware does run the shared CLI (`SensorMesh.cpp:450`) | Sensor apply needs an admin entry point | +| 11 | Room Servers already share the repeater admin screens | `contacts_screen.dart:1063` opens `RepeaterHubScreen` for room management | Repeater work covers Room Servers | + +## 2. Scope + +**In:** +- An Offband overlay preset file and a CI mirror of Liam's list in `OffbandMesh/config-profiles` (owner decision on #650 and #722). +- In the app: bundled snapshots of both, refresh, merge (ours over Liam's), last-good cache, a grouped picker with source labels, and credits. +- Applying presets to Companion, Observer, Repeater, Room Server and Sensor through stock commands only. +- A Temporary (`tempradio`) option for remote nodes (#662). + +**Out:** +- Firmware changes. +- Changing any non-US preset beyond matching Liam's published values. +- Regulatory or legal advice. + +## 3. Epics + +Each Epic ends with a verification task and gets one PR. Issue numbers are already filed on board #2. + +### Epic A: preset sources in config-profiles (#721) + +Code lands in `OffbandMesh/config-profiles`. + +| Task | Pts | +|---|---| +| **A1 · Overlay file + schema (#722):** OKI test, Philly (current values not yet known; to be found from a Philly Mesh source, or the chain stops), Arizona SF9/CR8, Russia, Off-Grid. Schema documents add, change and retire. Checked by a validation script. | 3 | +| **A2 · CI mirror of Liam's list (#723):** scheduled job. It runs A1's validation script on the fetched data **before** committing; if validation fails, the run fails and nothing is committed. Commits directly only on change. Checked by a manual run, a no-change rerun, and a simulated bad response. | 3 | +| **A3 · README credit (#724):** Liam Cottle / MeshCore, and the precedence rules. | 1 | +| **A4 · Epic verification (#725)** | 1 | + +### Epic B: in-app catalog and picker, Companion and Observer (#726) + +| Task | Pts | +|---|---| +| **B1 · Preset model (#727):** replaces the hardcoded list. Unit tests. | 3 | +| **B1b · Path hash field and bytes-to-mode conversion (#649):** tested conversion. | 2 | +| **B2 · Bundled snapshots, refresh, merge, last-good cache (#728, closes #648):** tests for offline, refresh, failure fallback, precedence, an edit with no release, and malformed entries. | 4 | +| **B3 · Grouped picker with source labels (#729):** widget test; preset match on load still works. | 3 | +| **B4 · Apply to Companion and Observer (#730):** cmd 11, TX power, cmd 61; client repeat preserved. Tests. | 3 | +| **B5 · Credits on About (#731)** | 1 | +| **B6 · Epic verification (#732)** | 1 | + +### Epic C: apply to remote nodes (#733) + +| Task | Pts | +|---|---| +| **C1 · Picker on the remote-node settings screen (#734):** Repeater and Room Server share it. | 3 | +| **C2 · Temporary checkbox (#662):** `tempradio`, sent last, duration capped. Tests. | 3 | +| **C3 · Path hash via `set path.hash.mode` (#735):** tests. | 2 | +| **C5 · Sensor admin entry point (new issue at merge):** log in to a Sensor and reach the same settings screen (owner choice 1: in scope). | 3 | +| **C4 · Epic verification (#736)** | 1 | + +### Epic D: integration testing (#737) + +| Task | Pts | +|---|---| +| **D1 · End-to-end on every node type (#738):** owner hardware. | 3 | +| **D2 · OUTCOMES.md (#739)** | 1 | + +## 4. Order and dependencies + +- A, B, C, D in that order. Each Epic's verification task blocks the next Epic (wired in Citadel). +- B needs A's file format. C reuses B's catalog and conversion. D needs all three. +- Within B: B1, B1b, B2, B3 and B4 all touch `radio_settings.dart` and `settings_screen.dart`, so they run in sequence. +- Within C: C1, C2, C3 and C5 all touch `repeater_settings_screen.dart` (C5 also `contacts_screen.dart`), so they run in sequence. +- Because merges wait until the end, C's branch is stacked on B's, and D's on C's. A fix found in B during D's hardware testing gets rebased up through C. + +## 5. Grants and authorization + +| Term | Proposed | Why | +|---|---|---| +| **What merging this plan authorizes** | Running Epics B, C and D in order without stopping between them: code, tests, builds, and one PR per Epic as it finishes. | The owner asked for the chain to run unattended unless a decision or fault needs him. | +| **Merges** | Deferred to the end of the chain, in order B, C, D, after the owner's hardware review in D. | Owner direction: merges come at the end. | +| **Epic verification** | Owner mode. My verification task (analyze, full test suite, format, em-dash check, Windows and APK builds) closes each Epic and lets the chain continue. The owner's approval of each PR happens at the end, before merge. | Hardware testing is the owner's gate; consolidating it at D avoids pausing the chain. | +| **Owner steps during the run** | None, unless a stop below fires. At the end: hardware review (D1), then approve the PRs. | | +| **Stops** | A new decision; a fault I can't fix; Philly's current values if no public source; Epic A's PR, because it's in `config-profiles` and outside this grant (needs a separate `dw-approve merge`). | Grants cover this repo only. | +| **Flash** | None. | No firmware is flashed. | + +```grant-terms +{ + "epic_chain": [726, 733, 737], + "chain": true, + "verification": { "mode": "owner" }, + "merge": { "budget": 3, "basis": "One PR per Epic in this repo: B (#726), C (#733), D (#737, OUTCOMES.md). Epic A merges in config-profiles, outside this grant." }, + "flash": null, + "reset": null, + "expires_after_hours": 168 +} +``` + +`expires_after_hours` basis: A plus B plus C is roughly four to five working sessions of build time, plus the owner's end-of-chain hardware review. 168 hours (the maximum) leaves room for his day job. + +## 6. Verification + +- **Named command (this repo):** `flutter analyze` with CI flags, `dart format --set-exit-if-changed`, the em-dash check, and `flutter test` (full suite). Every Epic PR shows the output. +- **Named command (config-profiles):** the A1 validation script over both files, plus one mirror job run. +- **Acceptance bar:** each finding in section 1 has a test that would have caught it. Most important: wrong CR values, path hash bytes-to-mode, `tempradio` ordering and cap, and an overlay edit reaching the app with no release. + +## 7. Done when + +- The picker shows Liam's presets plus ours, grouped, with sources and credits, and works offline. +- An overlay edit in `config-profiles` reaches the app on its next refresh with no new build, within about five minutes (GitHub's raw-file cache, #452). +- Companion, Observer, Repeater, Room Server and Sensor can each apply a preset with stock commands, including path hash and the Temporary option. +- The owner signs off D1, and `OUTCOMES.md` is approved. + +## 8. Your choices + +| # | Question | Option A | Option B | Rec. | Your choice | +|---|---|---|---|---|---| +| 1 | Sensors have no admin path in the app today | Add one (C5): log in, reuse the repeater settings screen | Drop Sensor from this Feature and file it separately | ⭐ A | **A**: add the Sensor admin path (2026-10-01) | +| 2 | When does your hardware testing happen? | Once, at Epic D, before any merge; the chain runs straight through. Risk: a hardware fault in B is found only after C is built on it, so the rework is bigger. | After each Epic, before the next starts. Catches faults earlier, but the chain pauses for you each time. | ⭐ A (your stated direction) | **A**: at the end; the chain does not stop between Epics (2026-10-01) | + +## 9. Carried-in work + +| Item | Goes to | +|---|---| +| #648 (hardcoded list, no update path) | B2 | +| #649 (preset path hash) | B1b | +| #662 (Temporary checkbox) | C2 | +| #661 (OKI stopgap, closed) | A1 | +| #650 (source decision, closed) | Decisions recorded; this plan implements them | +| Sensor admin path (finding 10) | C5, new issue when this plan merges | + +## 10. Amendments + +| Date | Change | Why | +|---|---|---| +| 2026-10-01 | Epic A (config-profiles#3) merged **before** D1, not at the end. The owner minted its grant separately. App PRs still merge after D1. | Gap in this plan: D1 checks preset refresh, which can't pass until the files are on config-profiles `main`. Stopping for A only at the end made D1 untestable. | +| 2026-10-01 | Added #748: a live test that refreshes from the real config-profiles URLs in CI, plus tests that each preset error message is absent under ideal conditions. | Owner requirement after "Couldn't update presets" reached him on two test builds. No build goes to him while that error still appears under ideal conditions. | diff --git a/docs/initiatives/standalone/750-contact-naming/PLAN.md b/docs/initiatives/standalone/750-contact-naming/PLAN.md new file mode 100644 index 00000000..df6d9d8e --- /dev/null +++ b/docs/initiatives/standalone/750-contact-naming/PLAN.md @@ -0,0 +1,220 @@ +# PLAN: contact naming, and what a name does not prove + +| | | +|---|---| +| **Covers** | [#750](https://github.com/OffbandMesh/meshcore-client/issues/750) Epic · Citadel `meshcore-open-b5l` · [#751](https://github.com/OffbandMesh/meshcore-client/issues/751) docs · Citadel `meshcore-open-le5` | +| **Serves** | Feature [#609](https://github.com/OffbandMesh/meshcore-client/issues/609) Contacts. #609 has **no** plan of record; this plan covers the naming slice only and does not retroactively cover its delivered epics (#610, #611, #619). | +| **Status** | Draft. Approved when this PR merges. | +| **Owner** | @Strycher | +| **Agent** | HazyCove (session db2d6bf0) | +| **Last updated** | 2026-10-01 | + +## At a glance + +When this is done you can give any contact a name of your own, the way stock MeshCore's CUSTOM NAME field works, and it sticks. Adverts keep correcting what the node calls itself underneath, so accuracy improves without your label ever moving. Where the two differ, you can see both. + +And the thing a client cannot fix is written down plainly instead of implied: a display name on the mesh is not unique, not owned, and not proof of who you are talking to. The key is the identity. The docs, the release notes and one short line in the app say so, and say what to check instead. + +## 1. Diagnosis + +| # | Finding | Evidence | Effect | +|---|---|---|---| +| 1 | Offband cannot rename a contact at all | No name field in `contact_settings_dialog.dart`; no contact edit screen; `git log -S renameContact -- lib/` returns nothing | Stock-parity gap. Stock has CUSTOM NAME per node | +| 2 | Firmware cannot hold a per-contact custom name | `ContactInfo.h:10` is a single `char name[32]`. `IdentityStore`'s `display_name` is the **device's own** name, not a per-contact override. No custom-name concept anywhere in firmware | A custom name is necessarily client-side, matching the owner's read that stock keeps the original underneath | +| 3 | An inbound advert overwrites the stored name | `meshcore_connector.dart:9122` → `name: hasName ? name : existing.name` | Accuracy is good, but the client can never hold a name the user chose; the next advert takes it back | +| 4 | An advertised name **is** cryptographically bound to the key | Firmware signs `pub_key‖timestamp‖app_data` and rejects a forged signature outright: `meshcore-firmware/src/Mesh.cpp:279-287` | Only the private-key holder can advertise a name for that key | +| 5 | A contact-card name is bound to **nothing** | `` is plain unsigned channel text (#610) | Anyone can pair any name with any key they do not own. This is #645 | +| 6 | Display names are not unique and cannot be made so | No registry exists. Setting your own radio's name to another operator's name produces correctly signed, legitimate traffic | Unpreventable. A property to document, not a defect to fix. See §6 | +| 7 | Renames do not propagate | Adverts are not immediate and may never come (owner, 2026-10-01) | Everyone else keeps a stale name indefinitely, with no way to correct it locally | +| 8 | The name surface is read-heavy and write-light | **85** display reads of a contact name in `lib/`; **11** `Contact(...)` constructions passing `name:`; **6** `copyWith(... name: ...)`; **5** `buildUpdateContactPathFrame` call sites | Decides the architecture, §2. A loose grep suggested 114 constructions; the measured figure is 11, and planning on 114 would have mis-sized this epic | +| 9 | Per-contact settings already have a home | `contact_settings_store.dart` keys by pubkey hex (`contact_cyr2lat_`) | New prefix, proven pattern, no new storage design | +| 10 | The unverified state is already rendered | #630's badge separates `advertVerified` from `keyOnly` (`contact_verification_badge.dart:50-57`) | This epic gives that badge real data instead of inferring from `lastSeen` | +| 11 | `resolveContactsByName` already exists | `meshcore_connector.dart:1228`, built for #468; returns every identity behind a claimed name and never picks a winner | Reusable for #645's collision check, with a cost constraint. See §5 | + +## 2. Architecture + +The decision is driven by finding 8: **85 reads, 22 writes.** Protect the many, make the few explicit. + +### Decisions + +| Decision | Why | +|---|---| +| `Contact.name` becomes a **getter**: `customName ?? receivedName` | All 85 display reads stay correct and untouched. A future read site cannot forget, because reading `.name` is already right | +| The received name is called **`receivedName`**, not `advertName` | Writing the test matrix caught this. A contact-card name is **not** advertised (finding 5), so calling the field `advertName` would make it lie for every card-added contact, and #645's honest signal would be built on a false premise | +| "Is this name key-bound?" is answered by the **existing** `isAdvertVerified` | `contact.dart:270` already derives it from `lastSeen`, and #630 already renders it. No third field, no new concept, and the provenance question stays in one place | +| The constructor and `copyWith` take **`receivedName`**, not `name` | Renaming the write parameter turns all 11 constructions and 6 `copyWith` calls into **compile errors**. The compiler enumerates them; nothing is missed silently | +| `customName` lives on `Contact` and persists in `contact_settings_store` | Survives `copyWith`, so no re-application is needed at the four radio-sync points (6672, 6690, 6780, 6791) | +| An empty or whitespace-only custom name counts as **unset** | Otherwise a user who clears the field by deleting its text gets a blank display name with no way back | +| The **radio always receives `receivedName`** | The radio's contact table is the shared record of what a node calls itself. The client holds the user's label. §3 Task 2 covers this, because it is the one hole the compiler cannot see | +| The custom name is **never** sent to the radio | Finding 2: there is nowhere to put it, and writing it would corrupt the shared record | + +### Alternatives considered but not chosen + +- **Add `displayName` and migrate the 85 read sites.** Rejected: the failure mode is silent and permanent. A missed site, or any future site that reaches for `.name`, shows the advertised name instead of the user's and nothing complains. +- **Resolve the custom name at render time from a connector map, leaving `Contact` untouched.** Rejected: it still needs all 85 reads to call the resolver, so it has the silent-failure problem plus a second lookup path. +- **Store the custom name on the radio.** Not possible, finding 2. + +### The one hole, named + +The 5 `buildUpdateContactPathFrame` call sites read `.name` today. Under the chosen design `.name` still compiles there, so the compiler will **not** flag them, and a miss would write the user's private label into the radio's contact table. They are: `meshcore_connector.dart` 4048, 4114, 4531, 4562, and `stock_config_import_service.dart:303`. Task 2 changes all five and adds a test that fails if a frame is built with a custom name, so the hole is closed by a test rather than by care. + +## 3. Epic #750: tasks + +| Task | What | Pts | +|---|---|---| +| **750.1 · Model and storage** | `receivedName` (required) + `customName` (nullable) on `Contact`; `name` becomes the getter; constructor and `copyWith` renamed; `contact_store` migration reads a legacy `name` into `receivedName`; `contact_settings_store` persists `customName` by pubkey hex. Tests T1 to T9 and T31 | 4 | +| **750.2 · Radio boundary** | All 5 `buildUpdateContactPathFrame` sites send `receivedName`. Tests T10 to T14, including the source guard | 3 | +| **750.3 · Advert path** | `meshcore_connector.dart:9122` writes `receivedName` always; the display name follows from the getter with no extra branch. Tests T15 to T22 | 3 | +| **750.4 · Contacts UI** | Set, edit and clear a custom name from the contacts screen; show the received name wherever it differs, so the user can see what the node calls itself. New l10n strings in `app_en.arb`. Tests T23 to T30 | 3 | +| **750.5 · Epic verification** | Owner, on hardware, Windows and Android. §7 | 1 | + +**Not in this epic:** #645's collision warning and the verify-the-key advisory. #645 is already blocked-by #750 and lands after, because the check must match the display name and the advisory should reference real advertised-name data. + +## 4. Automated tests + +Every behaviour below gets a **positive** test (it does the right thing) and a **negative** test (it does not do the wrong thing). The negatives are the ones that catch a future regression, because a positive test keeps passing while a new code path quietly breaks the guarantee next to it. Nothing in this epic is done on positives alone. + +All of these run in CI through the existing `analyze` job (`flutter test`), so a regression fails the build rather than waiting for someone to notice. + +### 750.1 Model and storage · `test/models/contact_naming_test.dart`, `test/storage/contact_settings_store_test.dart` + +| # | +/- | Test | +|---|---|---| +| T1 | **+** | `name` returns `customName` when one is set | +| T2 | **-** | `name` returns `receivedName` when `customName` is null, and the custom name does not leak in | +| T3 | **-** | An empty-string `customName` is treated as unset, so `name` falls back rather than returning `""` | +| T4 | **-** | A whitespace-only `customName` is treated as unset, same reason | +| T5 | **+** | `copyWith(receivedName:)` changes the received name and leaves `customName` intact | +| T6 | **-** | `copyWith(receivedName:)` does not change what `name` returns while a custom name is set | +| T7 | **+** | A legacy stored contact with only a `name` key migrates into `receivedName` | +| T8 | **-** | That migration leaves `customName` **null**. If it populated it, every existing contact would silently become "renamed" and adverts would stop updating any of them | +| T9 | **+/-** | Custom name round-trips through `contact_settings_store`; clearing removes it; a load for an unknown pubkey returns **null**, not `""`, and does not throw | + +### 750.2 Radio boundary · `test/connector/contact_frame_naming_test.dart` + +| # | +/- | Test | +|---|---|---| +| T10 | **+** | With a custom name set, `buildUpdateContactPathFrame` carries the **received** name | +| T11 | **-** | The built frame bytes do not contain the custom name anywhere. This is the test that stops a private label reaching the shared contact table | +| T12 | **+** | With no custom name, the frame is byte-identical to today's, so this change is behaviour-neutral for every existing path | +| T13 | **+** | `addContactByKey` on a card stub still sends the card's name, since a stub's received name is the card name | +| T14 | **-** | **Source guard:** exactly 5 `buildUpdateContactPathFrame` call sites exist and none passes `.name`. The test reads the source and fails if a sixth appears or an existing one regresses. The compiler cannot see this hole (§2), so a test holds it | + +### 750.3 Advert path · `test/connector/advert_name_update_test.dart` + +| # | +/- | Test | +|---|---|---| +| T15 | **+** | An advert carrying a name updates `receivedName` | +| T16 | **-** | That same advert does not change what `name` returns while a custom name is set. This is the whole point of the epic | +| T17 | **+** | Clearing the custom name afterwards reveals the newly advertised name, not the stale one | +| T18 | **-** | An advert with no name (`hasName` false) does not null or clobber `receivedName` | +| T19 | **-** | An advert does not write, alter or clear `customName` by any path | +| T20 | **+** | A card-added contact with no advert yet reports `isAdvertVerified == false` and displays the card's name | +| T21 | **-** | That contact is not reported verified, so #630's badge cannot show green on an unsigned name | +| T22 | **+** | A node renamed on its own radio whose advert never arrived still displays the user's custom name, and the stale received name remains available to show beside it | + +### 750.4 Contacts UI · `test/screens/contact_rename_test.dart` + +| # | +/- | Test | +|---|---|---| +| T23 | **+** | Setting a custom name updates the contact tile | +| T24 | **+** | Clearing it restores the received name in the tile | +| T25 | **+** | Where the two differ, both are visible, so the user can see what the node calls itself | +| T26 | **-** | Where they are the same, the received name is not shown twice | +| T27 | **+/-** | Error surfacing, per the owner's standing requirement: the over-length message appears when the field exceeds the UI maximum, and is **absent** when the input is valid | +| T28 | **-** | A custom name containing CJK, emoji or a ZWJ sequence is stored and displayed intact. It never crosses the wire, so #636's grapheme truncation must not be applied to it | +| T29 | **-** | Saving the dialog with an **empty** field writes `null` to the store, not `""`. Without this the display looks right (T3 makes the getter fall back) while the stored data is wrong, and the dialog can never truly unset a name through its primary save action | +| T30 | **-** | Saving the dialog with a **whitespace-only** field does the same | + +T29 and T30 come from the pre-PR adversarial review. T3 and T4 prove the *getter* tolerates an empty custom name; nothing proved the *UI* never writes one, and a clear button passing (T24) would have masked a broken save path. + +### 750.1 addendum: the fallback the rename could drop + +| # | +/- | Test | +|---|---|---| +| T31 | **-** | A legacy stored contact whose `name` key is **missing or null** migrates to `receivedName == 'Unknown'`, preserving the existing fallback at `contact_store.dart:145` (`json['name'] as String? ?? 'Unknown'`) | + +The review raised this as a crash risk. That premise is wrong: the fallback already exists and predates this epic, so there is no crash and no data-loss path. The real risk is narrower and worth a test anyway. Moving the deserializer from `name:` to `receivedName:` is exactly the kind of edit that drops a trailing `?? 'Unknown'` without anyone noticing, and the result would be a crash on load for any user holding such a row. T31 pins it. + +### Regression guarantee + +T8, T11, T14, T16, T19, T21, T29, T30 and T31 exist purely to fail if someone later breaks a guarantee this epic makes. They assert **absence**, which is what a regression actually looks like. T14 is the only source-reading test, and it is deliberate: it guards the one hole the type system cannot see. + +## 5. `resolveContactsByName`, and its cost + +It matches on `c.name`. Under the chosen design that keeps meaning **what the user reads**, which is the string any deception operates on, so #645's collision check needs **no resolver change**. Under the rejected `displayName` design it would have silently matched the advertised name instead. That is a second reason the chosen design wins. + +**[hypothesis: cost model read from the code, not measured. 750.1 measures it before 750.4 ships.]** + +It spreads `contacts` + `discoveredContacts` (both getters allocate a fresh list) and calls `trim().toLowerCase()` per element, allocating a string each. At the owner's reported scale of roughly 350 contacts (#188) plus discovered nodes, that is on the order of 700 allocations per call. + +| Call site | Frequency | Verdict | +|---|---|---| +| A dialog, on open | Once per user action | Fine. Sub-millisecond, invisible | +| Any list-rendered widget via `context.select` | Re-runs on **every** `notifyListeners()`; the connector notifies on every received packet | Not acceptable. 700 allocations × visible widgets × notifications per second | + +So any name-collision check belongs in a **dialog**, never in a tile or chip. `add_contact_by_key_dialog.dart:132` already holds the connector, so this needs no connector change and stays clear of the contact-sync work in P0 #660 / #668. A list-level signal would need a maintained `Map>` index keyed by lowercased display name, not a per-build scan; out of scope here, to be filed when a design calls for it. + +## 6. #751: documenting what cannot be fixed + +Finding 6 is permanent. The client's obligation is to stop presenting a name as an identity and to make the key reachable at the moment of decision. It is not to prevent collisions, which it cannot. + +Owner, 2026-10-01: *"Without an official registry enforcing globally unique display names, this is an unpreventable consequence."* + +| Surface | Content | +|---|---| +| `CHANGELOG.md` | Short entry, user-facing voice, under the release that ships it | +| Release notes | The same text, so it reaches people who never open the repo | +| Docs site (`OffbandMesh/offband-site`) | The full explanation: why names are not unique, what a signature does and does not prove, how to confirm a key out of band once, what the #630 badge states mean | +| In-app | One short advisory at the point a contact is added, as an l10n string. Placement rides with 750.4, since the honest wording references the advertised name | + +**Wording constraints, binding:** + +- Do **not** call this an attack or a vulnerability. It is how a registry-free mesh behaves. Overstating it is the same dishonesty as hiding it, and reads as alarmism to operators who already know. +- Do **not** imply Offband is weaker than stock. Stock has no name-key binding either; the verification badge is something Offband adds. +- Lead with what the user should **do**, which is confirm a key out of band with the person once, not with what could go wrong. +- No em-dashes. +- The docs-site page is public, so the draft is reviewed before it is published. + +## 7. Verification + +**750.5, owner, on hardware, Windows and Android:** + +1. Rename a contact. The new name shows everywhere that contact appears. +2. Let that contact advert. The name does **not** change back. +3. Clear the custom name. The advertised name returns. +4. Add a contact from a card, with no advert yet. It reads unverified, and shows the card's name. +5. Let that contact advert. It becomes verified, and the advertised name is now visible as distinct from any custom name set. +6. A contact renamed on its own radio, whose advert has not reached you, still shows your name, and shows the stale advertised name where the two differ. + +**Automated, in CI:** the full T1 to T31 matrix in §4, positives and negatives, including the radio-boundary source guard T14. + +**#751:** the owner reads the docs-site draft before it is published. The in-app string is checked in 750.5 step 4. + +## 8. What the owner has to do + +One step, at the end: run the Windows build and the Android build and walk §7. Everything else, including the T1 to T31 matrix and the measurement in §5, is run by the session and brought to him as evidence. + +## 9. Risks + +| Risk | Handling | +|---|---| +| A custom name reaches the radio and corrupts the shared record | §2 "the one hole". Five named sites, changed in 750.2, closed by a test, not by care | +| `meshcore_connector.dart` is OrangeDog's file for P0 #660 / #668 | 750.1 and 750.3 touch it. Announce on Agent Mail before starting, and carry the rebase rather than asking anyone to work around it | +| A `contact_store` migration loses names | Nullable, additive migration: a legacy `name` is read into `receivedName`, `customName` starts null. T7 and T8 cover both halves, and T8 is the negative that catches the worse failure: a migration that populated `customName` would silently mark every existing contact as renamed and stop adverts updating any of them. Data safety is not optional | +| The docs wording overstates the risk | §6 constraints, and the owner reviews the public draft | + +```grant-terms +{ + "epic_chain": [750], + "chain": true, + "verification": { "mode": "owner" }, + "merge": { "budget": 2, "basis": "One PR for Epic #750 (tasks 750.1-750.5, one branch, merged after owner verification), and one PR for the #751 documentation. The docs-site page merges in OffbandMesh/offband-site, outside this grant." }, + "flash": null, + "reset": null, + "expires_after_hours": 168 +} +``` + +--- +*Agent: HazyCove (session db2d6bf0).* diff --git a/docs/initiatives/standalone/755-fake-radio/PLAN.md b/docs/initiatives/standalone/755-fake-radio/PLAN.md new file mode 100644 index 00000000..170734c4 --- /dev/null +++ b/docs/initiatives/standalone/755-fake-radio/PLAN.md @@ -0,0 +1,197 @@ +# Feature PLAN: fake radio for automated testing in CI + +| | | +|---|---| +| **Feature** | [#755](https://github.com/OffbandMesh/meshcore-client/issues/755) · Citadel `meshcore-open-6o3` | +| **Serves** | No parent Initiative; a standalone Feature. Absorbs #601 from Epic #598. Depends on OffbandMesh/meshcore-firmware#1318. | +| **Status** | Draft. Approved when this PR merges. | +| **Owner** | @Strycher | +| **Last updated** | 2026-10-02 | + +## At a glance + +- **What:** a software MeshCore companion radio, written in Dart, that the real client connects to with no hardware. It plays either **stock MeshCore** or **Offband** firmware, answers the same frames a real radio does from a seeded, deterministic state, and can play scripted faults. +- **Why now:** no test can take the client through a real connect, sync, send or settings change. Everything past "connected" is tested by the owner, by hand, on hardware. The #647 remote preset commands shipped with no on-air test for exactly this reason. +- **How it stays in sync:** the firmware publishes a machine-readable protocol manifest at every tag and merge (firmware#1318). The fake radio's profiles load it, and client CI fails when the client disagrees with it. Captured traces from a real Offband radio and a real stock radio check behavior. +- **How:** four Epics, in order: + - A: the fake radio core, both profiles, the manifest check, in-process and over TCP; + - B: messaging, radio settings, remote nodes, faults, and trace replay; + - C: test suites that run in CI under both profiles, plus a runner for manual use; + - D: integration testing, including capturing the real-radio traces. +- **Done when:** + - Every PR's CI runs connect, sync, messaging and preset flows (including on a repeater, room server and sensor) against the fake radio, under both the stock and Offband profiles, with no hardware. + - Client CI fails when the client's protocol constants disagree with the firmware's published manifest. + - The owner can start the fake radio on his PC and connect the Windows app to it over TCP. + +## 1. Diagnosis + +Verified 2026-10-02 against `dev` @ `0fc407d4` and firmware `53951759`. + +| # | Finding | Evidence | Effect | +|---|---|---|---| +| 1 | Nothing past "connected" can be tested without a radio | `scanner_screen.dart:66` routes to the channel UI only on `connected`; #598 diagnosis | Connect, sync and messaging regressions reach users before anyone sees them | +| 2 | No test drives the protocol end to end | The only TCP tests are the transport (`tcp_transport_service_native_test.dart`, raw sockets) and `tcp_flow_test.dart`, which stubs `connectTcp` out entirely | The connector's handshake, sync and send logic (9,368 lines in `meshcore_connector.dart`) has no end-to-end test | +| 3 | The fake radio was planned, never built | #601 has no branch, comments or code | Nothing to build on but a plan | +| 4 | The connector already has an in-process seam | `handleFrameForTest` and `sendFrameOverrideForTest` (`meshcore_connector.dart:3112-3117`) | A fake radio can plug in with no sockets, so widget tests stay fast and deterministic | +| 5 | The TCP path needs no app changes, but uses serial framing | `connectTcp` (`meshcore_connector.dart:2295`); the transport wraps frames with `wrapUsbSerialTxFrame` (start `0x3c`) and decodes with `UsbSerialFrameDecoder` (start `0x3e`) (`tcp_transport_service_native.dart:11,92`) | The fake's TCP server must speak that framing | +| 6 | The handshake is a known, finite set | On connect the client sends `DEVICE_QUERY`, `APP_START`, `GET_CUSTOM_VARS`, battery, `GET_AUTO_ADD_CONFIG`, then contacts, channels and message sync (`meshcore_connector.dart:3592-3600`, `3712`); 53 frame builders, 34 response and push codes handled | The core can be built against a fixed list | +| 7 | Stock and Offband differ in what the radio reports | The client gates every Offband feature on the reported capability bytes (`_offbandCaps`, `_offbandCaps2`, `meshcore_connector.dart:370`) and the version code; the bits are defined in `OffbandConfigProtocol.h:275-299`; stock firmware reports none | A fake radio can play either by changing what it reports and which Offband commands it answers | +| 8 | The firmware publishes no machine-readable contract | The caps and `FIRMWARE_VER_CODE` registry is a prose comment table (firmware#514) | Today any copy of the protocol drifts silently; firmware#1318 fixes this at the source | +| 9 | Firmware version reporting is inconsistent | firmware#873 (`ver` vs `version` disagree), #958, #1277, #1311 | A test of the reported version catches this; firmware#1318 adds the firmware-side check | +| 10 | The firmware is the reference for every reply | `examples/companion_radio/MyMesh.cpp`, `handleCmdFrame` at line 1964; remote CLI in the shared `CommonCLI` | Each fake reply is copied from a named firmware function, not guessed | +| 11 | Remote-node presets are untested on air | #738 addendum: owner reviewed the screen, never applied a preset to a real node | The fake radio covers `set radio`, `tempradio` and `set path.hash.mode` in CI | +| 12 | No radio is on stock firmware today | Owner, 2026-10-02: one can be flashed | The stock trace capture needs one radio flashed to stock (section 5, Flash) | +| 13 | #598 scoped its bench out of CI | #598 body, owner 2026-08-24 | Reversed for the fake radio only (owner, 2026-10-02, logged on #598) | + +## 2. Scope + +**In:** +- A fake companion radio in Dart: frame codec, command dispatch, seeded state, deterministic clock. +- Two firmware profiles, stock and Offband, built from the firmware's published protocol manifests. +- A client CI check that the client's protocol constants match the manifest. +- Two ways to connect: in-process (through the connector's test seam) and a TCP loopback server. +- Messaging, acks, incoming messages, channels, radio settings, and repeater, room server and sensor admin (login and CLI) over the mesh. +- Scripted faults: dropped acks, error replies, disconnect mid-sync, slow replies. +- Trace replay: frames recorded from a real Offband radio and a real stock radio, which the fake must reproduce. +- Test suites in the default `flutter test`, so CI runs them on every PR. +- A standalone runner (`dart run tool/fake_radio.dart`) so the desktop app can connect over TCP. + +**Out:** +- The firmware side of the manifest and the reported-version check: firmware#1318. +- BLE and USB serial fakes. TCP and in-process cover the protocol; the transports already have their own tests. +- Simulating RF, propagation or multi-hop routing. The fake radio reports paths and hops from its seed. +- The rest of #598: the `integration_test` harness (#602) and Win32 input injection (#603) stay on-demand. +- Any change to `lib/` beyond what a test needs to attach. The fake radio never ships in a release build. + +## 3. Epics + +Each Epic ends with a verification task and gets one PR. The first task reproduces the diagnosis as a failing test. + +### Epic A: core, profiles and the manifest check (#756) + +| Task | Pts | +|---|---| +| **A1 · Failing scenario test:** the real `MeshCoreConnector` connects and reaches `connected` with self info, contacts and channels loaded. Fails today: there is nothing to connect to. | 2 | +| **A2 · Core (absorbs #601):** frame codec, dispatch, seeded state (self info, device info, contacts, channels, queued messages, battery, custom vars, auto-add), deterministic clock. Every delay the fake produces (including B4's slow replies) runs on that clock, never wall time, so tests advance it with the test's fake clock. Every reply cites its firmware function. Unknown commands get the firmware's error reply. Unit tests per command. | 4 | +| **A3 · In-process and TCP adapters:** the same core behind `sendFrameOverrideForTest`/`handleFrameForTest`, and behind a loopback `ServerSocket` speaking the transport's serial framing (finding 5). | 3 | +| **A4 · Profiles from manifests:** the fake loads a `protocol-manifest.json` per profile. Offband: firmware version, version code and capability bits; answers the Offband commands. Stock: no capability bytes; rejects Offband commands as stock firmware does. Pinned copies are checked in under `test/` so CI runs offline. Until firmware#1318 publishes them, the pinned copies are generated once from the firmware source at the pinned tags, in the same format, and replaced by the published ones when they land. | 3 | +| **A5 · Manifest contract check:** a test that fails when `meshcore_protocol.dart` disagrees with the pinned Offband manifest (a command or response code, a capability bit, a version gate). Includes the reported-version fields. | 3 | +| **A6 · Epic verification:** A1 passes on both adapters and both profiles; same seed, same result over 20 runs; A5 fails on a deliberately wrong constant. | 1 | + +### Epic B: messaging, settings, remote nodes, faults and replay (#757) + +| Task | Pts | +|---|---| +| **B1 · Messaging:** direct and channel send (`SENT`, then `SEND_CONFIRMED` with a settable delay or drop), incoming messages through `MSG_WAITING` and `SYNC_NEXT_MESSAGE` in the V3 formats. | 4 | +| **B2 · Radio settings:** cmd 11, 12, 38 and 61 change the fake's state and show in the next `SELF_INFO`. | 2 | +| **B3 · Remote nodes:** seeded repeater, room server and sensor contacts; login success and failure; CLI replies for `get radio`, `set radio`, `tempradio`, `set path.hash.mode`, `set tx`, `ver` and `version`, copied from firmware `CommonCLI`. | 4 | +| **B4 · Scripted faults:** drop an ack, return an error, close the connection mid-sync, delay a reply. | 3 | +| **B5 · Trace capture and replay tooling:** a recorder that saves a real radio's frames from a client session to a fixture file, and a replay test that requires the fake to produce the same frames for the same requests and seed. Built and tested here against a recorded fake session; real-radio fixtures are captured in D1. | 4 | +| **B6 · Epic verification** | 1 | + +### Epic C: CI suites and the manual runner (#758) + +| Task | Pts | +|---|---| +| **C1 · Connector scenario suite, both profiles:** connect and sync; direct send, ack, retry and timeout; channel send; Companion preset apply (#647: cmd 11 radio params, cmd 12 TX power, cmd 61 path hash mode, checked in the fake's state and the next `SELF_INFO`); remote preset apply on a repeater, room server and sensor, including `tempradio` going last. Under the stock profile, also: no Offband feature is offered and no Offband command is sent. Runs in the default `flutter test`. | 4 | +| **C2 · Screen-level tests:** the channels screen and a chat screen, attached in-process to the fake radio; a composer send reaches the fake and the ack shows. | 4 | +| **C3 · Manual runner:** `dart run tool/fake_radio.dart --profile offband|stock --port 5000 --seed `; seed file format documented. The Windows app connects to it by TCP. | 3 | +| **C4 · Release guard:** the fake radio lives only under `test/` and `tool/`; a test fails if anything under `lib/` imports it. | 2 | +| **C5 · Epic verification** | 1 | + +### Epic D: integration testing (#759) + +| Task | Pts | +|---|---| +| **D1 · Owner session:** the Windows app connected to the manual runner (both profiles); then one real Offband radio and one radio flashed to stock MeshCore, each connected once while B5's recorder runs. | 3 | +| **D2 · Real-radio conformance:** the D1 traces committed as fixtures; the replay test passes against both, or each difference is fixed or recorded. | 3 | +| **D3 · OUTCOMES.md** | 1 | + +## 4. Order and dependencies + +- A, B, C, D in that order. Each Epic's verification task blocks the next Epic (wired in Citadel). +- B builds on A's core and profiles; C uses everything in A and B; D needs all three. +- All Epics touch the same new files (`test/support/fake_radio/`, `tool/fake_radio.dart`), so they run in sequence. C2 is the only task that touches app screens, and only from tests. +- Merges wait until the end, so each Epic's branch is stacked on the one before. +- **firmware#1318** is not a blocker: A4 starts from pinned manifests generated from the firmware source, and switches to the published ones when #1318 lands. If #1318 changes the manifest format, A4's loader follows it. +- #598 keeps #599, #600, #602, #603 and #604. Its bench will use this fake radio, so #598 depends on this Feature. + +## 5. Grants and authorization + +| Term | Proposed | Why | +|---|---|---| +| **What merging this plan authorizes** | Running Epics A to D in order without stopping between them: code, tests, builds, and one PR per Epic, stacked. | Canon: once the plan grant is minted, run the whole chain. | +| **Merges** | Held to the end of the Feature, in order A, B, C, D, after the owner's D1 session. | Canon. | +| **Epic verification** | Command mode: the merge hook runs `flutter test` on each PR's exact commit. | This Feature is test infrastructure; its own suites are the evidence. It also spares the owner a verify step per PR. | +| **Owner steps during the run** | None until D1. Before D1: pick the radio to flash to stock and mint its flash grant. At D1: the runner session and the two radio captures, in one sitting. | Canon: owner steps are one message, at the end. | +| **Stops** | A new decision; a fault I can't fix; a firmware reply I can't find a source for. | | +| **Flash** | Not in this grant. Before D1, the session flashes one radio the owner picks to a stock MeshCore companion release file, with `scripts/pio-flash` under its own `dw-approve flash ` grant. | Finding 12. A plan's flash term must name one registered device, and the radio isn't chosen yet, so the flash gets its own grant when it is. `pio-flash` flashes any firmware file, stock included (owner, 2026-10-02). | + +```grant-terms +{ + "epic_chain": [756, 757, 758, 759], + "chain": true, + "verification": { "mode": "command", "command": "flutter test" }, + "merge": { "budget": 4, "basis": "One PR per Epic: A (#756), B (#757), C (#758), D (#759: conformance fixtures and OUTCOMES.md)." }, + "flash": null, + "reset": null, + "expires_after_hours": 168 +} +``` + +`expires_after_hours` basis: 55 points of work, roughly five to six working sessions, plus the owner's D1 session around his day job. 168 hours is the maximum. + +## 6. Verification + +- **Named command:** `flutter analyze --fatal-infos --fatal-warnings`, `dart format --set-exit-if-changed`, the em-dash check, and `flutter test` (full suite, which includes the new suites). Every Epic PR shows the output. +- **Acceptance bar:** each finding in section 1 has a test that would have caught it. Most important: the handshake reaches `connected` under both profiles; the stock profile never sees an Offband feature or command; the manifest check fails on a wrong constant; a dropped ack is retried; a remote `tempradio` is sent last; a release build contains no fake radio code. +- **Owner requirement (#748):** every error message these flows show is tested present on failure and absent under ideal conditions. + +## 7. Done when + +- The default `flutter test`, and so every PR's CI, connects the real connector to the fake radio under both profiles and covers connect, sync, messaging, Companion presets and remote-node presets. +- Client CI fails when the client's protocol constants disagree with the pinned Offband manifest. +- The fake radio reproduces the captured traces from a real Offband radio and a real stock radio. +- The same fake radio runs from `tool/fake_radio.dart`, and the Windows app connects to it over TCP. +- Nothing under `lib/` imports the fake radio. +- The owner signs off D1, and `OUTCOMES.md` is approved. + +## 8. Your choices + +| # | Question | Option A | Option B | Rec. | Your choice | +|---|---|---|---|---|---| +| 1 | Where #601 lives | Move it into this Feature (A2); #598 depends on #755 | Leave it under #598 and build a second fake here | ⭐ A | **A** (2026-10-02) | +| 2 | Manual runner (C3) | In this Feature | Later, separately | ⭐ A (it's the "USB cables are tied up" case, and small once the TCP adapter exists) | **A** (2026-10-02) | +| 3 | Remote-node emulation (B3) | In this Feature | Later, separately | ⭐ A (it covers the #647 remote-preset gap in CI) | **A** (2026-10-02) | + +## Decisions + +| Date | Decision | +|---|---| +| 2026-10-02 | The fake radio runs in CI (reverses #598's "not in CI" for the fake radio only). | +| 2026-10-02 | Stock and Offband are emulated as separate profiles. | +| 2026-10-02 | The firmware publishes the protocol manifest at every tag and merge (firmware#1318); the fake radio consumes it, never a hand copy. | +| 2026-10-02 | Behavior is checked against captured traces from a real Offband radio and a radio flashed to stock. | +| 2026-10-02 | The session flashes the stock radio with `scripts/pio-flash`, which flashes stock files too (owner). | +| 2026-10-02 | The stock flash moves out of the plan grant to its own `dw-approve flash ` grant: `dw-approve plan` refused a flash term with no device. | +| 2026-10-02 | Section 8: all three recommendations accepted. #601 moves under Epic A (#756); the manual runner and remote-node emulation are in scope. | + +## 9. Carried-in work + +| Item | Goes to | +|---|---| +| #601 (loopback fake radio, planned only) | A2 and A3 | +| #598 owner decision (not in CI) | Reversed for the fake radio only (2026-10-02, logged on #598) | +| #738 remote-preset test gap | C1 (in CI) | +| firmware#1318 (manifest, reported-version check) | Firmware repo; A4 and A5 consume it | +| firmware#514, #873 | Referenced by firmware#1318; firmware side | + +## Alternatives considered but not chosen + +- **Firmware CI builds the fake radio itself:** the fake is Dart code in the client repo; firmware CI builds C++. Firmware publishes the contract instead, and the client builds from it. +- **Hand-copied protocol constants in the fake:** drifts silently, the failure firmware#514 already documents. +- **`integration_test` on a Linux desktop runner in CI:** needs a display server and a full app build per run; the in-process adapter reaches the same screens from `flutter test`. +- **A Python or firmware-native simulator:** a second toolchain in CI, and it can't use the connector's in-process seam. +- **Running the real companion firmware on the host:** not investigated; it would mean building and maintaining a host port of the firmware, a much larger effort than this Feature. + +When this plan merges, each Task gets a GitHub issue and a Citadel task, per canon. diff --git a/lib/connector/caplog_reassembler.dart b/lib/connector/caplog_reassembler.dart index 1bcb4471..e4126770 100644 --- a/lib/connector/caplog_reassembler.dart +++ b/lib/connector/caplog_reassembler.dart @@ -71,23 +71,26 @@ class CaplogBusyException implements Exception { 'CaplogBusyException: device busy, another stream is in flight'; } -/// Thrown when the reassembled caplog byte count doesn't match the length the -/// device announced in its START frame. (#430) -class CaplogTruncatedException implements Exception { - const CaplogTruncatedException({ +/// Result of a caplog download. On a clean transfer [received] == [expected] +/// and [truncated] is false; on a short transfer [bytes] still carry everything +/// that was reassembled and [truncated] is true. A partial capture is kept and +/// handed back rather than discarded, so the user can still save/share it. (#580) +class CaplogDownload { + const CaplogDownload({ + required this.bytes, required this.received, required this.expected, - this.chunks, + required this.chunks, }); + + /// The reassembled bytes (complete, or partial when [truncated]). + final Uint8List bytes; final int received; final int expected; - /// Number of CHUNK frames the client accumulated before END, a diagnostic to - /// tell client/transport frame loss apart from the firmware streaming short. - final int? chunks; + /// Number of CHUNK frames accumulated before END, a diagnostic to tell + /// client/transport frame loss apart from the firmware streaming short. + final int chunks; - @override - String toString() => - 'CaplogTruncatedException: received $received of $expected bytes' - '${chunks != null ? ' in $chunks chunks' : ''}'; + bool get truncated => received != expected; } diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 9ddc6e09..3cdfb2c6 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -17,7 +17,9 @@ import '../models/message.dart'; import '../models/offband_gps_status.dart'; import '../models/path_selection.dart'; import '../models/translation_support.dart'; +import '../helpers/channel_send_timestamp.dart'; import '../helpers/pending_reactions.dart'; +import '../services/corescope_service.dart'; import '../helpers/pocketmesh_reaction.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/time_anomaly.dart'; @@ -179,6 +181,38 @@ enum MeshCoreConnectionState { enum MeshCoreTransportType { bluetooth, usb, tcp } +/// Outcome of a node-identity read or write. (#578) +/// +/// [unsupported] is deliberately distinct from [rejected]: the firmware can be +/// built without identity transfer at all (`ENABLE_PRIVATE_KEY_EXPORT` / +/// `ENABLE_PRIVATE_KEY_IMPORT`), and a UI must say "this radio cannot do it" +/// rather than "that failed, try again". +enum IdentityTransfer { + /// The device returned its identity, or accepted the one we sent. + ok, + + /// The firmware was compiled without the feature. + unsupported, + + /// The device understood the request and refused it, e.g. an invalid key. + rejected, + + /// Not connected, or no reply before the timeout. + noReply, +} + +/// Result of [MeshCoreConnector.exportPrivateKey]. [identity] is +/// non-null only when [outcome] is [IdentityTransfer.ok]. (#578) +class IdentityExportResult { + const IdentityExportResult(this.outcome, [this.identity]); + + final IdentityTransfer outcome; + + /// The 64-byte node identity. Secret material: never log it, never persist + /// it outside a user-initiated export file. + final Uint8List? identity; +} + class RepeaterBatterySnapshot { final int millivolts; final DateTime updatedAt; @@ -207,6 +241,36 @@ class MeshCoreRadioStateSnapshot { }); } +/// A full contact sync that delivered fewer contacts than the radio declared. +/// [declared] is null when the radio sent no total (older firmware). +class ContactSyncShortfall { + final int? declared; + final int received; + final int keptLocally; + + /// Saved contacts the radio answered "not found" for (#764). + final int confirmedGone; + + const ContactSyncShortfall({ + required this.declared, + required this.received, + required this.keptLocally, + this.confirmedGone = 0, + }); +} + +/// What the radio said when asked for one contact by key. (#762) +enum ContactKeyCheckResult { onRadio, notFound, unresolved } + +class _PendingKeyCheck { + final String keyHex; + final DateTime startedAt; + final Completer done = Completer(); + Timer? timer; + + _PendingKeyCheck({required this.keyHex, required this.startedAt}); +} + class MeshCoreConnector extends ChangeNotifier { // Message windowing to limit memory usage static const int _messageWindowSize = 200; @@ -221,6 +285,18 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + + // Set when a manual BLE disconnect was never confirmed by the platform, so + // the OS may still hold the radio and it stops advertising (#689/#697). + // Cleared on the next connect, the next disconnect attempt, or UI dismiss. + bool _bleReleaseUnconfirmed = false; + bool get bleReleaseUnconfirmed => _bleReleaseUnconfirmed; + void clearBleReleaseWarning() { + if (!_bleReleaseUnconfirmed) return; + _bleReleaseUnconfirmed = false; + notifyListeners(); + } + final MeshCoreUsbManager _usbManager = MeshCoreUsbManager(); final LinuxBlePairingService _linuxBlePairingService = LinuxBlePairingService(); @@ -235,6 +311,10 @@ class MeshCoreConnector extends ChangeNotifier { final List _channels = []; final Map> _conversations = {}; final Map> _channelMessages = {}; + + /// Last send timestamp (seconds) used per channel, to keep every channel + /// send's `(ts, channel_idx)` key unique for 0xC6 correlation (#524). + final Map _lastChannelSendTsSecs = {}; final List _pendingChannelSentQueue = []; final List<_PendingCommandAck> _pendingGenericAckQueue = []; static const String _reactionSendQueuePrefix = '__reaction_send__'; @@ -249,6 +329,7 @@ class MeshCoreConnector extends ChangeNotifier { StreamSubscription>? _scanSubscription; StreamSubscription? _connectionSubscription; StreamSubscription>? _notifySubscription; + StreamSubscription? _mtuSubscription; Timer? _notifyListenersTimer; Timer? _selfInfoRetryTimer; int _appStartRetryAttempt = 0; @@ -286,11 +367,19 @@ class MeshCoreConnector extends ChangeNotifier { bool _blockDumpInFlight = false; final Set _blockKeysTouchedDuringDump = {}; // Caplog serial-capture download (0xC4) streamed reassembly (#430). - Completer? _caplogCompleter; + Completer? _caplogCompleter; CaplogReassembler? _caplogReassembler; bool _caplogAwaitingStart = false; Completer? _caplogAckCompleter; Completer? _caplogStatusCompleter; + // Node identity transfer (#578). Only one of each may be in flight. + Completer? _identityExportCompleter; + Completer? _identityImportCompleter; + + /// Outstanding 0xC6 packet-hash queries, keyed "ts_chan" so a reply matches + /// its request without relying on ordering (#524). + final Map> _pendingPktHashCompleters = {}; + final CoreScopeService _coreScopeService = CoreScopeService(); int _caplogChunks = 0; // CHUNK frames in the active download (diagnostic) String? _firmwareVersion; String? _deviceModel; @@ -298,6 +387,7 @@ class MeshCoreConnector extends ChangeNotifier { int? _offbandCaps2; bool? _femLnaEnabled; ButtonMatrix? _buttonMatrix; + String? _lastDeviceUiSuppression; DeviceNotifyScope? _deviceNotifyScope; String? _deviceUiError; int _pathHashByteWidth = 1; @@ -339,7 +429,8 @@ class MeshCoreConnector extends ChangeNotifier { bool _pendingInitialQueuedMessageSync = false; bool _bleInitialSyncStarted = false; bool _webInitialHandshakeRequestSent = false; - bool _preserveContactsOnRefresh = false; + int _autoAddMaxHops = 0; + int _manualAddContactsRaw = 0; bool _autoAddUsers = false; bool _autoAddRepeaters = false; bool _autoAddRoomServers = false; @@ -359,6 +450,61 @@ class MeshCoreConnector extends ChangeNotifier { int? _contactSyncTotal; int _contactSyncReceived = 0; bool _contactSyncUsesSinceFilter = false; + // A full sync never clears the local list. It records which contacts the + // radio delivered, and only a complete sync (received == declared) may drop + // the ones it did not. A short sync once replaced the owner's 350 saved + // contacts with the 106 the radio sent (#660, #668). + bool _contactSyncIsFull = false; + int? _contactSyncDeclaredTotal; + final Set _contactSyncDeliveredKeys = {}; + bool _contactSyncDecisionPending = false; + // Forced resync (#703): after a short full sync the app waits for the link to + // settle, syncs again (at most [contactSyncMaxFullStreams] full syncs per + // connection, owner decision), then asks the radio by key for each saved + // contact still missing. Only a contact the radio answers "not found" for is + // ever removed by it. All of this is per connection: a disconnect or radio + // switch bumps [_recoveryRun] and drops it. + static const int contactSyncMaxFullStreams = 3; + static const Duration defaultContactRecoverySettle = Duration(seconds: 10); + static const Duration defaultContactKeyCheckGap = Duration(milliseconds: 250); + @visibleForTesting + Duration contactRecoverySettle = defaultContactRecoverySettle; + @visibleForTesting + Duration contactKeyCheckGap = defaultContactKeyCheckGap; + int _contactFullStreams = 0; + int _recoveryRun = 0; + String? _recoveryRadioKey; + final Set _recoveryDelivered = {}; + final Set _recoveryGone = {}; + int? _recoveryDeclared; + DateTime? _recoveryWaitingSince; + bool _recoveryCheckingKeys = false; + static const Duration contactRecoveryMaxWait = Duration(minutes: 2); + Timer? _recoverySettleTimer; + DateTime _lastRadioFrameAt = DateTime.fromMillisecondsSinceEpoch(0); + ContactSyncShortfall? _contactSyncShortfall; + // One contact request at a time: the firmware refuses a second + // CMD_GET_CONTACTS mid-stream with ERR_CODE_BAD_STATE. A request made while + // one runs is queued and sent after END. A request with no contact frames + // for [contactRequestStaleAfter] is treated as lost so a missing END cannot + // block every later refresh (#672, owner decision on the 30 s value). + static const Duration contactRequestStaleAfter = Duration(seconds: 30); + bool _contactRequestInFlight = false; + bool _contactStreamStarted = false; + DateTime _contactRequestLastActivity = DateTime.fromMillisecondsSinceEpoch(0); + ({int? since, bool preserveExisting})? _queuedContactRequest; + Timer? _contactRequestWatchdog; + // One CMD_GET_CONTACT_BY_KEY check at a time. Its NOT_FOUND reply carries no + // key, so the check only trusts one that nothing else could own: see + // [_notFoundIsForKeyCheck]. (#762) + _PendingKeyCheck? _pendingKeyCheck; + DateTime? _untrackedByKeyAt; + + @visibleForTesting + Duration contactKeyCheckTimeout = const Duration(seconds: 5); + + @visibleForTesting + DateTime Function() contactSyncClock = DateTime.now; bool _isSyncingQueuedMessages = false; bool _deferQueuedContactMessagesUntilContacts = false; bool _isProcessingDeferredQueuedContactMessages = false; @@ -441,18 +587,93 @@ class MeshCoreConnector extends ChangeNotifier { /// handle); a device that negotiates a smaller MTU than [maxFrameSize] assumes /// would otherwise reject a max-length message and wedge the send path (#395). /// USB/TCP have no such per-write cap, so they take the full [maxFrameSize]. - int get effectiveMaxFrameSize { - if (_activeTransport != MeshCoreTransportType.bluetooth) { + int get effectiveMaxFrameSize => resolveFrameBudget( + transport: _activeTransport, + isWeb: PlatformInfo.isWeb, + mtuNow: _device?.mtuNow ?? 0, + ); + + /// Writes the composer's actual byte budget to the app log. + /// + /// #592 was about this number, and until #793 it was the one thing the log + /// never recorded. We had Windows BLE logs back to August proving MTU 247, + /// and hundreds of Android sessions, and not one of them could evidence + /// whether the composer was usable: the log showed what was sent, never the + /// limit the field applied. A log reading `channel=0` beside a user saying + /// the keyboard is dead is a diagnosis; without it that is a guess. + /// + /// Derived from the same functions the composers call, never reimplemented, + /// so the log cannot drift away from the behaviour it is describing. + /// + /// Logs the name's LENGTH, never the name. The length is the whole of what + /// the budget depends on (the channel budget subtracts a `": "` + /// prefix), and these logs get attached to public issues. A radio name is + /// usually an amateur callsign, which is publicly resolvable to a real name + /// and address, so it has no business in a file we ask users to upload + /// (CLAUDE-BASE, redaction discipline). + /// + /// Called whenever an INPUT to the budget changes: the MTU, and the self + /// name. Both matter and they arrive at different times, the name only in + /// SELF_INFO well after the first MTU event, so logging on the MTU alone + /// would report a budget computed from a null name. That is not a harmless + /// gap: `_senderNameBytes(null)` returns the 31-byte maximum, so the early + /// line would understate the real channel budget. + /// + /// Not per keystroke or per send: diagnostics must not become the outage + /// (SAFELANE 11 rule 10). + void _logComposerBudget(String reason) { + final frame = effectiveMaxFrameSize; + final name = selfName; + final dm = maxContactMessageBytes(maxFrameBytes: frame); + final channel = maxChannelMessageBytes(name, maxFrameBytes: frame); + _appDebugLogService?.info( + 'composer budget ($reason): frame=$frame dm=$dm channel=$channel ' + 'transport=${_activeTransport.name} ' + 'nameLen=${name?.length ?? -1}' + '${isComposerBudgetUsable(channel) ? '' : ' <-- CHANNEL COMPOSER UNUSABLE'}', + tag: 'BLE Connect', + ); + } + + /// The frame-budget decision, as a pure function of its three inputs. + /// + /// Extracted from [effectiveMaxFrameSize] so every branch is reachable from a + /// VM test. In particular the web branch is not otherwise testable at all: + /// `kIsWeb` is a compile-time constant, so a VM test can never enter it, and + /// CI runs the suite on the VM only. This getter decides the composer's byte + /// budget on every platform and had collapsed it to zero on three of them + /// (#592, #686, #717, #718), so it is pinned by test rather than by comment. + /// + /// [mtuNow] is 0 when no device is attached. + @visibleForTesting + static int resolveFrameBudget({ + required MeshCoreTransportType transport, + required bool isWeb, + required int mtuNow, + }) { + if (transport != MeshCoreTransportType.bluetooth) { + return maxFrameSize; + } + // Web Bluetooth exposes no ATT MTU to page script: there is no API for it, + // so mtuNow can only ever be the 23-byte default and the floor below would + // cap every composer at 0-4 bytes forever (#718, the #592 symptom). + // + // The floor exists because a raw single characteristic write larger than + // the PDU is rejected and wedges the send path (#395). That failure mode is + // not reachable here: the browser owns fragmentation, and the Web Bluetooth + // spec caps one write at 512 bytes, rejecting anything larger with + // InvalidModificationError. maxFrameSize (172) is well inside that, so the + // write cannot be oversized no matter what the link negotiated. + if (isWeb) { return maxFrameSize; } - final mtu = _device?.mtuNow ?? 0; // ATT_MTU 23 is the BLE minimum; a single write then carries 23 - 3 = 20 // bytes. An unknown MTU must fall back to that floor, never [maxFrameSize], // defaulting an unknown link to the largest size would authorize an // oversized write (#395 review). const minWritable = 20; - if (mtu <= 0) return minWritable; - final writable = mtu - 3; + if (mtuNow <= 0) return minWritable; + final writable = mtuNow - 3; if (writable >= maxFrameSize) return maxFrameSize; return writable < minWritable ? minWritable : writable; } @@ -582,10 +803,20 @@ class MeshCoreConnector extends ChangeNotifier { bool? get autoAddRoomServers => _autoAddRoomServers; bool? get autoAddSensors => _autoAddSensors; bool? get autoAddOverwriteOldest => _overwriteOldest; + + /// `autoadd_max_hops`; 0 means no limit. Stays 0 on firmware old enough to + /// answer [respCodeAutoAddConfig] with only two bytes. (#578) + int get autoAddMaxHops => _autoAddMaxHops; int get telemetryModeBase => _telemetryModeBase; int get telemetryModeLoc => _telemetryModeLoc; int get telemetryModeEnv => _telemetryModeEnv; int get advertLocationPolicy => _advertLocPolicy; + + /// The device's `manual_add_contacts` pref exactly as reported, for callers + /// that must reproduce it rather than interpret it (stock config export, + /// #573). [_manualAddContacts] is a derived, inverted view of bit 0 and is + /// not what belongs in an export file. + int get manualAddContactsRaw => _manualAddContactsRaw; int get multiAcks => _multiAcks; bool? get clientRepeat => _clientRepeat; @@ -626,6 +857,16 @@ class MeshCoreConnector extends ChangeNotifier { /// Whether this radio exposes a settable device notification scope (#475). bool get supportsNotifyScope => firmwareSupportsNotifyScope(_offbandCaps2); + /// Whether this radio answers the 0xC6 packet-hash query (#524/#611). + bool get supportsPktHash => + firmwareSupportsPktHash(_offbandCaps2, _firmwareVerCode); + + /// Whether to fetch CoreScope observer counts for outgoing channel messages: + /// firmware supports the hash query AND the owner enabled the feature. + bool get _coreScopeQueryActive => + supportsPktHash && + (_appSettingsService?.settings.coreScopeObserverCountEnabled ?? false); + /// Whether the radio can actually be QUERIED, as opposed to merely reporting /// that it has the feature. False until firmware lands the get/set command, /// so no frame is emitted that nothing will answer. The distinction is real @@ -655,8 +896,51 @@ class MeshCoreConnector extends ChangeNotifier { /// Ask the radio for its button matrix. No-op unless the capability bit is /// set, so an unsupported radio never sees `0xC5`. + /// True when a `0xC5` request for [what] may be sent, logging the reason when + /// it may not. + /// + /// A suppressed request is the case that cost a whole diagnosis on + /// 2026-08-02: the scope appeared not to refresh, and nothing in either the + /// app log or a firmware serial capture could distinguish "the client never + /// asked" from "the client asked and got an unchanged value". Silence is + /// ambiguous, so the suppression says which gate closed and why. (#501) + bool _deviceUiGateOpen(String what, {required bool advertised}) { + if (!deviceUiCommandLanded) { + _logDeviceUiSuppression(what, '0xC5 command support is compiled off'); + return false; + } + if (!advertised) { + _logDeviceUiSuppression( + what, + 'radio does not advertise it ' + '(caps2=${_offbandCaps2 == null ? 'absent' : '0x${_offbandCaps2!.toRadixString(16).padLeft(2, '0')}'})', + ); + return false; + } + // A gate that opens clears the memo, so the next genuine suppression is + // reported rather than swallowed as a repeat. + _lastDeviceUiSuppression = null; + return true; + } + + /// Log a suppressed request ONCE per distinct reason. + /// + /// Device-info arrives on every connect, so a flapping radio would otherwise + /// emit the same suppression line on every reconnect. Diagnostics must not + /// become the outage (SAFELANE §11 rule 10), and a repeated identical line + /// carries no information the first one did not. + void _logDeviceUiSuppression(String what, String reason) { + final memo = '$what|$reason'; + if (_lastDeviceUiSuppression == memo) return; + _lastDeviceUiSuppression = memo; + _appDebugLogService?.info('$what suppressed: $reason', tag: 'DeviceUI'); + } + Future requestButtonMatrix() async { - if (!supportsDeviceUiCommand || !supportsButtonMatrix) return; + if (!_deviceUiGateOpen('matrix GET', advertised: supportsButtonMatrix)) { + return; + } + _appDebugLogService?.info('matrix GET -> [0xC5][0x03]', tag: 'DeviceUI'); await sendFrame(buildButtonMatrixGetFrame()); } @@ -668,22 +952,40 @@ class MeshCoreConnector extends ChangeNotifier { ButtonSequence sequence, ButtonAction action, ) async { - if (!supportsDeviceUiCommand || !supportsButtonMatrix) return; + if (!_deviceUiGateOpen('matrix SET', advertised: supportsButtonMatrix)) { + return; + } _deviceUiError = null; + _appDebugLogService?.info( + 'matrix SET -> ${sequence.label} = ${action.label} ' + '[0xC5][0x04][0x${sequence.code.toRadixString(16).padLeft(2, '0')}]' + '[0x${action.code.toRadixString(16).padLeft(2, '0')}]', + tag: 'DeviceUI', + ); await sendFrame(buildButtonMatrixSetFrame(sequence, action)); } /// Ask the radio for its current notification scope. Future requestNotifyScope() async { - if (!supportsDeviceUiCommand || !supportsNotifyScope) return; + if (!_deviceUiGateOpen('scope GET', advertised: supportsNotifyScope)) { + return; + } + _appDebugLogService?.info('scope GET -> [0xC5][0x01]', tag: 'DeviceUI'); await sendFrame(buildNotifyScopeGetFrame()); } /// Set the device notification scope. As with the matrix, local state follows /// the device's reply rather than the request. Future setNotifyScope(DeviceNotifyScope scope) async { - if (!supportsDeviceUiCommand || !supportsNotifyScope) return; + if (!_deviceUiGateOpen('scope SET', advertised: supportsNotifyScope)) { + return; + } _deviceUiError = null; + _appDebugLogService?.info( + 'scope SET -> ${scope.label} ' + '[0xC5][0x02][0x${scope.code.toRadixString(16).padLeft(2, '0')}]', + tag: 'DeviceUI', + ); await sendFrame(buildNotifyScopeSetFrame(scope)); } @@ -697,6 +999,7 @@ class MeshCoreConnector extends ChangeNotifier { /// reconnect can show one radio's notification scope as another's. void _clearDeviceUiState() { _buttonMatrix = null; + _lastDeviceUiSuppression = null; _deviceNotifyScope = null; _deviceUiError = null; } @@ -733,8 +1036,20 @@ class MeshCoreConnector extends ChangeNotifier { return; } if (reply.matrix != null) { - _buttonMatrix = reply.matrix; + final m = reply.matrix!; + _appDebugLogService?.info( + 'matrix GET reply: mask=0x${m.supportedActions.toRadixString(16).padLeft(2, '0')} ' + 'rows=${m.assignments.length} ' + '[${m.assignments.entries.map((e) => '${e.key.label}=${e.value.label}').join(', ')}]', + tag: 'DeviceUI', + ); + _buttonMatrix = m; } else if (reply.setSequence != null && reply.setAction != null) { + _appDebugLogService?.info( + 'matrix SET confirmed: ${reply.setSequence!.label} = ' + '${reply.setAction!.label}', + tag: 'DeviceUI', + ); final held = _buttonMatrix; if (held == null) { // A device-confirmed write with nothing to fold it into. Never drop it @@ -758,7 +1073,26 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'DeviceUI', ); } else { - _deviceNotifyScope = reply.scope; + final scope = reply.scope; + if (scope == null) { + // Not reachable today: parseNotifyScopeReply returns an error reply + // when the scope code is unknown, so a non-error reply always carries + // one. That invariant lives in another file, so it is checked here + // rather than asserted with a bang across the boundary. + _appDebugLogService?.warn( + 'scope reply with no scope (sub=0x' + '${reply.sub.toRadixString(16).padLeft(2, '0')})', + tag: 'DeviceUI', + ); + } else { + _appDebugLogService?.info( + 'scope reply: ${scope.label} ' + '(sub=0x${reply.sub.toRadixString(16).padLeft(2, '0')}, ' + '${reply.sub == offbandUiScopeSet ? 'write confirmed' : 'read'})', + tag: 'DeviceUI', + ); + _deviceNotifyScope = scope; + } } notifyListeners(); } @@ -828,6 +1162,15 @@ class MeshCoreConnector extends ChangeNotifier { int get maxContacts => _maxContacts; int get maxChannels => _maxChannels; Set get knownContactKeys => Set.unmodifiable(_knownContactKeys); + + /// O(1) membership test for a contact by public key hex. + /// + /// Use this from a widget `build`, never [knownContactKeys], which copies the + /// whole set on every call, nor a scan of [contacts]. A received contact card + /// asks this question once per rendered chip on every connector + /// notification. (#610) + bool isKnownContact(String publicKeyHex) => + _knownContactKeys.contains(publicKeyHex); double? get contactSyncProgress { final total = _contactSyncTotal; if (!_isLoadingContacts || total == null || total <= 0) return null; @@ -1003,19 +1346,25 @@ class MeshCoreConnector extends ChangeNotifier { /// display name matches [name] (case-insensitive). Resolves an anonymous /// channel sender (name-only, no pubkey) back to identities for block /// matching. Multiple keys => several devices/people share the name. - List resolveContactKeysByName(String name) { + /// Resolve a claimed name to the identities behind it, known contacts first. + /// + /// Channel messages carry no key (#468), so a claimed name is all a channel + /// sender gives us. A name several nodes share resolves to every one of them: + /// callers surface the ambiguity, they never pick a winner. + List resolveContactsByName(String name) { final target = name.trim().toLowerCase(); if (target.isEmpty) return const []; - final keys = {}; - for (final c in contacts) { - if (c.name.trim().toLowerCase() == target) keys.add(c.publicKeyHex); - } - for (final c in discoveredContacts) { - if (c.name.trim().toLowerCase() == target) keys.add(c.publicKeyHex); + final byKey = {}; + for (final c in [...contacts, ...discoveredContacts]) { + if (c.name.trim().toLowerCase() != target) continue; + byKey.putIfAbsent(c.publicKeyHex, () => c); } - return keys.toList(); + return byKey.values.toList(); } + List resolveContactKeysByName(String name) => + resolveContactsByName(name).map((c) => c.publicKeyHex).toList(); + Future deleteChannelMessage(ChannelMessage message) async { final channelIndex = message.channelIndex; if (channelIndex == null) return; @@ -2196,6 +2545,7 @@ class MeshCoreConnector extends ChangeNotifier { _lastDeviceId = _deviceId; _lastDeviceDisplayName = _deviceDisplayName; _manualDisconnect = false; + _bleReleaseUnconfirmed = false; _cancelReconnectTimer(); _bleInitialSyncStarted = false; if (PlatformInfo.isWeb) { @@ -2214,6 +2564,8 @@ class MeshCoreConnector extends ChangeNotifier { _connectionSubscription = null; await _notifySubscription?.cancel(); _notifySubscription = null; + await _mtuSubscription?.cancel(); + _mtuSubscription = null; _connectionSubscription = device.connectionState.listen((state) { if (state == BluetoothConnectionState.disconnected && isConnected) { _handleDisconnection(); @@ -2339,18 +2691,42 @@ class MeshCoreConnector extends ChangeNotifier { } } } else { - try { - await device.connect( - timeout: connectTimeout, - mtu: null, - license: License.free, - ); - } catch (error) { - _appDebugLogService?.error( - 'device.connect() failure: $error', - tag: 'BLE Connect', - ); - rethrow; + var attempt = 0; + while (true) { + attempt++; + try { + await device.connect( + timeout: connectTimeout, + mtu: null, + license: License.free, + ); + break; + } catch (error) { + // Android GATT status 133 (ANDROID_SPECIFIC_ERROR) is the + // notorious, frequently transient connect failure. Standard + // mitigation (#522/#698): clean close, short delay, one bounded + // retry before surfacing anything to the user. + final isTransient133 = + error is FlutterBluePlusException && error.code == 133; + _appDebugLogService?.error( + 'device.connect() failure (attempt $attempt): $error', + tag: 'BLE Connect', + ); + if (!isTransient133 || attempt >= 2) rethrow; + try { + await device.disconnect(queue: false, timeout: 5); + } catch (cleanupError) { + _appDebugLogService?.warn( + 'cleanup disconnect before 133 retry failed: $cleanupError', + tag: 'BLE Connect', + ); + } + await Future.delayed(const Duration(milliseconds: 800)); + _appDebugLogService?.info( + 'retrying connect after GATT 133', + tag: 'BLE Connect', + ); + } } } @@ -2361,8 +2737,11 @@ class MeshCoreConnector extends ChangeNotifier { ); } - // Request larger MTU only where the platform path supports it. - if (!PlatformInfo.isWeb && !PlatformInfo.isLinux) { + // Requesting an MTU is Android-only: flutter_blue_plus throws + // "android-only" on every other platform before the platform code runs + // (#683). Elsewhere the platform reports the negotiated value on its own + // and we pick it up from the mtu stream below. + if (PlatformInfo.isAndroid) { try { final mtu = await device.requestMtu(185); _appDebugLogService?.info('MTU set to: $mtu', tag: 'BLE Connect'); @@ -2372,13 +2751,19 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'BLE Connect', ); } - } else if (PlatformInfo.isLinux) { - _appDebugLogService?.info( - 'Skipping MTU request on Linux; flutter_blue_plus only supports requestMtu on Android', - tag: 'BLE Connect', - ); } + // The MTU can arrive or change after connect. effectiveMaxFrameSize is + // read on every composer rebuild, so notifying here is what lets the + // message byte budget recover from the 20-byte floor once the real value + // is known (#592). + await _mtuSubscription?.cancel(); + _mtuSubscription = device.mtu.listen((mtu) { + _appDebugLogService?.info('MTU now: $mtu', tag: 'BLE Connect'); + _logComposerBudget('mtu'); + notifyListeners(); + }); + late final List services; try { services = await device.discoverServices(); @@ -2812,9 +3197,27 @@ class MeshCoreConnector extends ChangeNotifier { void resetConnectionHandshakeStateForTest() => _resetConnectionHandshakeState(); + /// Feeds a device frame through the normal dispatch, so parse paths can be + /// exercised without a radio. (#578) + @visibleForTesting + void handleFrameForTest(List frame) => _handleFrameInner(frame); + + /// When set, [sendFrame] hands frames here instead of a transport. + @visibleForTesting + void Function(Uint8List data)? sendFrameOverrideForTest; + + @visibleForTesting + void setConnectedForTest() => _state = MeshCoreConnectionState.connected; + @visibleForTesting Map> get channelMessagesForTest => _channelMessages; + @visibleForTesting + List get contactsForTest => _contacts; + + @visibleForTesting + List get discoveredContactsForTest => _discoveredContacts; + @visibleForTesting Map> get conversationsForTest => _conversations; @@ -2828,6 +3231,30 @@ class MeshCoreConnector extends ChangeNotifier { _contactSyncTotal = null; _contactSyncReceived = 0; _contactSyncUsesSinceFilter = false; + _contactSyncIsFull = false; + _contactSyncDeclaredTotal = null; + _contactSyncDeliveredKeys.clear(); + _contactFullStreams = 0; + _recoveryRun++; + _recoveryRadioKey = null; + _recoveryDelivered.clear(); + _recoveryGone.clear(); + _recoveryDeclared = null; + _recoveryWaitingSince = null; + _recoveryCheckingKeys = false; + _recoverySettleTimer?.cancel(); + _recoverySettleTimer = null; + _contactSyncDecisionPending = false; + _contactRequestWatchdog?.cancel(); + _contactRequestWatchdog = null; + _contactRequestInFlight = false; + _contactStreamStarted = false; + _queuedContactRequest = null; + final keyCheck = _pendingKeyCheck; + if (keyCheck != null) { + _finishKeyCheck(keyCheck, ContactKeyCheckResult.unresolved); + } + _untrackedByKeyAt = null; _isLoadingContacts = false; _hasLoadedContacts = false; _isLoadingChannels = false; @@ -2938,6 +3365,9 @@ class MeshCoreConnector extends ChangeNotifier { await _notifySubscription?.cancel(); _notifySubscription = null; + await _mtuSubscription?.cancel(); + _mtuSubscription = null; + await _connectionSubscription?.cancel(); _connectionSubscription = null; _selfInfoRetryTimer?.cancel(); @@ -2951,11 +3381,32 @@ class MeshCoreConnector extends ChangeNotifier { await _translationService?.releaseModel(); if (!skipBleDeviceDisconnect) { - try { - // Skip queued BLE operations so disconnect doesn't get stuck behind them. - await _device?.disconnect(queue: false); - } catch (e) { - _appDebugLogService?.warn('Disconnect error: $e', tag: 'BLE Connect'); + _bleReleaseUnconfirmed = false; + var released = _device == null; + for (var attempt = 1; attempt <= 2 && !released; attempt++) { + try { + // Skip queued BLE operations so disconnect doesn't get stuck behind + // them. Cap the platform-confirm wait well below FBP's 35 s default; + // the vendored Android plugin force-closes and confirms within ~5 s + // when the OS never reports the disconnect (#696). + await _device?.disconnect(queue: false, timeout: 10); + released = true; + } catch (e) { + _appDebugLogService?.warn( + 'Disconnect attempt $attempt failed: $e', + tag: 'BLE Connect', + ); + if (attempt == 1) { + await Future.delayed(const Duration(milliseconds: 500)); + } + } + } + if (!released && + transportAtDisconnect == MeshCoreTransportType.bluetooth) { + // Both attempts failed: the OS never confirmed the release, so this + // device may still hold the radio and keep it from advertising + // (#689). Surfaced as a persistent warning, never swallowed. + _bleReleaseUnconfirmed = true; } } else { _appDebugLogService?.info( @@ -3019,6 +3470,11 @@ class MeshCoreConnector extends ChangeNotifier { if (!isConnected) { throw Exception("Not connected to a MeshCore device"); } + final override = sendFrameOverrideForTest; + if (override != null) { + override(data); + return; + } _bleDebugLogService?.logFrame(data, outgoing: true); if (_activeTransport == MeshCoreTransportType.usb) { @@ -3360,18 +3816,120 @@ class MeshCoreConnector extends ChangeNotifier { Future getContacts({int? since, bool preserveExisting = false}) async { if (!isConnected) return; + if (_contactRequestInFlight) { + final idle = contactSyncClock().difference(_contactRequestLastActivity); + if (idle < contactRequestStaleAfter) { + _queueContactRequest(since: since, preserveExisting: preserveExisting); + return; + } + _appDebugLogService?.warn( + 'Contact request had no reply for ${idle.inSeconds}s; treating it as ' + 'lost and sending a new one', + tag: 'ContactSync', + ); + } + _contactRequestInFlight = true; + _contactStreamStarted = false; + _contactRequestLastActivity = contactSyncClock(); + _armContactRequestWatchdog(); + _isLoadingContacts = true; - _preserveContactsOnRefresh = preserveExisting; _contactSyncTotal = null; _contactSyncReceived = 0; _contactSyncUsesSinceFilter = since != null; + if (since == null) _recoverySettleTimer?.cancel(); + _beginContactSync(full: since == null); if (!preserveExisting) { _hasLoadedContacts = false; - _contacts.clear(); } notifyListeners(); - await sendFrame(buildGetContactsFrame(since: since)); + try { + await sendFrame(buildGetContactsFrame(since: since)); + } catch (e) { + _endContactRequest(); + _appDebugLogService?.error( + 'Contact request could not be sent: $e', + tag: 'ContactSync', + ); + notifyListeners(); + rethrow; + } + } + + /// Keeps at most one request waiting. A full request wins over an + /// incremental one, since it covers it. + void _queueContactRequest({int? since, required bool preserveExisting}) { + final queued = _queuedContactRequest; + final full = since == null || (queued != null && queued.since == null); + _queuedContactRequest = ( + since: full ? null : since, + preserveExisting: preserveExisting && (queued?.preserveExisting ?? true), + ); + _appDebugLogService?.info( + 'Contact request queued behind the one in flight ' + '(${full ? 'full' : 'incremental'})', + tag: 'ContactSync', + ); + } + + void _endContactRequest() { + _contactRequestWatchdog?.cancel(); + _contactRequestWatchdog = null; + _contactRequestInFlight = false; + _contactStreamStarted = false; + _isLoadingContacts = false; + _contactSyncIsFull = false; + } + + void _armContactRequestWatchdog() { + _contactRequestWatchdog?.cancel(); + final idle = contactSyncClock().difference(_contactRequestLastActivity); + final wait = contactRequestStaleAfter - idle; + _contactRequestWatchdog = Timer( + wait.isNegative ? Duration.zero : wait, + checkStaleContactRequest, + ); + } + + /// Ends a request whose stream went silent for [contactRequestStaleAfter] + /// without END, so it cannot hold the queue or the loading state until some + /// later refresh happens to run. Nothing is pruned: an unfinished stream is + /// never a complete sync. + @visibleForTesting + void checkStaleContactRequest() { + if (!_contactRequestInFlight) return; + final idle = contactSyncClock().difference(_contactRequestLastActivity); + if (idle < contactRequestStaleAfter) { + _armContactRequestWatchdog(); + return; + } + _appDebugLogService?.warn( + 'Contact request had no reply for ${idle.inSeconds}s; ending it, saved ' + 'contacts kept', + tag: 'ContactSync', + ); + _endContactRequest(); + _hasLoadedContacts = true; + notifyListeners(); + _runQueuedContactRequest(); + } + + void _runQueuedContactRequest() { + final queued = _queuedContactRequest; + if (queued == null || _contactRequestInFlight) return; + _queuedContactRequest = null; + unawaited( + getContacts( + since: queued.since, + preserveExisting: queued.preserveExisting, + ).catchError((Object e) { + _appDebugLogService?.error( + 'Queued contact request failed to send: $e', + tag: 'ContactSync', + ); + }), + ); } Future refreshContacts() async { @@ -3382,11 +3940,313 @@ class MeshCoreConnector extends ChangeNotifier { await getContacts(since: _latestContactLastmod(), preserveExisting: true); } + /// The latest short full sync, kept until dismissed or a complete sync. + ContactSyncShortfall? get contactSyncShortfall => _contactSyncShortfall; + + /// True after the automatic retry was also short: the owner chooses between + /// keeping the local list and accepting the radio's. + bool get contactSyncDecisionPending => _contactSyncDecisionPending; + + /// Contacts the app holds that the last full sync did not deliver, i.e. what + /// "use the radio's list" would remove. + int get contactSyncUndeliveredCount => _contacts + .where((c) => !_recoveryDelivered.contains(c.publicKeyHex)) + .length; + + /// Saved contacts the radio answered "not found" for during recovery. + int get contactSyncConfirmedGoneCount => _recoveryGone.length; + + /// A full sync is complete only when the radio declared a total and at + /// least that many contacts arrived. No declared total (older firmware) is + /// unverifiable, so it is never treated as complete. + @visibleForTesting + static bool isContactSyncComplete({ + required int? declared, + required int received, + }) => declared != null && received >= declared; + + void _beginContactSync({required bool full}) { + _contactSyncIsFull = full; + _contactSyncDeclaredTotal = null; + _contactSyncDeliveredKeys.clear(); + if (full) _contactSyncDecisionPending = false; + } + + void _finishFullContactSync() { + final declared = _contactSyncDeclaredTotal; + final received = _contactSyncReceived; + _contactFullStreams++; + if (_recoveryRadioKey != selfPublicKeyHex) { + _recoveryRadioKey = selfPublicKeyHex; + _recoveryDelivered.clear(); + _recoveryGone.clear(); + } + _recoveryDelivered.addAll(_contactSyncDeliveredKeys); + if (declared != null) _recoveryDeclared = declared; + if (isContactSyncComplete(declared: declared, received: received)) { + final before = _contacts.length; + _contacts.removeWhere( + (c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex), + ); + final removed = before - _contacts.length; + if (removed > 0) { + _appDebugLogService?.info( + 'Contact sync complete ($received of $declared): removed $removed ' + 'contact(s) the radio no longer holds', + tag: 'ContactSync', + ); + } + _contactSyncShortfall = null; + _contactSyncDecisionPending = false; + _recoveryDelivered.clear(); + _recoveryGone.clear(); + // A complete sync ends any recovery still running, so a leftover by-key + // loop cannot report a shortfall against the cleared union. (Gemini) + _recoveryRun++; + _recoveryCheckingKeys = false; + _recoverySettleTimer?.cancel(); + return; + } + + final syncCount = _contactFullStreams <= contactSyncMaxFullStreams + ? 'full sync $_contactFullStreams of $contactSyncMaxFullStreams' + : 'full sync $_contactFullStreams, past the $contactSyncMaxFullStreams ' + 'automatic syncs; checking by key'; + _appDebugLogService?.warn( + 'Contact sync short: radio declared ${declared ?? 'no total'}, sent ' + '$received ($syncCount). Nothing removed.', + tag: 'ContactSync', + ); + // A user refresh during the by-key checks only adds what it delivered; + // the checks finish the run. + if (_recoveryCheckingKeys) return; + + final unionComplete = + declared != null && _recoveryDelivered.length >= declared; + if (!unionComplete && _contactFullStreams < contactSyncMaxFullStreams) { + _scheduleRecoveryStream(_recoveryRun); + return; + } + unawaited(_checkMissingContactsByKey(_recoveryRun)); + } + + void _scheduleRecoveryStream(int run) { + _recoverySettleTimer?.cancel(); + _recoveryWaitingSince = contactSyncClock(); + _recoverySettleTimer = Timer( + contactRecoverySettle, + () => _runRecoveryStreamWhenSettled(run), + ); + } + + /// Waits until the radio has been quiet for [contactRecoverySettle] and no + /// other startup sync is running, so recovery never hammers the link. + void _runRecoveryStreamWhenSettled(int run) { + if (run != _recoveryRun || !isConnected) return; + final busy = + _contactRequestInFlight || + _isSyncingChannels || + _channelSyncInFlight || + isSyncingQueuedMessages; + final quietFor = contactSyncClock().difference(_lastRadioFrameAt); + if (busy || quietFor < contactRecoverySettle) { + final waited = contactSyncClock().difference( + _recoveryWaitingSince ?? contactSyncClock(), + ); + if (waited >= contactRecoveryMaxWait) { + // Never let a busy link hide a short sync: stop waiting and let the + // owner decide, without sending anything more. (Gemini review) + _appDebugLogService?.warn( + 'Contact recovery gave up waiting for a quiet link after ' + '${waited.inSeconds}s', + tag: 'ContactSync', + ); + unawaited(_checkMissingContactsByKey(run, checkKeys: false)); + return; + } + final wait = busy + ? contactRecoverySettle + : contactRecoverySettle - quietFor; + _recoverySettleTimer = Timer( + wait < const Duration(seconds: 1) ? const Duration(seconds: 1) : wait, + () => _runRecoveryStreamWhenSettled(run), + ); + return; + } + _appDebugLogService?.info( + 'Contact recovery: full sync ${_contactFullStreams + 1} of ' + '$contactSyncMaxFullStreams', + tag: 'ContactSync', + ); + unawaited( + getContacts().catchError((Object e) { + _appDebugLogService?.error( + 'Contact recovery sync failed to send: $e', + tag: 'ContactSync', + ); + }), + ); + } + + /// After the last full sync: asks the radio, one key at a time and spaced + /// apart, about each saved contact no sync delivered. Removes only the ones + /// it answers "not found" for, and only when every declared contact has + /// been accounted for; otherwise the owner decides. + Future _checkMissingContactsByKey( + int run, { + bool checkKeys = true, + }) async { + final missing = !checkKeys + ? const [] + : _contacts + .where((c) => !_recoveryDelivered.contains(c.publicKeyHex)) + .map((c) => c.publicKey) + .toList(); + _recoveryCheckingKeys = true; + for (final key in missing) { + await Future.delayed(contactKeyCheckGap); + if (run != _recoveryRun || !isConnected) return; + final result = await checkContactOnRadio(key); + if (run != _recoveryRun) return; + final hex = pubKeyToHex(key); + if (result == ContactKeyCheckResult.onRadio) { + _recoveryDelivered.add(hex); + } else if (result == ContactKeyCheckResult.notFound) { + _recoveryGone.add(hex); + } + } + _recoveryCheckingKeys = false; + + // The latest total: a refresh during the checks may have changed it. + final declared = _recoveryDeclared; + final accounted = _recoveryDelivered.length; + if (declared != null && accounted >= declared) { + final gone = Set.of(_recoveryGone); + _contacts.removeWhere((c) => gone.contains(c.publicKeyHex)); + _appDebugLogService?.info( + 'Contact recovery complete ($accounted of $declared): removed ' + '${gone.length} contact(s) the radio no longer holds', + tag: 'ContactSync', + ); + _contactSyncShortfall = null; + _contactSyncDecisionPending = false; + notifyListeners(); + await _persistContacts(); + return; + } + + final kept = contactSyncUndeliveredCount; + _contactSyncShortfall = ContactSyncShortfall( + declared: declared, + received: accounted, + keptLocally: kept, + confirmedGone: _recoveryGone.length, + ); + _contactSyncDecisionPending = true; + final message = + 'Contact sync incomplete after $_contactFullStreams full sync(s): ' + 'radio declared ${declared ?? 'no total'}, app has $accounted. Kept ' + '$kept saved contact(s) it did not send (${_recoveryGone.length} ' + 'confirmed gone); nothing removed.'; + debugPrint(message); + _appDebugLogService?.error(message, tag: 'ContactSync'); + notifyListeners(); + } + + /// The owner chose to keep the local list after a short sync. + void resolveContactSyncKeepLocal() { + _contactSyncDecisionPending = false; + _appDebugLogService?.info( + 'Owner kept the local contact list after a short sync', + tag: 'ContactSync', + ); + notifyListeners(); + } + + /// The owner chose the radio's list after a short sync: drop what no sync on + /// this connection delivered (confirmed gone, or never sent by the radio). + Future resolveContactSyncUseRadio() async { + final removed = contactSyncUndeliveredCount; + _contacts.removeWhere((c) => !_recoveryDelivered.contains(c.publicKeyHex)); + _contactSyncDecisionPending = false; + _contactSyncShortfall = null; + _appDebugLogService?.warn( + 'Owner accepted the radio\'s contact list: removed $removed contact(s)', + tag: 'ContactSync', + ); + notifyListeners(); + await _persistContacts(); + } + + void dismissContactSyncShortfall() { + if (_contactSyncDecisionPending) return; + _contactSyncShortfall = null; + notifyListeners(); + } + Future getContactByKey(Uint8List pubKey) async { if (!isConnected) return; + _untrackedByKeyAt = contactSyncClock(); await sendFrame(buildGetContactByKeyFrame(pubKey)); } + /// Asks the radio whether it still holds [pubKey]. Only one check runs at a + /// time; a second call while one is pending returns + /// [ContactKeyCheckResult.unresolved] without sending. A timeout, a send + /// failure, a disconnect, or a NOT_FOUND that something else may own are all + /// unresolved, never [ContactKeyCheckResult.notFound]. (#762) + Future checkContactOnRadio(Uint8List pubKey) async { + if (!isConnected || _pendingKeyCheck != null) { + return ContactKeyCheckResult.unresolved; + } + final check = _PendingKeyCheck( + keyHex: pubKeyToHex(pubKey), + startedAt: contactSyncClock(), + ); + _pendingKeyCheck = check; + check.timer = Timer( + contactKeyCheckTimeout, + () => _finishKeyCheck(check, ContactKeyCheckResult.unresolved), + ); + try { + await sendFrame(buildGetContactByKeyFrame(pubKey)); + } catch (e) { + _appDebugLogService?.warn( + 'Contact check could not be sent: $e', + tag: 'ContactSync', + ); + _finishKeyCheck(check, ContactKeyCheckResult.unresolved); + } + return check.done.future; + } + + void _finishKeyCheck(_PendingKeyCheck check, ContactKeyCheckResult result) { + check.timer?.cancel(); + if (identical(_pendingKeyCheck, check)) _pendingKeyCheck = null; + if (!check.done.isCompleted) check.done.complete(result); + } + + void _resolveKeyCheckOnContact(Uint8List frame) { + final check = _pendingKeyCheck; + if (check == null || frame.length < 1 + pubKeySize) return; + if (pubKeyToHex(frame.sublist(1, 1 + pubKeySize)) == check.keyHex) { + _finishKeyCheck(check, ContactKeyCheckResult.onRadio); + } + } + + /// A NOT_FOUND belongs to the pending check only when no other request that + /// can draw an ERR is in flight, and no untracked by-key request was sent + /// since the check started. + bool _notFoundIsForKeyCheck(int errCode, _PendingKeyCheck check) { + final untracked = _untrackedByKeyAt; + return errCode == errCodeNotFound && + !_contactRequestInFlight && + !_isSyncingChannels && + !_channelSyncInFlight && + _pendingGenericAckQueue.isEmpty && + (untracked == null || untracked.isBefore(check.startedAt)); + } + Future sendMessage( Contact contact, String text, { @@ -3771,6 +4631,19 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// A strictly-increasing per-channel send timestamp (seconds), so no two + /// channel sends share a `(ts, channel_idx)` key. Required for 0xC6 hash + /// correlation (#524); harmless otherwise. + int _nextChannelSendTimestampSecs(int channelIndex) { + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final ts = monotonicChannelSendTs( + nowSecs, + _lastChannelSendTsSecs[channelIndex], + ); + _lastChannelSendTsSecs[channelIndex] = ts; + return ts; + } + Future sendChannelMessage( Channel channel, String text, { @@ -3815,7 +4688,11 @@ class MeshCoreConnector extends ChangeNotifier { await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); try { await sendFrame( - buildSendChannelTextMsgFrame(channel.index, text), + buildSendChannelTextMsgFrame( + channel.index, + text, + timestamp: _nextChannelSendTimestampSecs(channel.index), + ), channelSendQueueId: reactionQueueId, expectsGenericAck: true, ); @@ -3832,10 +4709,15 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // One monotonic timestamp shared by the outgoing message and the frame, so + // the (ts, channel) key is unique and the client can correlate it to the + // firmware packet hash via 0xC6 (#524). + final sendTsSecs = _nextChannelSendTimestampSecs(channel.index); final message = ChannelMessage.outgoing( text, _selfName ?? 'Me', channel.index, + timestampSecs: sendTsSecs, originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, @@ -3848,10 +4730,25 @@ class MeshCoreConnector extends ChangeNotifier { await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); try { await sendFrame( - buildSendChannelTextMsgFrame(channel.index, outboundText), + buildSendChannelTextMsgFrame( + channel.index, + outboundText, + timestamp: sendTsSecs, + ), channelSendQueueId: message.messageId, expectsGenericAck: true, ); + // Owner-only CoreScope observer count (#524): background, gated, and + // best-effort. Never blocks or fails the send. + if (_coreScopeQueryActive) { + unawaited( + _fetchAndStoreCoreScopeCount( + channel.index, + sendTsSecs, + message.messageId, + ), + ); + } } catch (e) { // Clear the stuck queue id and surface the failure in the chat bubble // instead of leaving the message pending and blocking the queue (#395). @@ -3909,6 +4806,48 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// Adds a contact from an identity alone: a public key, a name and a type, + /// with no advert behind it. (#627) + /// + /// This is the path behind manual key entry, a scanned QR, and a pasted + /// `meshcore://contact/add` card. It uses the stock `CMD_ADD_UPDATE_CONTACT` + /// (command 9), whose handler creates the contact outright when the key is + /// unknown, so it needs no capability gate and works on stock firmware, not + /// just Offband builds. + /// + /// Returns false when not connected. The radio answers with a generic OK, or + /// an error when its contact table is full. + Future addContactByKey(Contact stub) async { + if (!isConnected) return false; + + await sendFrame( + buildUpdateContactPathFrame( + stub.publicKey, + // No path is known, so send an empty one and let the flood sentinel + // below carry the meaning. The builder pads this to the full width. + Uint8List(0), + // Negative maps to the firmware's OUT_PATH_UNKNOWN (0xFF): flood until + // the mesh teaches us a route back. + -1, + type: stub.type, + flags: 0, + name: stub.name, + // The whole point of this path. Anything else here would trip the + // firmware advert replay guard and leave the contact permanently deaf + // to its own adverts. See buildUpdateContactPathFrame. (#620) + lastAdvert: DateTime.fromMillisecondsSinceEpoch(0), + ), + expectsGenericAck: true, + ); + + // Mirror the device write into local state, keeping lastSeen at the epoch + // so the contact continues to read as unverified until a real advert + // arrives and upgrades it. (#630) + _handleContactAdvert(stub); + notifyListeners(); + return true; + } + Future importDiscoveredContact(Contact contact) async { if (!isConnected) return; @@ -4429,6 +5368,129 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Reads the node's 64-byte identity. + /// + /// Firmware can be built without this (`ENABLE_PRIVATE_KEY_EXPORT`), in which + /// case the device answers [respCodeDisabled] and the result is + /// [IdentityTransfer.unsupported] rather than a failure. Callers must handle + /// that case: it means this radio can never do it, so retrying is pointless + /// and an export must proceed without the identity section. (#578) + Future exportPrivateKey({ + Duration timeout = const Duration(seconds: 5), + }) async { + if (!isConnected) { + return const IdentityExportResult(IdentityTransfer.noReply); + } + final existing = _identityExportCompleter; + if (existing != null && !existing.isCompleted) { + return existing.future.timeout( + timeout, + onTimeout: () => const IdentityExportResult(IdentityTransfer.noReply), + ); + } + final completer = Completer(); + _identityExportCompleter = completer; + await sendFrame(buildExportPrivateKeyFrame()); + try { + return await completer.future.timeout(timeout); + } on TimeoutException { + return const IdentityExportResult(IdentityTransfer.noReply); + } finally { + if (identical(_identityExportCompleter, completer)) { + _identityExportCompleter = null; + } + } + } + + /// Overwrites the node's identity with [identity], which must be + /// [privateKeySize] bytes. + /// + /// **This is destructive.** The node's existing identity is replaced, every + /// contact's view of this node becomes stale, and there is no undo short of + /// importing the previous key back. Callers must confirm with the user first. + /// Availability is firmware-dependent exactly as in [exportPrivateKey]. (#578) + Future importPrivateKey( + Uint8List identity, { + Duration timeout = const Duration(seconds: 5), + }) async { + if (identity.length != privateKeySize) { + throw ArgumentError.value( + identity.length, + 'identity', + 'a node identity is exactly $privateKeySize bytes', + ); + } + if (!isConnected) return IdentityTransfer.noReply; + final completer = Completer(); + _identityImportCompleter = completer; + await sendFrame(buildImportPrivateKeyFrame(identity)); + try { + return await completer.future.timeout(timeout); + } on TimeoutException { + return IdentityTransfer.noReply; + } finally { + if (identical(_identityImportCompleter, completer)) { + _identityImportCompleter = null; + } + } + } + + void _handlePrivateKey(Uint8List frame) { + final completer = _identityExportCompleter; + _identityExportCompleter = null; + if (completer == null || completer.isCompleted) return; + if (frame.length < 1 + privateKeySize) { + // A short frame is not a usable identity; report it as a refusal rather + // than handing a caller a truncated key it might write to a file. + appLogger.error( + 'RESP_CODE_PRIVATE_KEY frame too short: ${frame.length} bytes', + tag: 'Connector', + ); + completer.complete(const IdentityExportResult(IdentityTransfer.rejected)); + return; + } + // Never log the key itself. + completer.complete( + IdentityExportResult( + IdentityTransfer.ok, + Uint8List.sublistView(frame, 1, 1 + privateKeySize), + ), + ); + } + + /// RESP_CODE_DISABLED is generic: it means "that feature is not in this + /// build". Only an identity request is currently able to provoke it from us, + /// so it resolves whichever identity transfer is in flight and is otherwise + /// logged rather than silently dropped. (#578) + void _handleDisabledFrame() { + final export = _identityExportCompleter; + _identityExportCompleter = null; + if (export != null && !export.isCompleted) { + export.complete(const IdentityExportResult(IdentityTransfer.unsupported)); + return; + } + final import = _identityImportCompleter; + _identityImportCompleter = null; + if (import != null && !import.isCompleted) { + import.complete(IdentityTransfer.unsupported); + return; + } + appLogger.warn( + 'Device reported a disabled feature with no request in flight', + tag: 'Connector', + ); + } + + /// Lets an in-flight identity import claim a generic OK or ERR frame. + /// Returns true when it did, so the shared handlers can stop. (#578) + bool _completeIdentityImport(IdentityTransfer outcome) { + final completer = _identityImportCompleter; + if (completer == null || completer.isCompleted) return false; + _identityImportCompleter = null; + completer.complete(outcome); + return true; + } + void _handleOffbandGps(Uint8List frame) { if (frame.length < 2) return; final text = utf8.decode(frame.sublist(1), allowMalformed: true); @@ -4486,18 +5548,19 @@ class MeshCoreConnector extends ChangeNotifier { /// (0xC4). Sends the request and reassembles the START/CHUNK*/END stream into /// the raw captured bytes. /// - /// Throws [StateError] if a download is already in flight, + /// Returns a [CaplogDownload] carrying the reassembled bytes. A short transfer + /// is NOT an error: the result's [CaplogDownload.truncated] is set and the + /// partial [CaplogDownload.bytes] are kept so the caller can still save/share + /// them (#580). Throws [StateError] if a download is already in flight, /// [CaplogBusyException] if the device rejects because another stream is - /// already in flight, [CaplogTruncatedException] if the byte count doesn't - /// match the announced length, or [TimeoutException] if it never finishes. - /// (#430) - Future downloadCaplog({ + /// already in flight, or [TimeoutException] if it never finishes. (#430) + Future downloadCaplog({ Duration timeout = const Duration(seconds: 30), }) async { if (_caplogCompleter != null) { throw StateError('A caplog download is already in progress'); } - final completer = Completer(); + final completer = Completer(); _caplogCompleter = completer; _caplogReassembler = CaplogReassembler(); _caplogAwaitingStart = true; @@ -4560,7 +5623,14 @@ class MeshCoreConnector extends ChangeNotifier { '$_caplogChunks chunks', tag: 'Caplog', ); - completer.complete(event.bytes); + completer.complete( + CaplogDownload( + bytes: event.bytes!, + received: event.bytes!.length, + expected: event.bytes!.length, + chunks: _caplogChunks, + ), + ); break; case CaplogStatus.truncated: _appDebugLogService?.warn( @@ -4568,8 +5638,11 @@ class MeshCoreConnector extends ChangeNotifier { '${event.expected} bytes in $_caplogChunks chunks', tag: 'Caplog', ); - completer.completeError( - CaplogTruncatedException( + // Not an error: hand back the partial bytes so the caller can still + // save/share them (#580). + completer.complete( + CaplogDownload( + bytes: event.bytes!, received: event.bytes!.length, expected: event.expected!, chunks: _caplogChunks, @@ -4648,6 +5721,164 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Ask firmware for the on-air packet hash of a channel message we sent, + /// keyed by (ts, chan) (0xC6, #524). Returns null on timeout / error frame. + Future _queryPacketHash( + int ts, + int chan, { + Duration timeout = const Duration(seconds: 5), + }) async { + final key = '${ts}_$chan'; + final completer = Completer(); + _pendingPktHashCompleters[key] = completer; + final timer = Timer(timeout, () { + if (!completer.isCompleted) completer.complete(null); + }); + try { + await sendFrame(buildOffbandPktHashGetFrame(ts, chan)); + return await completer.future; + } catch (e) { + appLogger.warn('0xC6 query failed for $key: $e', tag: 'CoreScope'); + return null; + } finally { + timer.cancel(); + _pendingPktHashCompleters.remove(key); + } + } + + /// Routes a 0xC6 reply to its waiting query. Success replies echo the key; + /// error/malformed frames are logged and left for the query to time out (the + /// error frame carries no key, so it cannot be correlated). + void _handleOffbandPktHashFrame(Uint8List frame) { + final parsed = parseOffbandPktHashReply(frame); + if (parsed == null) { + appLogger.warn('0xC6 error or malformed reply', tag: 'CoreScope'); + return; + } + final key = '${parsed.timestamp}_${parsed.channelIdx}'; + final completer = _pendingPktHashCompleters[key]; + appLogger.info( + '0xC6 reply hash=${parsed.hashHex} key=$key matched=${completer != null}', + tag: 'CoreScope', + ); + if (completer != null && !completer.isCompleted) { + completer.complete(parsed); + } + } + + /// After sending a channel message, fetch its firmware hash then CoreScope's + /// observer count and stamp both on the message. Best-effort and gated; any + /// failure leaves the message showing radio-only. + /// Poll intervals (seconds) after a send: quick at first, then settle. The + /// list also caps the total window (sum ~5 min). Observer counts accrue over + /// time (the packet must propagate and be reported), so a single instant + /// query misses it. The loop also stops early once the count stabilises, no + /// increase across [_coreScopeStableChecks] consecutive polls. There is no + /// true "final" count (it only ever grows), so this is a pragmatic stop, the + /// tappable badge covers re-checking later. + static const List _coreScopePollSecs = [10, 20, 30, 60, 60, 60, 90, 90]; + static const int _coreScopeStableChecks = 3; + + Future _fetchAndStoreCoreScopeCount( + int channelIndex, + int ts, + String messageId, + ) async { + try { + appLogger.info( + 'start ts=$ts chan=$channelIndex msg=$messageId', + tag: 'CoreScope', + ); + final pkt = await _queryPacketHash(ts, channelIndex); + if (pkt == null) { + appLogger.info('no hash (0xC6 null/timeout)', tag: 'CoreScope'); + return; + } + _updateChannelMessageById( + channelIndex, + messageId, + (m) => m.copyWith(onAirHash: pkt.hashHex), + ); + var best = 0; + var flat = 0; + for (final secs in _coreScopePollSecs) { + await Future.delayed(Duration(seconds: secs)); + if (!isConnected) return; + final counts = (await _coreScopeService.fetchCounts( + pkt.hashHex, + )).counts; + if (counts == null) continue; + if (counts.observers > best) { + best = counts.observers; + flat = 0; + _updateChannelMessageById( + channelIndex, + messageId, + (m) => m.copyWith( + coreScopeObserverCount: counts.observers, + coreScopeObservationCount: counts.observations, + ), + ); + appLogger.info( + 'observers=${counts.observers} observations=${counts.observations}', + tag: 'CoreScope', + ); + notifyListeners(); + } else if (++flat >= _coreScopeStableChecks) { + return; // stabilised + } + } + } catch (e) { + appLogger.warn( + 'CoreScope observer-count fetch failed: $e', + tag: 'CoreScope', + ); + } + } + + /// Tap-to-refresh: re-query CoreScope for a message's stored on-air hash and + /// bump the counts if they grew (they only ever climb). Returns the full + /// result so the UI can distinguish found / notFound / unreachable (#571). + Future refreshCoreScopeCounts( + int channelIndex, + String messageId, + String hashHex, + ) async { + final result = await _coreScopeService.fetchCounts(hashHex); + final counts = result.counts; + if (counts != null) { + _updateChannelMessageById(channelIndex, messageId, (m) { + final current = m.coreScopeObserverCount ?? 0; + return counts.observers >= current + ? m.copyWith( + coreScopeObserverCount: counts.observers, + coreScopeObservationCount: counts.observations, + ) + : m; + }); + notifyListeners(); + } + return result; + } + + void _updateChannelMessageById( + int channelIndex, + String messageId, + ChannelMessage Function(ChannelMessage) transform, + ) { + final messages = _channelMessages[channelIndex]; + if (messages == null) return; + final i = messages.indexWhere((m) => m.messageId == messageId); + if (i >= 0) { + messages[i] = transform(messages[i]); + } else { + appLogger.warn( + 'message $messageId not found on chan $channelIndex; count dropped', + tag: 'CoreScope', + ); + } + } + /// Called when a BLOCK_LIST dump ends. A truncated dump (early-END) is /// re-requested once the link settles; never derive removals from a partial /// pull. The union reconcile against the local list is wired in B4. @@ -4813,6 +6044,7 @@ class MeshCoreConnector extends ChangeNotifier { void _handleFrameInner(List data) { if (data.isEmpty) return; _lastRxTime = DateTime.now(); + _lastRadioFrameAt = contactSyncClock(); final frame = Uint8List.fromList(data); _receivedFramesController.add(frame); @@ -4823,8 +6055,17 @@ class MeshCoreConnector extends ChangeNotifier { switch (code) { case respCodeOk: + // An identity import is confirmed by a generic OK, so it claims the + // frame before the shared handler runs. (#578) + if (_completeIdentityImport(IdentityTransfer.ok)) break; _handleOk(); break; + case respCodePrivateKey: + _handlePrivateKey(frame); + break; + case respCodeDisabled: + _handleDisabledFrame(); + break; case respCodeDeviceInfo: _handleDeviceInfo(frame); break; @@ -4840,6 +6081,9 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeOffbandCaplog: _handleOffbandCaplogFrame(frame); break; + case cmdOffbandPktHash: + _handleOffbandPktHashFrame(frame); + break; case respCodeOffbandDeviceUi: _handleDeviceUiReply(frame); break; @@ -4849,17 +6093,19 @@ class MeshCoreConnector extends ChangeNotifier { break; case respCodeContactsStart: debugPrint('Got CONTACTS_START'); - if (!_preserveContactsOnRefresh) { - _contacts.clear(); - } + _contactStreamStarted = true; + _contactRequestLastActivity = contactSyncClock(); _isLoadingContacts = true; _contactSyncReceived = 0; + _contactSyncDeliveredKeys.clear(); + _contactSyncDeclaredTotal = null; // Firmware v3+ includes total contacts after CONTACTS_START. // Incremental sync reports total contacts, not filtered result count. if (frame.length >= 5 && !_contactSyncUsesSinceFilter) { final reader = BufferReader(frame); reader.skipBytes(1); _contactSyncTotal = reader.readUInt32LE(); + _contactSyncDeclaredTotal = _contactSyncTotal; } else if (!_contactSyncUsesSinceFilter) { // Older firmwares may omit the count; use the nRF node capacity as // a conservative progress fallback instead of hiding the progress. @@ -4880,13 +6126,16 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeContact: debugPrint('Got CONTACT'); _handleContact(frame); + _resolveKeyCheckOnContact(frame); break; case respCodeEndOfContacts: debugPrint('Got END_OF_CONTACTS'); - _isLoadingContacts = false; + final wasFullSync = _contactSyncIsFull && _isLoadingContacts; + _endContactRequest(); _hasLoadedContacts = true; - _preserveContactsOnRefresh = false; _contactSyncUsesSinceFilter = false; + if (wasFullSync) _finishFullContactSync(); + _runQueuedContactRequest(); unawaited(updateKnownDiscovered()); notifyListeners(); unawaited(_persistContacts()); @@ -4995,6 +6244,10 @@ class MeshCoreConnector extends ChangeNotifier { }) => isSyncingChannels && channelSyncInFlight && !hasPendingGenericAck; void _handleErrorFrame(Uint8List frame) { + // An identity import is refused with a generic ERR (illegal argument for a + // malformed key), so it claims the frame first. (#578) + if (_completeIdentityImport(IdentityTransfer.rejected)) return; + final caplogWasAwaitingStart = _caplogAwaitingStart; // A caplog download awaiting its START frame: the firmware answers the // generic RESP_CODE_ERR when another stream (block-list / contacts / // observer config) is already in flight. Fail the download fast with a @@ -5026,6 +6279,14 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Protocol', ); + final keyCheck = _pendingKeyCheck; + if (keyCheck != null && + !caplogWasAwaitingStart && + _notFoundIsForKeyCheck(errCode, keyCheck)) { + _finishKeyCheck(keyCheck, ContactKeyCheckResult.notFound); + return; + } + // An in-flight channel GET that draws an ERR means that slot is empty, // advance to the next index the instant the ERR lands instead of waiting // out the timeout + retry budget (mirrors the CHANNEL_INFO success path @@ -5043,6 +6304,25 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // A contact request the radio refused before streaming (e.g. BAD_STATE + // while another stream runs). Only claimed when nothing else could own + // the ERR. The saved list is untouched; the request just ends. (#672) + if (_contactRequestInFlight && + !_contactStreamStarted && + !caplogWasAwaitingStart && + _pendingGenericAckQueue.isEmpty) { + _endContactRequest(); + _hasLoadedContacts = true; + _appDebugLogService?.error( + 'Radio refused the contact request (error $errCode); saved contacts ' + 'kept', + tag: 'ContactSync', + ); + notifyListeners(); + _runQueuedContactRequest(); + return; + } + if (_pendingGenericAckQueue.isEmpty) { return; } @@ -5067,8 +6347,6 @@ class MeshCoreConnector extends ChangeNotifier { if (contact != null) { _pathHistoryService!.handlePathUpdated(contact); // Refresh just this specific contact instead of all contacts. - // This avoids race conditions with _preserveContactsOnRefresh flag - // that can occur when using refreshContactsSinceLastmod(). getContactByKey(pubKey); } } @@ -5109,7 +6387,12 @@ class MeshCoreConnector extends ChangeNotifier { _telemetryModeEnv = telemetryFlag >> 2 & 0x03; _telemetryModeLoc = telemetryFlag >> 4 & 0x03; - _manualAddContacts = reader.readByte() & 0x01 == 0x00; + _manualAddContactsRaw = reader.readByte(); + // Firmware treats bit 0 as "manual add", so auto-add is on when it is + // clear (`isAutoAddEnabled()` in MyMesh.cpp). This flag therefore means + // "device is in auto-add mode", despite its name, and drives the one-shot + // default-applying pass in _checkManualAddContacts. + _manualAddContacts = _manualAddContactsRaw & 0x01 == 0x00; _currentFreqHz = reader.readUInt32LE(); _currentBwHz = reader.readUInt32LE(); @@ -5123,6 +6406,12 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); } + // The name is the other input to the channel composer's byte budget, and + // it only lands here, well after the first MTU event. Re-log so the entry + // reflects the real name length rather than the null-name worst case + // (#793). + _logComposerBudget('self-info'); + final selfName = _selfName?.trim(); if (_activeTransport == MeshCoreTransportType.usb && selfName != null && @@ -5536,12 +6825,22 @@ class MeshCoreConnector extends ChangeNotifier { secondsSinceLastRx: secSinceRx, ); if (mlTimeout != null) { - if (pathLength < 0) { - // Flood: trust ML, only enforce firmware formula as floor - if (mlTimeout < physicsMin) { - return physicsMin; - } - } + // Flood is a single firmware value, not a range: _physicsMinTimeout and + // _physicsMaxTimeout both return `500 + (16 * airtime)` for + // pathLength < 0, mirroring the firmware's calcFloodTimeoutMillisFor. + // A clamp between two equal bounds cannot preserve a prediction, so the + // model has never influenced a flood timeout in either direction. + // + // Previously written as an early return guarded by `mlTimeout < + // physicsMin`, above the comment "Flood: trust ML, only enforce firmware + // formula as floor". That described behaviour the code did not have, and + // read as though the model were consulted here. Stating the constraint + // is honest; the branch was not. Behaviour is unchanged (#533). + // + // Whether flood *should* trust a prediction is unanswered and is not + // decided here. Every round trip measured to date was 0-hop direct, so + // there is no flood data to decide it from. + if (pathLength < 0) return physicsMax; return mlTimeout.clamp(physicsMin, physicsMax); } @@ -5549,6 +6848,60 @@ class MeshCoreConnector extends ChangeNotifier { return physicsMax; } + /// Worst case the app allows *itself* to take fetching one message once the + /// radio already holds it: every `CMD_SYNC_NEXT_MESSAGE` attempt plus its + /// retries. Replies are pull-based, so this sits inside every CLI round trip. + /// + /// Derived from the retrieval constants rather than restated, so a command + /// timeout built on it cannot drift below the layer it depends on (#530). + int get messageRetrievalBudgetMs => + _queueSyncTimeoutMs * (_maxQueueSyncRetries + 1); + + /// Timeout for a repeater CLI command. + /// + /// [calculateTimeout] models **one-way delivery**: it mirrors the firmware's + /// `calcDirectTimeoutMillisFor`, whose job is to estimate when an outbound + /// packet should have been acknowledged. A CLI command is not that. It is a + /// request, an execution, and a reply, and the budget has to name all of it: + /// + /// 1. the outbound leg, which is what [calculateTimeout] is actually for; + /// 2. [cliReplyDelayMs], the fixed hold the repeater applies before it even + /// queues the reply; + /// 3. the reply's own transmission, a second packet the ACK formula never + /// modelled; + /// 4. [messageRetrievalBudgetMs], because the reply is not pushed to us. The + /// radio raises `MSG_WAITING` and we must ask for it. + /// + /// The tail is transmit scheduling, not command execution, and neither end + /// exposes it. Measured round trips to one repeater ranged from 1.65 s to + /// 20.33 s, and the *same* verb returned in both 2.31 s and 20.33 s. On the + /// 20.33 s case the repeater stamped its reply about 5 s in and the packet + /// did not reach us for another ~15 s, so the time went into queueing on + /// both radios, not into running the command: `wifi on N` only sets a + /// deadline and returns immediately (firmware `CommonCLI.cpp` "wifi on"). + /// Nothing here is a per-verb constant that could be tabulated, so the + /// retrieval term is what absorbs it. + /// + /// The reply leg uses physics only. The predictor is trained on direct-message + /// ACK latency, not on command round trips, so asking it about a reply leg + /// would be extrapolation (#534, #535). + int calculateCliTimeout({ + required int pathLength, + int messageBytes = maxFrameSize, + String? contactKey, + }) { + final outboundMs = calculateTimeout( + pathLength: pathLength, + messageBytes: messageBytes, + contactKey: contactKey, + ); + final replyLegMs = _physicsMaxTimeout( + pathLength, + _estimateAirtimeMs(messageBytes), + ); + return outboundMs + cliReplyDelayMs + replyLegMs + messageRetrievalBudgetMs; + } + /// Coalesces notifications during a bulk contact pull. /// /// Outside a pull this notifies immediately, preserving live-update @@ -5577,6 +6930,19 @@ class MeshCoreConnector extends ChangeNotifier { if (isContact && _isLoadingContacts) { _contactSyncReceived++; } + // Adverts heard mid-sync count as delivered too: the radio holds them, + // so a complete sync must not drop them just because they arrived as a + // push rather than in the contact stream. + if (_isLoadingContacts) { + _contactSyncDeliveredKeys.add(contactTmp.publicKeyHex); + _contactRequestLastActivity = contactSyncClock(); + } + // Any frame for a key proves the radio holds it now, so recovery must + // not remove it even if an earlier check said "not found". + if (_recoveryRadioKey != null) { + _recoveryGone.remove(contactTmp.publicKeyHex); + _recoveryDelivered.add(contactTmp.publicKeyHex); + } if (listEquals(contactTmp.publicKey, _selfPublicKey)) { appLogger.info( 'Ignoring contact with self public key: ${contactTmp.name}', @@ -6672,8 +8038,15 @@ class MeshCoreConnector extends ChangeNotifier { } final retryService = _retryService; + // Channel sends draw this same frame. While one is awaiting its own + // RESP_CODE_SENT the frame is ambiguous, so the retry service must not + // adopt an unpredicted hash into a direct message (#581). if (retryService != null && - retryService.updateMessageFromSent(ackHash, timeoutMs)) { + retryService.updateMessageFromSent( + ackHash, + timeoutMs, + allowUnpredictedAdoption: _pendingChannelSentQueue.isEmpty, + )) { return; } @@ -7783,6 +9156,9 @@ class MeshCoreConnector extends ChangeNotifier { _gpsLocationPollTimer?.cancel(); _radioStatsPollTimer?.cancel(); _channelsChangedDebounce?.cancel(); + _contactRequestWatchdog?.cancel(); + _pendingKeyCheck?.timer?.cancel(); + _recoverySettleTimer?.cancel(); radioStatsNotifier.dispose(); _receivedFramesController.close(); _usbManager.dispose(); @@ -8128,6 +9504,11 @@ class MeshCoreConnector extends ChangeNotifier { _autoAddRoomServers = (flags & autoAddRoomServerFlag) != 0; _autoAddSensors = (flags & autoAddSensorFlag) != 0; _overwriteOldest = (flags & autoAddOverwriteOldestFlag) != 0; + // The hop limit is the third byte. Older firmware sends a 2-byte frame, + // so its absence is normal and leaves the previous value alone. (#578) + if (frame.length > 2) { + _autoAddMaxHops = reader.readByte(); + } } catch (e) { appLogger.error('Failed to parse auto-add config: $e', tag: 'Connector'); } diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index ac3903de..42eaac68 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -2,8 +2,37 @@ import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; +// `flutter/widgets.dart` re-exports package:characters, which supplies the +// grapheme-cluster iteration used by utf8TruncateToBytes below. import 'package:flutter/widgets.dart'; +/// Encodes [s] as UTF-8, truncated to at most [maxBytes], never splitting a +/// character. (#636) +/// +/// Truncation stops on a **grapheme cluster** boundary, not a byte boundary and +/// not merely a codepoint boundary. Cutting on bytes puts invalid UTF-8 on the +/// wire, which every reader then renders as replacement characters. Cutting +/// between codepoints is valid UTF-8 but still wrong: a ZWJ emoji sequence is +/// several codepoints joined by U+200D plus a variation selector, so a +/// codepoint-safe cut can still leave a bare glyph, a dangling joiner, or an +/// orphaned selector. +/// +/// The on-wire name field is 32 bytes including a null terminator, so callers +/// pass 31. That holds roughly 10 CJK characters, or two ZWJ emoji. +Uint8List utf8TruncateToBytes(String s, int maxBytes) { + if (maxBytes <= 0) return Uint8List(0); + final whole = utf8.encode(s); + if (whole.length <= maxBytes) return Uint8List.fromList(whole); + + final out = []; + for (final cluster in s.characters) { + final encoded = utf8.encode(cluster); + if (out.length + encoded.length > maxBytes) break; + out.addAll(encoded); + } + return Uint8List.fromList(out); +} + // Buffer Reader - sequential binary data reader with pointer tracking class BufferReader { int _pointer = 0; @@ -132,8 +161,10 @@ class BufferWriter { void writeCString(String string, int maxLength) { final bytes = Uint8List(maxLength); - final encoded = utf8.encode(string); - for (var i = 0; i < maxLength - 1 && i < encoded.length; i++) { + // Grapheme-safe: a raw byte copy would cut a multi-byte character in half + // and put invalid UTF-8 on the wire. (#636) + final encoded = utf8TruncateToBytes(string, maxLength - 1); + for (var i = 0; i < encoded.length; i++) { bytes[i] = encoded[i]; } writeBytes(bytes); @@ -213,6 +244,17 @@ const int cmdSetAutoAddConfig = 58; const int cmdGetAutoAddConfig = 59; const int cmdSetPathHashMode = 61; +/// Read the node's 64-byte identity. Compiled out of some firmware builds +/// (`ENABLE_PRIVATE_KEY_EXPORT`), in which case the device answers +/// [respCodeDisabled] rather than [respCodePrivateKey]. (#578) +const int cmdExportPrivateKey = 23; + +/// Overwrite the node's identity with a 64-byte key. Like the export command +/// this can be compiled out (`ENABLE_PRIVATE_KEY_IMPORT`). Firmware validates +/// the key and answers [respCodeErr] with [errCodeIllegalArg] if it is +/// malformed. (#578) +const int cmdImportPrivateKey = 24; + // Text message types const int txtTypePlain = 0; const int txtTypeCliData = 1; @@ -256,6 +298,18 @@ const int respCodeCustomVars = 21; const int respCodeAutoAddConfig = 25; const int respCodeStats = 24; +/// Reply to [cmdExportPrivateKey]: this byte followed by +/// [privateKeySize] bytes. (#578) +const int respCodePrivateKey = 14; + +/// One-byte reply meaning the firmware was built without the requested +/// feature. Distinct from [respCodeErr], which reports a runtime failure of a +/// command the firmware does support. (#578) +const int respCodeDisabled = 15; + +/// A node identity is 64 bytes: the Ed25519 secret followed by its public key. +const int privateKeySize = 64; + /// Offband fork-only extension space (0xC0+), never collides with upstream, /// never submitted upstream. Request and reply share the code. (#135) const int cmdOffbandGps = 0xC1; @@ -279,6 +333,13 @@ const int offbandFemLnaGet = 0x02; const int femLnaBypass = 0x00; const int femLnaEnabled = 0x01; +/// Fixed delay a repeater applies before queueing a CLI reply for transmit. +/// +/// Firmware `CLI_REPLY_DELAY_MILLIS` in `examples/simple_repeater/MyMesh.cpp`, +/// applied on both the direct and the flood reply path. It is unconditional, so +/// every CLI round trip pays it and any budget for one must include it. +const int cliReplyDelayMs = 600; + Uint8List buildOffbandFemLnaSetFrame(bool enabled) => Uint8List.fromList([ cmdOffbandFemLna, offbandFemLnaSet, @@ -432,6 +493,10 @@ const int errCodeIllegalArg = 6; /// it defensively against a stale or mis-gated client. (#304) const int errCodeUnsupportedCmd = 1; +/// `ERR_CODE_NOT_FOUND`: e.g. `CMD_GET_CONTACT_BY_KEY` for a key the radio does +/// not hold. (#762) +const int errCodeNotFound = 2; + Uint8List buildOffbandBlockAddFrame(Uint8List pubKey) => Uint8List.fromList([cmdOffbandBlock, offbandBlockAdd, ...pubKey]); Uint8List buildOffbandBlockRemoveFrame(Uint8List pubKey) => @@ -533,6 +598,75 @@ bool firmwareSupportsOffbandCaplog(int? offbandCaps, int? firmwareVerCode) => (offbandCaps & offbandCapCaplog) != 0 && (firmwareVerCode ?? 0) >= 17; +/// Packet-hash query capability (firmware #611, cap byte 2 bit 3). Lets the +/// client ask firmware for the authoritative on-air hash of a channel message +/// it sent, keyed by (msg_timestamp, channel_idx), to correlate against +/// CoreScope observer counts (#524). Allocation provisional until the firmware +/// PR merges; confirm against it before release. +const int offbandCap2PktHash = 0x08; + +/// True iff this radio supports the 0xC6 packet-hash query. Requires both the +/// cap-byte-2 bit AND FIRMWARE_VER_CODE >= 22. The client must never emit 0xC6 +/// unless this is true. +bool firmwareSupportsPktHash(int? offbandCaps2, int? firmwareVerCode) => + offbandCaps2 != null && + (offbandCaps2 & offbandCap2PktHash) != 0 && + (firmwareVerCode ?? 0) >= 22; + +/// 0xC6 CMD_OFFBAND_PKT_HASH (firmware #611). Client-issued query, never a push; +/// the stock channel-send OK reply is untouched. +const int cmdOffbandPktHash = 0xC6; +const int pktHashReqGet = 0x01; +const int pktHashRespGet = 0x01; +const int pktHashRespErr = 0x7F; + +/// Build a 0xC6 GET request for the hash of a sent channel message, keyed by +/// the (msg_timestamp, channel_idx) the client used in CMD_SEND_CHANNEL_TXT_MSG. +/// Wire: [0xC6][0x01][ts:4 LE][chan:1] = 7 bytes. +Uint8List buildOffbandPktHashGetFrame(int msgTimestamp, int channelIdx) { + final frame = Uint8List(7); + frame[0] = cmdOffbandPktHash; + frame[1] = pktHashReqGet; + ByteData.sublistView(frame, 2, 6).setUint32(0, msgTimestamp, Endian.little); + frame[6] = channelIdx & 0xFF; + return frame; +} + +/// A parsed 0xC6 success reply: the on-air packet hash plus the echoed key, +/// so a reply can be matched to its request without relying on ordering. +class OffbandPktHash { + const OffbandPktHash({ + required this.timestamp, + required this.channelIdx, + required this.hashHex, + }); + + /// msg_timestamp echoed from the request. + final int timestamp; + + /// channel_idx echoed from the request. + final int channelIdx; + + /// 16 lowercase hex chars, matching CoreScope's hash and the client's own + /// [_computePacketHash] format. + final String hashHex; +} + +/// Parse a 0xC6 reply. Returns the hash on a success reply +/// ([0xC6][0x01][ts:4][chan:1][hash:8], 15 bytes), or null on the error reply +/// ([0xC6][0x7F][reason]) or any malformed frame. +OffbandPktHash? parseOffbandPktHashReply(Uint8List frame) { + if (frame.length < 15) return null; + if (frame[0] != cmdOffbandPktHash || frame[1] != pktHashRespGet) return null; + final ts = ByteData.sublistView(frame, 2, 6).getUint32(0, Endian.little); + final chan = frame[6]; + final hashHex = frame + .sublist(7, 15) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(); + return OffbandPktHash(timestamp: ts, channelIdx: chan, hashHex: hashHex); +} + const int statsTypeCore = 0; const int statsTypeRadio = 1; const int statsTypePackets = 2; @@ -588,6 +722,9 @@ const int payloadTypeRawCustom = 0x0F; // custom packet as raw bytes, for applications with custom encryption, payloads, etc //auto-add flags +/// Firmware clamps `autoadd_max_hops` to this value. 0 means no limit. (#578) +const int autoAddMaxHopsLimit = 64; + const int autoAddOverwriteOldestFlag = 1 << 0; // 0x01 - overwrite oldest non-favourite when full const int autoAddChatFlag = @@ -637,6 +774,23 @@ int maxChannelMessageBytes(String? senderName, {int? maxFrameBytes}) { return _minPositive(byPayload, byFrame); } +/// Fewest bytes a composer needs before it is worth calling usable. +/// +/// Judgement call, not a protocol constant: below this a user cannot say +/// anything meaningful, so an apparently-normal text field is misleading and +/// the guard in #684 explains itself instead. Deliberately larger than the +/// degenerate values #592 produced (DM 4, channel 1 or 0) so the guard also +/// catches the near-miss cases, not only the literal zero. +const int minUsableComposerBytes = 16; + +/// Whether [maxBytes] leaves a composer able to carry a real message. +/// +/// A budget of 0 rejects every keystroke, which is the #592 symptom that read +/// as a dead keyboard. A budget of 1-15 accepts input but cannot carry a +/// sentence. Both are cases the user must be told about rather than left to +/// discover by typing into a field that ignores them (SAFELANE 6). +bool isComposerBudgetUsable(int maxBytes) => maxBytes >= minUsableComposerBytes; + int _senderNameBytes(String? senderName) { if (senderName == null || senderName.isEmpty) return maxNameSize - 1; final bytes = utf8.encode(senderName); @@ -889,13 +1043,19 @@ Uint8List buildSendTextMsgFrame( // Build CMD_SEND_CHANNEL_TXT_MSG frame // Format: [cmd][txt_type][channel_idx][timestamp x4][text...] -Uint8List buildSendChannelTextMsgFrame(int channelIndex, String text) { - final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; +// [timestamp] (seconds) may be supplied by the caller so it can correlate the +// send to the firmware packet hash (0xC6, #524); defaults to now. +Uint8List buildSendChannelTextMsgFrame( + int channelIndex, + String text, { + int? timestamp, +}) { + final ts = timestamp ?? DateTime.now().millisecondsSinceEpoch ~/ 1000; final writer = BufferWriter(); writer.writeByte(cmdSendChannelTxtMsg); writer.writeByte(txtTypePlain); writer.writeByte(channelIndex); - writer.writeUInt32LE(timestamp); + writer.writeUInt32LE(ts); writer.writeString(text); writer.writeByte(0); return writer.toBytes(); @@ -983,13 +1143,14 @@ Uint8List buildSendSelfAdvertFrame({bool flood = false}) { // Build CMD_SET_ADVERT_NAME frame // Format: [cmd][name...] Uint8List buildSetAdvertNameFrame(String name) { - final nameBytes = utf8.encode(name); - final nameLen = nameBytes.length < maxNameSize - ? nameBytes.length - : maxNameSize - 1; + // Grapheme-safe. This one matters most of the three: it sets THIS device's + // own advert name, which is what every other node on the mesh sees, what is + // embedded in the contact cards this device emits, and what other clients + // match against. Corrupt it once and the corruption propagates outward. + // (#636) final writer = BufferWriter(); writer.writeByte(cmdSetAdvertName); - writer.writeBytes(Uint8List.fromList(nameBytes.sublist(0, nameLen))); + writer.writeBytes(utf8TruncateToBytes(name, maxNameSize - 1)); return writer.toBytes(); } @@ -1046,7 +1207,8 @@ Uint8List buildSetChannelFrame(int channelIndex, String name, Uint8List psk) { // Build CMD_SET_RADIO_PARAMS frame // Format: [cmd][freq x4][bw x4][sf][cr] (pre-v9) // [cmd][freq x4][bw x4][sf][cr][repeat] (firmware v9+) -// freq: frequency in Hz (300000-2500000) +// freq: frequency in kHz despite the parameter name (stock firmware stores +// freq / 1000.0 as MHz and accepts 150000-2500000) // bw: bandwidth in Hz (7000-500000) // sf: spreading factor (5-12) // cr: coding rate (5-8) @@ -1106,6 +1268,7 @@ Uint8List buildUpdateContactPathFrame( double? lat, double? lon, DateTime? lastModified, + DateTime? lastAdvert, }) { final writer = BufferWriter(); writer.writeByte(cmdAddUpdateContact); @@ -1120,9 +1283,20 @@ Uint8List buildUpdateContactPathFrame( // Name (32 bytes, null-padded) writer.writeCString(name, maxNameSize); - // Timestamp - final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000; - writer.writeUInt32LE(timestamp); + // Mandatory last_advert_timestamp. Defaults to now, which is right for the + // path-update callers: they refresh a contact the radio already learned from + // a real advert. + // + // A key-only add MUST pass the epoch instead (#627). The firmware compares + // this field against every incoming advert with + // `timestamp <= last_advert_timestamp` and silently discards the non-greater + // ones as replay attacks (`BaseChatMesh.cpp:142-145`). Advert timestamps come + // from the SENDER's clock, and clocks in the field run years behind, so + // stamping "now" on a contact that has never adverted would leave it + // permanently deaf to its own adverts. Zero lets any genuine advert win. + final advertSeconds = + (lastAdvert ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000; + writer.writeUInt32LE(advertSeconds < 0 ? 0 : advertSeconds); // Optional [Lat x4, Lon x4][timestamp x4] tail per the doc comment above. // Emit 8 bytes of position (zero-filled when only lastModified is provided) @@ -1326,6 +1500,7 @@ Uint8List buildSetAutoAddConfigFrame({ required bool autoAddRoomServer, required bool autoAddSensor, required bool overwriteOldest, + int? maxHops, }) { final writer = BufferWriter(); writer.writeByte(cmdSetAutoAddConfig); @@ -1336,6 +1511,32 @@ Uint8List buildSetAutoAddConfigFrame({ if (autoAddSensor) flags |= autoAddSensorFlag; if (overwriteOldest) flags |= autoAddOverwriteOldestFlag; writer.writeByte(flags); + // Firmware applies the hop limit only when the frame carries a third byte, + // so omitting [maxHops] leaves the device's current limit untouched. It + // clamps to [autoAddMaxHopsLimit] on its side; we clamp here too so the + // value we believe we sent is the value that lands. (#578) + if (maxHops != null) { + writer.writeByte(maxHops.clamp(0, autoAddMaxHopsLimit)); + } + return writer.toBytes(); +} + +/// Request the node's identity. See [cmdExportPrivateKey] for availability. +Uint8List buildExportPrivateKeyFrame() => + Uint8List.fromList([cmdExportPrivateKey]); + +/// Overwrite the node's identity. [identity] must be [privateKeySize] bytes. +Uint8List buildImportPrivateKeyFrame(Uint8List identity) { + if (identity.length != privateKeySize) { + throw ArgumentError.value( + identity.length, + 'identity', + 'a node identity is exactly $privateKeySize bytes', + ); + } + final writer = BufferWriter(); + writer.writeByte(cmdImportPrivateKey); + writer.writeBytes(identity); return writer.toBytes(); } diff --git a/lib/connector/observer_config_client.dart b/lib/connector/observer_config_client.dart index 39a460dd..0edfb30e 100644 --- a/lib/connector/observer_config_client.dart +++ b/lib/connector/observer_config_client.dart @@ -241,12 +241,17 @@ class ObserverConfigClient { } } - /// Extract the value from a scalar reply ("key = value\n" → "value"). - /// Falls back to the trimmed whole string if there's no " = ". + /// Extract the value from a scalar reply (`key = value` -> `value`). + /// + /// Splits on the FIRST `=` (config keys never contain `=`; values may). A + /// blank field replies `key =` with nothing after the `=`, so the old + /// ` = ` (space-equals-space) match failed and leaked the whole `key =` line + /// as the value (#469). Splitting on `=` and trimming handles blank values + /// (-> empty) and values containing `=` correctly. static String extractScalarValue(String reply) { - final trimmed = reply.replaceAll('\n', '').trimRight(); - final i = trimmed.indexOf(' = '); - return i < 0 ? trimmed : trimmed.substring(i + 3); + final line = reply.replaceAll('\n', ''); + final i = line.indexOf('='); + return i < 0 ? line.trim() : line.substring(i + 1).trim(); } /// Read a NUL-terminated UTF-8 string from [f] starting at [start]. diff --git a/lib/helpers/channel_send_timestamp.dart b/lib/helpers/channel_send_timestamp.dart new file mode 100644 index 00000000..07ac5a34 --- /dev/null +++ b/lib/helpers/channel_send_timestamp.dart @@ -0,0 +1,17 @@ +/// Returns a channel-send timestamp (Unix seconds) strictly greater than +/// [lastSecs] for the same channel, so no two sends on one channel ever share a +/// `(ts, channel_idx)` key. +/// +/// This is a correctness requirement for the 0xC6 packet-hash correlation +/// (#524/#611): `msg_timestamp` is only second-resolution and MeshCore channel +/// encryption is deterministic (AES-128-ECB), so two different messages on the +/// same channel within one second would otherwise map to the same key but +/// different hashes, and the client would query CoreScope with the wrong hash. +/// +/// Uses [nowSecs] unless it would collide with or precede [lastSecs], in which +/// case it bumps to `lastSecs + 1`. Mirrors the firmware's own +/// `getCurrentTimeUnique()`. +int monotonicChannelSendTs(int nowSecs, int? lastSecs) { + if (lastSecs != null && nowSecs <= lastSecs) return lastSecs + 1; + return nowSecs; +} diff --git a/lib/helpers/remote_radio_commands.dart b/lib/helpers/remote_radio_commands.dart new file mode 100644 index 00000000..06059e2e --- /dev/null +++ b/lib/helpers/remote_radio_commands.dart @@ -0,0 +1,102 @@ +import '../models/radio_preset.dart'; + +// Radio presets on remote nodes (repeater, room server, sensor) through the +// stock admin CLI (#733). Kept out of the screen so it can be tested. + +/// Default `tempradio` duration (owner decision on #662). +const int kTempRadioDefaultMinutes = 1440; + +/// Longest `tempradio` duration that works. Firmware schedules the revert at +/// `futureMillis(2000 + timeout_mins * 60 * 1000)` in a 32-bit int +/// (simple_repeater/MyMesh.cpp), which overflows past this. +const int kTempRadioMaxMinutes = 35791; + +String _bandwidthKHz(int bandwidthHz) => '${bandwidthHz / 1000}'; + +/// Stock CLI: persist radio params (applied after a reboot). +String setRadioCommand( + String frequencyText, + int bandwidthHz, + int spreadingFactor, + int codingRate, +) => + 'set radio $frequencyText,${_bandwidthKHz(bandwidthHz)},' + '$spreadingFactor,$codingRate'; + +/// Stock CLI: apply radio params now, reverting after [minutes]. Nothing is +/// saved on the node. Coding rate is the 4/x denominator (4/5 is 5), which +/// is what firmware range-checks (5-8). +String tempRadioCommand( + String frequencyText, + int bandwidthHz, + int spreadingFactor, + int codingRate, + int minutes, +) => + 'tempradio $frequencyText,${_bandwidthKHz(bandwidthHz)},' + '$spreadingFactor,$codingRate,$minutes'; + +/// A valid `tempradio` duration in minutes (1 to [kTempRadioMaxMinutes]), +/// or null. +int? parseTempRadioMinutes(String text) { + final minutes = int.tryParse(text.trim()); + if (minutes == null || minutes < 1 || minutes > kTempRadioMaxMinutes) { + return null; + } + return minutes; +} + +/// `tempradio` retunes the node 2 s after it replies, so anything sent after +/// it in the same save would go out on the old frequency. Keep the original +/// order otherwise, with retuning commands moved to the end. +List withRetuneLast(List commands, bool Function(T) retunes) => [ + ...commands.where((c) => !retunes(c)), + ...commands.where(retunes), +]; + +bool isRetuneCommand(String command) => command.startsWith('tempradio '); + +/// Stock CLI: path hash mode, zero-based (2 bytes = mode 1). +String setPathHashModeCommand(int mode) => 'set path.hash.mode $mode'; + +/// Whether a path hash that came from a preset goes out in this save (#735). +/// Firmware has no temporary path hash, so with a temporary radio change it +/// would outlive the revert; it stays pending for a normal save instead. A +/// path hash the user set by hand is always sent. +bool sendsPresetPathHash({ + required bool temporaryRadio, + required bool pathHashFromPreset, +}) => !(temporaryRadio && pathHashFromPreset); + +/// The preset whose radio values match the form's, or null for custom values. +/// The form holds frequency as text (the repeater reports e.g. "908.205017"), +/// so frequency matches to the nearest kHz. TX power is not compared: the +/// remote screen sets it separately. A preset with a path hash only matches +/// a node on that mode (#747): MeshCore's "Canada" and "USA" differ only there. +String? matchRemotePresetId( + List presets, { + required String frequencyText, + required int? bandwidthHz, + required int? spreadingFactor, + required int? codingRate, + required int pathHashMode, +}) { + final mhz = double.tryParse(frequencyText.trim()); + if (mhz == null || + bandwidthHz == null || + spreadingFactor == null || + codingRate == null) { + return null; + } + final khz = (mhz * 1000).round(); + for (final p in presets) { + if (p.frequencyKHz == khz && + p.bandwidth.hz == bandwidthHz && + p.spreadingFactor.value == spreadingFactor && + p.codingRate.value == codingRate && + presetPathHashMatches(p, pathHashMode + 1)) { + return p.id; + } + } + return null; +} diff --git a/lib/helpers/snack_bar_builder.dart b/lib/helpers/snack_bar_builder.dart index d7409b6d..1c5626ed 100644 --- a/lib/helpers/snack_bar_builder.dart +++ b/lib/helpers/snack_bar_builder.dart @@ -1,56 +1,25 @@ import 'package:flutter/material.dart'; -// showDismissibleSnackBar shows a [SnackBar] with tap to dismiss -// all other properties are default and optional +import '../widgets/top_toast.dart'; + +/// Shows a transient notification that dismisses on tap, on an upward swipe, +/// or after [duration]. +/// +/// Kept under its original name so existing call sites are unchanged; the +/// notification itself moved from a bottom [SnackBar] to a top-anchored +/// overlay (#638), because the bottom placement covered the chat composer. void showDismissibleSnackBar( BuildContext context, { - Key? key, required Widget content, Color? backgroundColor, - double? elevation, - EdgeInsetsGeometry? margin, - EdgeInsetsGeometry? padding, - double? width, - ShapeBorder? shape, - HitTestBehavior? hitTestBehavior, - SnackBarBehavior? behavior, - SnackBarAction? action, - double? actionOverflowThreshold, - bool? showCloseIcon, - Color? closeIconColor, Duration? duration, bool? persist, - Animation? animation, - void Function()? onVisible, - DismissDirection? dismissDirection, - Clip? clipBehavior, }) { - final messenger = ScaffoldMessenger.of(context); - messenger.showSnackBar( - SnackBar( - key: key, - content: GestureDetector( - onTap: () => messenger.hideCurrentSnackBar(), - child: content, - ), - backgroundColor: backgroundColor, - elevation: elevation, - margin: margin, - padding: padding, - width: width, - shape: shape, - hitTestBehavior: hitTestBehavior, - behavior: behavior, - action: action, - actionOverflowThreshold: actionOverflowThreshold, - showCloseIcon: showCloseIcon, - closeIconColor: closeIconColor, - duration: duration ?? const Duration(seconds: 4), - persist: persist, - animation: animation, - onVisible: onVisible, - dismissDirection: dismissDirection ?? DismissDirection.down, - clipBehavior: clipBehavior ?? Clip.hardEdge, - ), + TopToast.show( + context, + content: content, + backgroundColor: backgroundColor, + duration: duration ?? TopToast.defaultDuration, + persist: persist ?? false, ); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 83b522ad..fdf9b684 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -134,6 +134,26 @@ "scanner_scan": "Scan", "scanner_bluetoothOff": "Bluetooth is off", "scanner_bluetoothOffMessage": "Please turn on Bluetooth to scan for devices", + "scanner_connectFailedTransient": "The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.", + "@scanner_connectFailedTransient": { + "description": "Human-readable text for an Android GATT 133 connect failure after the bounded retry also failed (#698)." + }, + "scanner_connectFailedTimeout": "The connection timed out. Check that the radio is powered, in range, and not already connected to another device.", + "@scanner_connectFailedTimeout": { + "description": "Human-readable text for a connect timeout (#698)." + }, + "scanner_connectFailedGeneric": "Could not connect to the radio. Details are in the App Debug Log.", + "@scanner_connectFailedGeneric": { + "description": "Human-readable fallback for any other connect failure; the raw exception goes to the log only (#522/#698)." + }, + "scanner_bleReleaseWarning": "Radio may still be held by this device", + "@scanner_bleReleaseWarning": { + "description": "Persistent banner title when a BLE disconnect was never confirmed by the OS, so the radio may stay latched and stop advertising (#697)." + }, + "scanner_bleReleaseWarningMessage": "The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.", + "@scanner_bleReleaseWarningMessage": { + "description": "Persistent banner body naming the recovery for an unconfirmed BLE release (#697)." + }, "scanner_chromeRequired": "Chrome Browser Required", "scanner_chromeRequiredMessage": "This web application requires Google Chrome or a Chromium-based browser for Bluetooth support.", "scanner_enableBluetooth": "Enable Bluetooth", @@ -215,6 +235,24 @@ "settings_rebootDeviceSubtitle": "Restart the MeshCore device", "settings_rebootDeviceConfirm": "Are you sure you want to reboot the device? You will be disconnected.", "settings_debug": "Debug", + "settings_experimental": "Experimental", + "settings_experimentalSubtitle": "Advanced and in-development features", + "settings_experimentalDescription": "These features are experimental and may change or be removed at any time. They default to off.", + "settings_coreScopeObserverCount": "CoreScope observer counts", + "settings_coreScopeObserverCountSubtitle": "On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.", + "settings_coreScopeObserverCountUnsupported": "Requires a firmware build with packet-hash support (v22+).", + "settings_experimentalDisable": "Disable experimental features", + "settings_experimentalDisableSubtitle": "Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.", + "settings_experimentalUnlocked": "Experimental features unlocked", + "settings_experimentalAlreadyUnlocked": "Experimental features are already unlocked", + "settings_experimentalCountdown": "{count} more taps to unlock experimental features", + "@settings_experimentalCountdown": { + "placeholders": { + "count": { + "type": "int" + } + } + }, "settings_companionDebugLog": "Companion Debug Log", "settings_companionDebugLogSubtitle": "BLE/TCP/USB commands, responses, and raw data", "settings_appDebugLog": "App Debug Log", @@ -228,9 +266,15 @@ } } }, - "settings_aboutLegalese": "2026 MeshCore Open Source Project", - "settings_aboutDescription": "An open-source Flutter client for MeshCore LoRa mesh networking devices.", + "settings_aboutLegalese": "© 2026 Offband. Based on MeshCore Open by zjs81, MIT licensed.", + "settings_aboutDescription": "Offband Meshcore is an open-source client for MeshCore LoRa mesh networking devices.", + "settings_aboutLicenses": "View licenses", + "settings_aboutWebsite": "Offband website", + "settings_aboutPlayStore": "Google Play", + "settings_aboutDonate": "Donate or sponsor", + "settings_aboutLinkFailed": "Could not open the link", "settings_aboutOpenMeteoAttribution": "LOS elevation data: Open-Meteo (CC BY 4.0)", + "settings_aboutPresetsAttribution": "Regional radio presets: MeshCore's suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.", "settings_infoName": "Name", "settings_infoId": "ID", "settings_infoStatus": "Status", @@ -246,6 +290,20 @@ "settings_infoContactsCount": "Contacts Count", "settings_infoChannelCount": "Channel Count", "settings_presets": "Presets", + "settings_presetSourceMeshCore": "MeshCore", + "settings_presetSourceOffband": "Offband", + "settings_presetsRefresh": "Update presets", + "settings_presetsUpdating": "Updating presets...", + "settings_presetsUpdateFailed": "Couldn't update presets. Showing the saved list.", + "settings_presetsUpdatedAt": "Presets updated {date}", + "@settings_presetsUpdatedAt": { + "placeholders": { + "date": { + "type": "String" + } + } + }, + "settings_presetsBundled": "Presets included with this version of the app", "settings_frequency": "Frequency (MHz)", "settings_frequencyHelper": "300.0 - 2500.0", "settings_frequencyInvalid": "Invalid frequency (300-2500 MHz)", @@ -483,6 +541,7 @@ } }, "contacts_manageRepeater": "Manage Repeater", + "contacts_manageSensor": "Manage Sensor", "contacts_manageRoom": "Manage Room Server", "contacts_roomLogin": "Room Server Login", "contacts_openChat": "Open Chat", @@ -721,6 +780,17 @@ } } }, + "composerBudgetBlockedTitle": "Can't send messages on this connection", + "composerBudgetLimitedTitle": "Only {maxBytes} characters will fit", + "@composerBudgetLimitedTitle": { + "placeholders": { + "maxBytes": { + "type": "int" + } + } + }, + "composerBudgetBluetoothCause": "The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.", + "composerBudgetGenericCause": "The connection to the radio left no room for message text. Try reconnecting.", "chat_messageCopied": "Message copied", "chat_messageDeleted": "Message deleted", "chat_retryingMessage": "Retrying message", @@ -858,6 +928,59 @@ } } }, + "channel_coreScopeTooltip": "Seen by {count, plural, =1{1 CoreScope observer} other{{count} CoreScope observers}}", + "@channel_coreScopeTooltip": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "channel_coreScopeRefresh": "Refresh CoreScope observers", + "channel_coreScopeRefreshFailed": "CoreScope unreachable", + "channel_coreScopeNotFound": "Not seen by CoreScope yet", + "channel_coreScopeCounts": "{observers, plural, =1{1 observer} other{{observers} observers}} · {observations} observations", + "@channel_coreScopeCounts": { + "placeholders": { + "observers": { + "type": "int" + }, + "observations": { + "type": "int" + } + } + }, + "channel_senderNameUnknown": "No node known by that name", + "channel_senderNameUnknownHint": "Adding needs an advert from this node", + "channel_senderAlreadyContact": "Already in contacts", + "channel_senderMultipleMatches": "{count} nodes use this name", + "@channel_senderMultipleMatches": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "channel_senderAddNotConnected": "Not connected to a radio, so this sender can't be added yet", + "channel_senderAddFailed": "Couldn't add this sender: {error}", + "@channel_senderAddFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "channel_senderCandidate": "{keyPrefix} · {type}", + "@channel_senderCandidate": { + "placeholders": { + "keyPrefix": { + "type": "String" + }, + "type": { + "type": "String" + } + } + }, "chat_successes": "successes", "chat_score": "Score", "chat_removePath": "Remove path", @@ -1337,6 +1460,18 @@ "repeater_bandwidth": "Bandwidth", "repeater_spreadingFactor": "Spreading Factor", "repeater_codingRate": "Coding Rate", + "repeater_tempRadio": "Apply temporarily", + "repeater_tempRadioSubtitle": "Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.", + "repeater_tempRadioMinutes": "Duration (minutes)", + "repeater_tempRadioPathHashNote": "This preset's path hash size isn't applied with a temporary change: the node can't revert it on its own. It stays pending for a normal save.", + "repeater_tempRadioMinutesInvalid": "1 to {max} minutes", + "@repeater_tempRadioMinutesInvalid": { + "placeholders": { + "max": { + "type": "int" + } + } + }, "repeater_locationSettings": "Location Settings", "repeater_latitude": "Latitude", "repeater_latitudeHelper": "Decimal degrees (e.g., 37.7749)", @@ -1522,6 +1657,14 @@ } } }, + "repeater_cliCommandTimeout": "Command timed out after {seconds} seconds", + "@repeater_cliCommandTimeout": { + "placeholders": { + "seconds": { + "type": "String" + } + } + }, "repeater_cliQuickGetName": "Get Name", "repeater_cliQuickGetRadio": "Get Radio", "repeater_cliQuickGetTx": "Get TX", @@ -2396,6 +2539,56 @@ "contacts_floodAdvert": "Flood Advert", "contacts_copyAdvertToClipboard": "Copy Advert to Clipboard", "contacts_addContactFromClipboard": "Add Contact from Clipboard", + "contacts_addByKey": "Add by public key", + "contacts_addByKeyDescription": "Add someone using the public key they gave you. Works even if you have never heard their advert.", + "contacts_publicKeyLabel": "Public key", + "contacts_publicKeyHelper": "64 hex characters, or paste a meshcore:// contact link", + "contacts_publicKeyInvalid": "Enter 64 hex characters, or a meshcore:// contact link", + "contacts_nameLabel": "Name", + "contacts_typeLabel": "Type", + "contacts_addByKeyUnverifiedNote": "Not confirmed on air yet. The name is whatever you type here until this node sends an advert.", + "contacts_addByKeyAdded": "Added {name}", + "@contacts_addByKeyAdded": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "contacts_addByKeyFailed": "Could not add the contact. Check the radio connection.", + "contacts_myContactQr": "My contact QR", + "contacts_myContactQrInstructions": "Have them scan this, or send them the link below. It works even if they have never heard your advert.", + "contacts_contactLinkCopied": "Contact link copied", + "contacts_qrNeedsConnection": "Connect to a radio first, so the app knows your public key.", + "contacts_scanContactQr": "Scan contact QR", + "contacts_scanContactQrInstructions": "Point the camera at a MeshCore contact QR", + "contacts_invalidContactQr": "That QR is not a MeshCore contact", + "contacts_verifiedByAdvert": "Confirmed on air. This node sent a signed advert.", + "contacts_verifiedByMessage": "Key confirmed. A message with this contact went through, which only works with the matching key.", + "contacts_verifiedKeyOnly": "Added from a key. Nothing has confirmed it on air yet.", + "contacts_lastSeenNever": "Not heard yet", + "contacts_cardAddContact": "Add {name}", + "@contacts_cardAddContact": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "contacts_cardAlreadyAdded": "{name}", + "@contacts_cardAlreadyAdded": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "contacts_cardAlreadyAddedTooltip": "Already in your contacts", + "chat_attachTooltip": "Add to message", + "chat_attachGif": "GIF", + "chat_attachMyContact": "My contact card", + "chat_attachMyContactSubtitle": "Puts your public key in the message so anyone here can add you", + "chat_contactCardNeedsConnection": "Connect to a radio first, so the app knows your public key.", "contacts_ShareContact": "Copy contact to Clipboard", "contacts_ShareContactZeroHop": "Share contact by advert", "contacts_zeroHopContactAdvertSent": "Sent contact by advert.", @@ -2689,5 +2882,312 @@ "batteryOptimizationOpenFailed": "Couldn't open battery settings", "@batteryOptimizationOpenFailed": { "description": "Snackbar shown when the battery-optimization settings screen could not be opened (#443)." + }, + "stockConfig_selectAll": "Select All", + "@stockConfig_selectAll": { + "description": "Button selecting every section on the stock config export/import screens (#568)." + }, + "stockConfig_deselectAll": "Deselect All", + "@stockConfig_deselectAll": { + "description": "Button clearing every section on the stock config export/import screens (#568)." + }, + "stockConfig_sectionName": "Name", + "@stockConfig_sectionName": { + "description": "Config section holding the device's display name (#568)." + }, + "stockConfig_sectionIdentity": "Private Identity Key", + "@stockConfig_sectionIdentity": { + "description": "Config section holding the node's key pair (#568)." + }, + "stockConfig_sectionRadio": "Radio Settings", + "@stockConfig_sectionRadio": { + "description": "Config section holding LoRa radio parameters (#568)." + }, + "stockConfig_sectionPosition": "Position Settings", + "@stockConfig_sectionPosition": { + "description": "Config section holding the device's advertised position (#568)." + }, + "stockConfig_sectionOther": "Other Settings", + "@stockConfig_sectionOther": { + "description": "Config section holding miscellaneous device preferences (#568)." + }, + "stockConfig_sectionAutoAdd": "Auto Add Settings", + "@stockConfig_sectionAutoAdd": { + "description": "Config section holding automatic contact-add preferences (#568)." + }, + "stockConfig_sectionChannels": "Channels ({count})", + "@stockConfig_sectionChannels": { + "description": "Config section holding channels, with how many there are (#568).", + "placeholders": { "count": { "type": "int" } } + }, + "stockConfig_sectionContacts": "Contacts ({count})", + "@stockConfig_sectionContacts": { + "description": "Config section holding contacts, with how many there are (#568).", + "placeholders": { "count": { "type": "int" } } + }, + "stockConfig_identityWarning": "Your private key must be kept secret. It should only be exported as a backup.", + "@stockConfig_identityWarning": { + "description": "Warning shown beside the identity section when exporting (#568)." + }, + "stockConfig_publicKeyLabel": "Public Key: {key}", + "@stockConfig_publicKeyLabel": { + "description": "Abbreviated public key shown under the identity section (#568).", + "placeholders": { "key": { "type": "String" } } + }, + "stockConfig_privateKeyHidden": "Private Key: hidden", + "@stockConfig_privateKeyHidden": { + "description": "Placeholder shown instead of the private key, which is never displayed (#568)." + }, + "exportConfig_title": "Export Config", + "@exportConfig_title": { + "description": "Title of the stock config export screen (#574)." + }, + "exportConfig_instruction": "Please select data to export.", + "@exportConfig_instruction": { + "description": "Banner instructing the user to pick sections to export (#574)." + }, + "exportConfig_allChannels": "All channels will be exported.", + "@exportConfig_allChannels": { + "description": "Note that channels export as a whole, with no per-channel choice (#574)." + }, + "exportConfig_allContacts": "All contacts will be exported.", + "@exportConfig_allContacts": { + "description": "Note that contacts export as a whole, with no per-contact choice (#574)." + }, + "exportConfig_nothingSelected": "Select at least one section to export.", + "@exportConfig_nothingSelected": { + "description": "Shown when the user tries to export with every section unchecked (#574)." + }, + "exportConfig_lossyNotice": "This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.", + "@exportConfig_lossyNotice": { + "description": "Explains that an export drops Offband-only contact fields (#574)." + }, + "exportConfig_omittedTitle": "Some sections could not be exported", + "@exportConfig_omittedTitle": { + "description": "Title of the dialog listing sections that could not be gathered (#574)." + }, + "exportConfig_omittedUnsupported": "{section}: this radio's firmware was built without it.", + "@exportConfig_omittedUnsupported": { + "description": "Reason line when firmware lacks the feature entirely, so retrying cannot help (#574).", + "placeholders": { "section": { "type": "String" } } + }, + "exportConfig_omittedNoReply": "{section}: the device did not respond.", + "@exportConfig_omittedNoReply": { + "description": "Reason line when the device did not answer in time (#574).", + "placeholders": { "section": { "type": "String" } } + }, + "exportConfig_omittedRejected": "{section}: the device refused the request.", + "@exportConfig_omittedRejected": { + "description": "Reason line when the device refused the request (#574).", + "placeholders": { "section": { "type": "String" } } + }, + "exportConfig_omittedUnavailable": "{section}: the device has not reported this yet.", + "@exportConfig_omittedUnavailable": { + "description": "Reason line when the value is not known to the app yet (#574).", + "placeholders": { "section": { "type": "String" } } + }, + "exportConfig_exportAnyway": "Export anyway", + "@exportConfig_exportAnyway": { + "description": "Confirms writing the file even though some sections are missing (#574)." + }, + "exportConfig_cancel": "Cancel", + "@exportConfig_cancel": { + "description": "Dismisses the export without writing a file (#574)." + }, + "exportConfig_shareSubject": "MeshCore config", + "@exportConfig_shareSubject": { + "description": "Subject line used when sharing an exported config file (#574)." + }, + "exportConfig_failed": "Export failed: {message}", + "@exportConfig_failed": { + "description": "Snackbar shown when writing the export file failed (#574).", + "placeholders": { "message": { "type": "String" } } + }, + "exportConfig_notConnected": "Connect to a device before exporting.", + "@exportConfig_notConnected": { + "description": "Shown when the export screen has no connected radio to read from (#574)." + }, + "importConfig_title": "Import Config", + "@importConfig_title": { + "description": "Title of the stock config import screen (#576)." + }, + "importConfig_instruction": "Please select data to import.", + "@importConfig_instruction": { + "description": "Banner instructing the user to pick which sections to import (#576)." + }, + "importConfig_chooseFile": "Choose a config file", + "@importConfig_chooseFile": { + "description": "Button that opens the file picker to load a config file (#576)." + }, + "importConfig_identityWarning": "Importing this private key will overwrite your current identity.", + "@importConfig_identityWarning": { + "description": "Warning under the identity section, matching the wording stock uses (#576)." + }, + "importConfig_channelsNote": "New channels will be added. Existing channels will not change.", + "@importConfig_channelsNote": { + "description": "Explains the additive channel rule, matching stock's wording (#576)." + }, + "importConfig_contactsNote": "New contacts will be added. Existing contacts will be updated.", + "@importConfig_contactsNote": { + "description": "Explains the contact upsert rule, matching stock's wording (#576)." + }, + "importConfig_nothingSelected": "Select at least one section to import.", + "@importConfig_nothingSelected": { + "description": "Shown when the user confirms with nothing checked (#576)." + }, + "importConfig_notConnected": "Connect to a device before importing.", + "@importConfig_notConnected": { + "description": "Shown when there is no connected radio to import into (#576)." + }, + "importConfig_parseFailed": "That file is not a MeshCore config. {message}", + "@importConfig_parseFailed": { + "description": "Shown when the chosen file could not be parsed (#576).", + "placeholders": { "message": { "type": "String" } } + }, + "importConfig_confirmIdentityTitle": "Overwrite this node's identity?", + "@importConfig_confirmIdentityTitle": { + "description": "Title of the confirmation shown before a destructive identity import (#576)." + }, + "importConfig_confirmIdentityBody": "The node's current identity will be replaced with the one in this file, and every contact's record of this node becomes stale. This cannot be undone except by importing the previous key.", + "@importConfig_confirmIdentityBody": { + "description": "Body of the destructive identity import confirmation (#576)." + }, + "importConfig_confirmIdentityAccept": "Overwrite identity", + "@importConfig_confirmIdentityAccept": { + "description": "Confirms the destructive identity import (#576)." + }, + "importConfig_cancel": "Cancel", + "@importConfig_cancel": { + "description": "Dismisses a config import confirmation (#576)." + }, + "importConfig_resultTitle": "Import finished", + "@importConfig_resultTitle": { + "description": "Title of the dialog summarising what an import did (#576)." + }, + "importConfig_resultCounts": "Sent {contacts} contacts and {channels} channels to the device.", + "@importConfig_resultCounts": { + "description": "Summary counts after an import. Deliberately says sent, not applied: apart from identity these commands are not confirmed by the device yet (#576).", + "placeholders": { + "contacts": { "type": "int" }, + "channels": { "type": "int" } + } + }, + "importConfig_resultSkippedHeading": "Channels not imported", + "@importConfig_resultSkippedHeading": { + "description": "Heading above the list of channels that were skipped (#576)." + }, + "importConfig_resultFailedHeading": "Sections not applied", + "@importConfig_resultFailedHeading": { + "description": "Heading above the list of sections that could not be applied (#576)." + }, + "importConfig_reasonAlreadyPresent": "already on this device, so it was left unchanged", + "@importConfig_reasonAlreadyPresent": { + "description": "Skip reason: stock never overwrites an existing channel (#576)." + }, + "importConfig_reasonNoFreeSlot": "no free channel slot on the device", + "@importConfig_reasonNoFreeSlot": { + "description": "Skip reason: every channel slot is occupied (#576)." + }, + "importConfig_reasonAbsentFromFile": "not present in this file", + "@importConfig_reasonAbsentFromFile": { + "description": "Failure reason: the file did not contain the section (#576)." + }, + "importConfig_reasonNoReply": "the device did not respond", + "@importConfig_reasonNoReply": { + "description": "Failure reason: no answer from the device (#576)." + }, + "importConfig_reasonUnsupported": "this radio's firmware was built without it", + "@importConfig_reasonUnsupported": { + "description": "Failure reason: firmware lacks the feature entirely (#576)." + }, + "importConfig_reasonRejected": "the device refused it", + "@importConfig_reasonRejected": { + "description": "Failure reason: the device refused the request (#576)." + }, + "importConfig_reasonNotWritable": "this app cannot write every value in it", + "@importConfig_reasonNotWritable": { + "description": "Failure reason: no supported way to write the value (#576)." + }, + "importConfig_entryLine": "{item}: {reason}", + "@importConfig_entryLine": { + "description": "One line pairing a channel or section with why it was skipped (#576).", + "placeholders": { + "item": { "type": "String" }, + "reason": { "type": "String" } + } + }, + "importConfig_close": "Close", + "@importConfig_close": { + "description": "Dismisses the import result dialog (#576)." + }, + "settings_exportConfig": "Export Config", + "@settings_exportConfig": { + "description": "Settings entry opening the config export screen (#568)." + }, + "settings_importConfig": "Import Config", + "@settings_importConfig": { + "description": "Settings entry opening the config import screen (#568)." + }, + "settings_configBackupSubtitle": "Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.", + "@settings_configBackupSubtitle": { + "description": "Explains what the config export and import entries do (#568)." + }, + "contactSyncShortfallTitle": "Contact sync incomplete", + "@contactSyncShortfallTitle": { + "description": "Persistent banner title when the radio sent fewer contacts than it reported (#668)." + }, + "contactSyncShortfallBody": "The radio reported {declared} contacts; after checking again the app has {received}. Your saved contacts were kept.", + "@contactSyncShortfallBody": { + "description": "Persistent banner body for a short contact sync (#668).", + "placeholders": { + "declared": { + "type": "int" + }, + "received": { + "type": "int" + } + } + }, + "contactSyncShortfallBodyNoTotal": "The radio did not report how many contacts it holds; after checking again the app has {received}. Your saved contacts were kept.", + "@contactSyncShortfallBodyNoTotal": { + "description": "Persistent banner body for a contact sync whose total the radio did not report (#668).", + "placeholders": { + "received": { + "type": "int" + } + } + }, + "contactSyncDecisionTitle": "Contact sync still incomplete", + "@contactSyncDecisionTitle": { + "description": "Dialog title after the automatic retry of a short contact sync was also short (#668)." + }, + "contactSyncDecisionBody": "After checking again the app still has only {received} of the radio's contacts. Keep your saved contacts, or use the radio's list? Using the radio's list removes {removed} contacts from this app.", + "@contactSyncDecisionBody": { + "description": "Dialog body asking whether to keep saved contacts or accept the radio's shorter list (#668).", + "placeholders": { + "received": { + "type": "int" + }, + "removed": { + "type": "int" + } + } + }, + "contactSyncKeep": "Keep my contacts", + "@contactSyncKeep": { + "description": "Default dialog action: keep the saved contact list after a short sync (#668)." + }, + "contactSyncUseRadio": "Use the radio's list", + "@contactSyncUseRadio": { + "description": "Dialog action: replace the saved contacts with the radio's shorter list (#668)." + }, + "contactSyncConfirmedGone": "{count, plural, =1{1 saved contact is no longer on the radio.} other{{count} saved contacts are no longer on the radio.}}", + "@contactSyncConfirmedGone": { + "description": "Extra sentence on the short-sync banner and dialog: saved contacts the radio answered 'not found' for (#764).", + "placeholders": { + "count": { + "type": "int" + } + } } } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 06b1299f..44ba49de 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -640,6 +640,36 @@ abstract class AppLocalizations { /// **'Please turn on Bluetooth to scan for devices'** String get scanner_bluetoothOffMessage; + /// Human-readable text for an Android GATT 133 connect failure after the bounded retry also failed (#698). + /// + /// In en, this message translates to: + /// **'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'** + String get scanner_connectFailedTransient; + + /// Human-readable text for a connect timeout (#698). + /// + /// In en, this message translates to: + /// **'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'** + String get scanner_connectFailedTimeout; + + /// Human-readable fallback for any other connect failure; the raw exception goes to the log only (#522/#698). + /// + /// In en, this message translates to: + /// **'Could not connect to the radio. Details are in the App Debug Log.'** + String get scanner_connectFailedGeneric; + + /// Persistent banner title when a BLE disconnect was never confirmed by the OS, so the radio may stay latched and stop advertising (#697). + /// + /// In en, this message translates to: + /// **'Radio may still be held by this device'** + String get scanner_bleReleaseWarning; + + /// Persistent banner body naming the recovery for an unconfirmed BLE release (#697). + /// + /// In en, this message translates to: + /// **'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'** + String get scanner_bleReleaseWarningMessage; + /// No description provided for @scanner_chromeRequired. /// /// In en, this message translates to: @@ -1090,6 +1120,72 @@ abstract class AppLocalizations { /// **'Debug'** String get settings_debug; + /// No description provided for @settings_experimental. + /// + /// In en, this message translates to: + /// **'Experimental'** + String get settings_experimental; + + /// No description provided for @settings_experimentalSubtitle. + /// + /// In en, this message translates to: + /// **'Advanced and in-development features'** + String get settings_experimentalSubtitle; + + /// No description provided for @settings_experimentalDescription. + /// + /// In en, this message translates to: + /// **'These features are experimental and may change or be removed at any time. They default to off.'** + String get settings_experimentalDescription; + + /// No description provided for @settings_coreScopeObserverCount. + /// + /// In en, this message translates to: + /// **'CoreScope observer counts'** + String get settings_coreScopeObserverCount; + + /// No description provided for @settings_coreScopeObserverCountSubtitle. + /// + /// In en, this message translates to: + /// **'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'** + String get settings_coreScopeObserverCountSubtitle; + + /// No description provided for @settings_coreScopeObserverCountUnsupported. + /// + /// In en, this message translates to: + /// **'Requires a firmware build with packet-hash support (v22+).'** + String get settings_coreScopeObserverCountUnsupported; + + /// No description provided for @settings_experimentalDisable. + /// + /// In en, this message translates to: + /// **'Disable experimental features'** + String get settings_experimentalDisable; + + /// No description provided for @settings_experimentalDisableSubtitle. + /// + /// In en, this message translates to: + /// **'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'** + String get settings_experimentalDisableSubtitle; + + /// No description provided for @settings_experimentalUnlocked. + /// + /// In en, this message translates to: + /// **'Experimental features unlocked'** + String get settings_experimentalUnlocked; + + /// No description provided for @settings_experimentalAlreadyUnlocked. + /// + /// In en, this message translates to: + /// **'Experimental features are already unlocked'** + String get settings_experimentalAlreadyUnlocked; + + /// No description provided for @settings_experimentalCountdown. + /// + /// In en, this message translates to: + /// **'{count} more taps to unlock experimental features'** + String settings_experimentalCountdown(int count); + /// No description provided for @settings_companionDebugLog. /// /// In en, this message translates to: @@ -1129,21 +1225,57 @@ abstract class AppLocalizations { /// No description provided for @settings_aboutLegalese. /// /// In en, this message translates to: - /// **'2026 MeshCore Open Source Project'** + /// **'© 2026 Offband. Based on MeshCore Open by zjs81, MIT licensed.'** String get settings_aboutLegalese; /// No description provided for @settings_aboutDescription. /// /// In en, this message translates to: - /// **'An open-source Flutter client for MeshCore LoRa mesh networking devices.'** + /// **'Offband Meshcore is an open-source client for MeshCore LoRa mesh networking devices.'** String get settings_aboutDescription; + /// No description provided for @settings_aboutLicenses. + /// + /// In en, this message translates to: + /// **'View licenses'** + String get settings_aboutLicenses; + + /// No description provided for @settings_aboutWebsite. + /// + /// In en, this message translates to: + /// **'Offband website'** + String get settings_aboutWebsite; + + /// No description provided for @settings_aboutPlayStore. + /// + /// In en, this message translates to: + /// **'Google Play'** + String get settings_aboutPlayStore; + + /// No description provided for @settings_aboutDonate. + /// + /// In en, this message translates to: + /// **'Donate or sponsor'** + String get settings_aboutDonate; + + /// No description provided for @settings_aboutLinkFailed. + /// + /// In en, this message translates to: + /// **'Could not open the link'** + String get settings_aboutLinkFailed; + /// No description provided for @settings_aboutOpenMeteoAttribution. /// /// In en, this message translates to: /// **'LOS elevation data: Open-Meteo (CC BY 4.0)'** String get settings_aboutOpenMeteoAttribution; + /// No description provided for @settings_aboutPresetsAttribution. + /// + /// In en, this message translates to: + /// **'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'** + String get settings_aboutPresetsAttribution; + /// No description provided for @settings_infoName. /// /// In en, this message translates to: @@ -1234,6 +1366,48 @@ abstract class AppLocalizations { /// **'Presets'** String get settings_presets; + /// No description provided for @settings_presetSourceMeshCore. + /// + /// In en, this message translates to: + /// **'MeshCore'** + String get settings_presetSourceMeshCore; + + /// No description provided for @settings_presetSourceOffband. + /// + /// In en, this message translates to: + /// **'Offband'** + String get settings_presetSourceOffband; + + /// No description provided for @settings_presetsRefresh. + /// + /// In en, this message translates to: + /// **'Update presets'** + String get settings_presetsRefresh; + + /// No description provided for @settings_presetsUpdating. + /// + /// In en, this message translates to: + /// **'Updating presets...'** + String get settings_presetsUpdating; + + /// No description provided for @settings_presetsUpdateFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t update presets. Showing the saved list.'** + String get settings_presetsUpdateFailed; + + /// No description provided for @settings_presetsUpdatedAt. + /// + /// In en, this message translates to: + /// **'Presets updated {date}'** + String settings_presetsUpdatedAt(String date); + + /// No description provided for @settings_presetsBundled. + /// + /// In en, this message translates to: + /// **'Presets included with this version of the app'** + String get settings_presetsBundled; + /// No description provided for @settings_frequency. /// /// In en, this message translates to: @@ -2008,6 +2182,12 @@ abstract class AppLocalizations { /// **'Manage Repeater'** String get contacts_manageRepeater; + /// No description provided for @contacts_manageSensor. + /// + /// In en, this message translates to: + /// **'Manage Sensor'** + String get contacts_manageSensor; + /// No description provided for @contacts_manageRoom. /// /// In en, this message translates to: @@ -2650,6 +2830,30 @@ abstract class AppLocalizations { /// **'Message too long (max {maxBytes} bytes).'** String chat_messageTooLong(int maxBytes); + /// No description provided for @composerBudgetBlockedTitle. + /// + /// In en, this message translates to: + /// **'Can\'t send messages on this connection'** + String get composerBudgetBlockedTitle; + + /// No description provided for @composerBudgetLimitedTitle. + /// + /// In en, this message translates to: + /// **'Only {maxBytes} characters will fit'** + String composerBudgetLimitedTitle(int maxBytes); + + /// No description provided for @composerBudgetBluetoothCause. + /// + /// In en, this message translates to: + /// **'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'** + String get composerBudgetBluetoothCause; + + /// No description provided for @composerBudgetGenericCause. + /// + /// In en, this message translates to: + /// **'The connection to the radio left no room for message text. Try reconnecting.'** + String get composerBudgetGenericCause; + /// No description provided for @chat_messageCopied. /// /// In en, this message translates to: @@ -3016,6 +3220,78 @@ abstract class AppLocalizations { /// **'Heard {count, plural, =1{1 repeat} other{{count} repeats}}'** String channel_heardTooltip(int count); + /// No description provided for @channel_coreScopeTooltip. + /// + /// In en, this message translates to: + /// **'Seen by {count, plural, =1{1 CoreScope observer} other{{count} CoreScope observers}}'** + String channel_coreScopeTooltip(int count); + + /// No description provided for @channel_coreScopeRefresh. + /// + /// In en, this message translates to: + /// **'Refresh CoreScope observers'** + String get channel_coreScopeRefresh; + + /// No description provided for @channel_coreScopeRefreshFailed. + /// + /// In en, this message translates to: + /// **'CoreScope unreachable'** + String get channel_coreScopeRefreshFailed; + + /// No description provided for @channel_coreScopeNotFound. + /// + /// In en, this message translates to: + /// **'Not seen by CoreScope yet'** + String get channel_coreScopeNotFound; + + /// No description provided for @channel_coreScopeCounts. + /// + /// In en, this message translates to: + /// **'{observers, plural, =1{1 observer} other{{observers} observers}} · {observations} observations'** + String channel_coreScopeCounts(int observers, int observations); + + /// No description provided for @channel_senderNameUnknown. + /// + /// In en, this message translates to: + /// **'No node known by that name'** + String get channel_senderNameUnknown; + + /// No description provided for @channel_senderNameUnknownHint. + /// + /// In en, this message translates to: + /// **'Adding needs an advert from this node'** + String get channel_senderNameUnknownHint; + + /// No description provided for @channel_senderAlreadyContact. + /// + /// In en, this message translates to: + /// **'Already in contacts'** + String get channel_senderAlreadyContact; + + /// No description provided for @channel_senderMultipleMatches. + /// + /// In en, this message translates to: + /// **'{count} nodes use this name'** + String channel_senderMultipleMatches(int count); + + /// No description provided for @channel_senderAddNotConnected. + /// + /// In en, this message translates to: + /// **'Not connected to a radio, so this sender can\'t be added yet'** + String get channel_senderAddNotConnected; + + /// No description provided for @channel_senderAddFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t add this sender: {error}'** + String channel_senderAddFailed(String error); + + /// No description provided for @channel_senderCandidate. + /// + /// In en, this message translates to: + /// **'{keyPrefix} · {type}'** + String channel_senderCandidate(String keyPrefix, String type); + /// No description provided for @chat_successes. /// /// In en, this message translates to: @@ -4418,6 +4694,36 @@ abstract class AppLocalizations { /// **'Coding Rate'** String get repeater_codingRate; + /// No description provided for @repeater_tempRadio. + /// + /// In en, this message translates to: + /// **'Apply temporarily'** + String get repeater_tempRadio; + + /// No description provided for @repeater_tempRadioSubtitle. + /// + /// In en, this message translates to: + /// **'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'** + String get repeater_tempRadioSubtitle; + + /// No description provided for @repeater_tempRadioMinutes. + /// + /// In en, this message translates to: + /// **'Duration (minutes)'** + String get repeater_tempRadioMinutes; + + /// No description provided for @repeater_tempRadioPathHashNote. + /// + /// In en, this message translates to: + /// **'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'** + String get repeater_tempRadioPathHashNote; + + /// No description provided for @repeater_tempRadioMinutesInvalid. + /// + /// In en, this message translates to: + /// **'1 to {max} minutes'** + String repeater_tempRadioMinutesInvalid(int max); + /// No description provided for @repeater_locationSettings. /// /// In en, this message translates to: @@ -5006,6 +5312,12 @@ abstract class AppLocalizations { /// **'Error: {error}'** String repeater_cliCommandError(String error); + /// No description provided for @repeater_cliCommandTimeout. + /// + /// In en, this message translates to: + /// **'Command timed out after {seconds} seconds'** + String repeater_cliCommandTimeout(String seconds); + /// No description provided for @repeater_cliQuickGetName. /// /// In en, this message translates to: @@ -7258,6 +7570,180 @@ abstract class AppLocalizations { /// **'Add Contact from Clipboard'** String get contacts_addContactFromClipboard; + /// No description provided for @contacts_addByKey. + /// + /// In en, this message translates to: + /// **'Add by public key'** + String get contacts_addByKey; + + /// No description provided for @contacts_addByKeyDescription. + /// + /// In en, this message translates to: + /// **'Add someone using the public key they gave you. Works even if you have never heard their advert.'** + String get contacts_addByKeyDescription; + + /// No description provided for @contacts_publicKeyLabel. + /// + /// In en, this message translates to: + /// **'Public key'** + String get contacts_publicKeyLabel; + + /// No description provided for @contacts_publicKeyHelper. + /// + /// In en, this message translates to: + /// **'64 hex characters, or paste a meshcore:// contact link'** + String get contacts_publicKeyHelper; + + /// No description provided for @contacts_publicKeyInvalid. + /// + /// In en, this message translates to: + /// **'Enter 64 hex characters, or a meshcore:// contact link'** + String get contacts_publicKeyInvalid; + + /// No description provided for @contacts_nameLabel. + /// + /// In en, this message translates to: + /// **'Name'** + String get contacts_nameLabel; + + /// No description provided for @contacts_typeLabel. + /// + /// In en, this message translates to: + /// **'Type'** + String get contacts_typeLabel; + + /// No description provided for @contacts_addByKeyUnverifiedNote. + /// + /// In en, this message translates to: + /// **'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'** + String get contacts_addByKeyUnverifiedNote; + + /// No description provided for @contacts_addByKeyAdded. + /// + /// In en, this message translates to: + /// **'Added {name}'** + String contacts_addByKeyAdded(String name); + + /// No description provided for @contacts_addByKeyFailed. + /// + /// In en, this message translates to: + /// **'Could not add the contact. Check the radio connection.'** + String get contacts_addByKeyFailed; + + /// No description provided for @contacts_myContactQr. + /// + /// In en, this message translates to: + /// **'My contact QR'** + String get contacts_myContactQr; + + /// No description provided for @contacts_myContactQrInstructions. + /// + /// In en, this message translates to: + /// **'Have them scan this, or send them the link below. It works even if they have never heard your advert.'** + String get contacts_myContactQrInstructions; + + /// No description provided for @contacts_contactLinkCopied. + /// + /// In en, this message translates to: + /// **'Contact link copied'** + String get contacts_contactLinkCopied; + + /// No description provided for @contacts_qrNeedsConnection. + /// + /// In en, this message translates to: + /// **'Connect to a radio first, so the app knows your public key.'** + String get contacts_qrNeedsConnection; + + /// No description provided for @contacts_scanContactQr. + /// + /// In en, this message translates to: + /// **'Scan contact QR'** + String get contacts_scanContactQr; + + /// No description provided for @contacts_scanContactQrInstructions. + /// + /// In en, this message translates to: + /// **'Point the camera at a MeshCore contact QR'** + String get contacts_scanContactQrInstructions; + + /// No description provided for @contacts_invalidContactQr. + /// + /// In en, this message translates to: + /// **'That QR is not a MeshCore contact'** + String get contacts_invalidContactQr; + + /// No description provided for @contacts_verifiedByAdvert. + /// + /// In en, this message translates to: + /// **'Confirmed on air. This node sent a signed advert.'** + String get contacts_verifiedByAdvert; + + /// No description provided for @contacts_verifiedByMessage. + /// + /// In en, this message translates to: + /// **'Key confirmed. A message with this contact went through, which only works with the matching key.'** + String get contacts_verifiedByMessage; + + /// No description provided for @contacts_verifiedKeyOnly. + /// + /// In en, this message translates to: + /// **'Added from a key. Nothing has confirmed it on air yet.'** + String get contacts_verifiedKeyOnly; + + /// No description provided for @contacts_lastSeenNever. + /// + /// In en, this message translates to: + /// **'Not heard yet'** + String get contacts_lastSeenNever; + + /// No description provided for @contacts_cardAddContact. + /// + /// In en, this message translates to: + /// **'Add {name}'** + String contacts_cardAddContact(String name); + + /// No description provided for @contacts_cardAlreadyAdded. + /// + /// In en, this message translates to: + /// **'{name}'** + String contacts_cardAlreadyAdded(String name); + + /// No description provided for @contacts_cardAlreadyAddedTooltip. + /// + /// In en, this message translates to: + /// **'Already in your contacts'** + String get contacts_cardAlreadyAddedTooltip; + + /// No description provided for @chat_attachTooltip. + /// + /// In en, this message translates to: + /// **'Add to message'** + String get chat_attachTooltip; + + /// No description provided for @chat_attachGif. + /// + /// In en, this message translates to: + /// **'GIF'** + String get chat_attachGif; + + /// No description provided for @chat_attachMyContact. + /// + /// In en, this message translates to: + /// **'My contact card'** + String get chat_attachMyContact; + + /// No description provided for @chat_attachMyContactSubtitle. + /// + /// In en, this message translates to: + /// **'Puts your public key in the message so anyone here can add you'** + String get chat_attachMyContactSubtitle; + + /// No description provided for @chat_contactCardNeedsConnection. + /// + /// In en, this message translates to: + /// **'Connect to a radio first, so the app knows your public key.'** + String get chat_contactCardNeedsConnection; + /// No description provided for @contacts_ShareContact. /// /// In en, this message translates to: @@ -8097,6 +8583,402 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Couldn\'t open battery settings'** String get batteryOptimizationOpenFailed; + + /// Button selecting every section on the stock config export/import screens (#568). + /// + /// In en, this message translates to: + /// **'Select All'** + String get stockConfig_selectAll; + + /// Button clearing every section on the stock config export/import screens (#568). + /// + /// In en, this message translates to: + /// **'Deselect All'** + String get stockConfig_deselectAll; + + /// Config section holding the device's display name (#568). + /// + /// In en, this message translates to: + /// **'Name'** + String get stockConfig_sectionName; + + /// Config section holding the node's key pair (#568). + /// + /// In en, this message translates to: + /// **'Private Identity Key'** + String get stockConfig_sectionIdentity; + + /// Config section holding LoRa radio parameters (#568). + /// + /// In en, this message translates to: + /// **'Radio Settings'** + String get stockConfig_sectionRadio; + + /// Config section holding the device's advertised position (#568). + /// + /// In en, this message translates to: + /// **'Position Settings'** + String get stockConfig_sectionPosition; + + /// Config section holding miscellaneous device preferences (#568). + /// + /// In en, this message translates to: + /// **'Other Settings'** + String get stockConfig_sectionOther; + + /// Config section holding automatic contact-add preferences (#568). + /// + /// In en, this message translates to: + /// **'Auto Add Settings'** + String get stockConfig_sectionAutoAdd; + + /// Config section holding channels, with how many there are (#568). + /// + /// In en, this message translates to: + /// **'Channels ({count})'** + String stockConfig_sectionChannels(int count); + + /// Config section holding contacts, with how many there are (#568). + /// + /// In en, this message translates to: + /// **'Contacts ({count})'** + String stockConfig_sectionContacts(int count); + + /// Warning shown beside the identity section when exporting (#568). + /// + /// In en, this message translates to: + /// **'Your private key must be kept secret. It should only be exported as a backup.'** + String get stockConfig_identityWarning; + + /// Abbreviated public key shown under the identity section (#568). + /// + /// In en, this message translates to: + /// **'Public Key: {key}'** + String stockConfig_publicKeyLabel(String key); + + /// Placeholder shown instead of the private key, which is never displayed (#568). + /// + /// In en, this message translates to: + /// **'Private Key: hidden'** + String get stockConfig_privateKeyHidden; + + /// Title of the stock config export screen (#574). + /// + /// In en, this message translates to: + /// **'Export Config'** + String get exportConfig_title; + + /// Banner instructing the user to pick sections to export (#574). + /// + /// In en, this message translates to: + /// **'Please select data to export.'** + String get exportConfig_instruction; + + /// Note that channels export as a whole, with no per-channel choice (#574). + /// + /// In en, this message translates to: + /// **'All channels will be exported.'** + String get exportConfig_allChannels; + + /// Note that contacts export as a whole, with no per-contact choice (#574). + /// + /// In en, this message translates to: + /// **'All contacts will be exported.'** + String get exportConfig_allContacts; + + /// Shown when the user tries to export with every section unchecked (#574). + /// + /// In en, this message translates to: + /// **'Select at least one section to export.'** + String get exportConfig_nothingSelected; + + /// Explains that an export drops Offband-only contact fields (#574). + /// + /// In en, this message translates to: + /// **'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'** + String get exportConfig_lossyNotice; + + /// Title of the dialog listing sections that could not be gathered (#574). + /// + /// In en, this message translates to: + /// **'Some sections could not be exported'** + String get exportConfig_omittedTitle; + + /// Reason line when firmware lacks the feature entirely, so retrying cannot help (#574). + /// + /// In en, this message translates to: + /// **'{section}: this radio\'s firmware was built without it.'** + String exportConfig_omittedUnsupported(String section); + + /// Reason line when the device did not answer in time (#574). + /// + /// In en, this message translates to: + /// **'{section}: the device did not respond.'** + String exportConfig_omittedNoReply(String section); + + /// Reason line when the device refused the request (#574). + /// + /// In en, this message translates to: + /// **'{section}: the device refused the request.'** + String exportConfig_omittedRejected(String section); + + /// Reason line when the value is not known to the app yet (#574). + /// + /// In en, this message translates to: + /// **'{section}: the device has not reported this yet.'** + String exportConfig_omittedUnavailable(String section); + + /// Confirms writing the file even though some sections are missing (#574). + /// + /// In en, this message translates to: + /// **'Export anyway'** + String get exportConfig_exportAnyway; + + /// Dismisses the export without writing a file (#574). + /// + /// In en, this message translates to: + /// **'Cancel'** + String get exportConfig_cancel; + + /// Subject line used when sharing an exported config file (#574). + /// + /// In en, this message translates to: + /// **'MeshCore config'** + String get exportConfig_shareSubject; + + /// Snackbar shown when writing the export file failed (#574). + /// + /// In en, this message translates to: + /// **'Export failed: {message}'** + String exportConfig_failed(String message); + + /// Shown when the export screen has no connected radio to read from (#574). + /// + /// In en, this message translates to: + /// **'Connect to a device before exporting.'** + String get exportConfig_notConnected; + + /// Title of the stock config import screen (#576). + /// + /// In en, this message translates to: + /// **'Import Config'** + String get importConfig_title; + + /// Banner instructing the user to pick which sections to import (#576). + /// + /// In en, this message translates to: + /// **'Please select data to import.'** + String get importConfig_instruction; + + /// Button that opens the file picker to load a config file (#576). + /// + /// In en, this message translates to: + /// **'Choose a config file'** + String get importConfig_chooseFile; + + /// Warning under the identity section, matching the wording stock uses (#576). + /// + /// In en, this message translates to: + /// **'Importing this private key will overwrite your current identity.'** + String get importConfig_identityWarning; + + /// Explains the additive channel rule, matching stock's wording (#576). + /// + /// In en, this message translates to: + /// **'New channels will be added. Existing channels will not change.'** + String get importConfig_channelsNote; + + /// Explains the contact upsert rule, matching stock's wording (#576). + /// + /// In en, this message translates to: + /// **'New contacts will be added. Existing contacts will be updated.'** + String get importConfig_contactsNote; + + /// Shown when the user confirms with nothing checked (#576). + /// + /// In en, this message translates to: + /// **'Select at least one section to import.'** + String get importConfig_nothingSelected; + + /// Shown when there is no connected radio to import into (#576). + /// + /// In en, this message translates to: + /// **'Connect to a device before importing.'** + String get importConfig_notConnected; + + /// Shown when the chosen file could not be parsed (#576). + /// + /// In en, this message translates to: + /// **'That file is not a MeshCore config. {message}'** + String importConfig_parseFailed(String message); + + /// Title of the confirmation shown before a destructive identity import (#576). + /// + /// In en, this message translates to: + /// **'Overwrite this node\'s identity?'** + String get importConfig_confirmIdentityTitle; + + /// Body of the destructive identity import confirmation (#576). + /// + /// In en, this message translates to: + /// **'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'** + String get importConfig_confirmIdentityBody; + + /// Confirms the destructive identity import (#576). + /// + /// In en, this message translates to: + /// **'Overwrite identity'** + String get importConfig_confirmIdentityAccept; + + /// Dismisses a config import confirmation (#576). + /// + /// In en, this message translates to: + /// **'Cancel'** + String get importConfig_cancel; + + /// Title of the dialog summarising what an import did (#576). + /// + /// In en, this message translates to: + /// **'Import finished'** + String get importConfig_resultTitle; + + /// Summary counts after an import. Deliberately says sent, not applied: apart from identity these commands are not confirmed by the device yet (#576). + /// + /// In en, this message translates to: + /// **'Sent {contacts} contacts and {channels} channels to the device.'** + String importConfig_resultCounts(int contacts, int channels); + + /// Heading above the list of channels that were skipped (#576). + /// + /// In en, this message translates to: + /// **'Channels not imported'** + String get importConfig_resultSkippedHeading; + + /// Heading above the list of sections that could not be applied (#576). + /// + /// In en, this message translates to: + /// **'Sections not applied'** + String get importConfig_resultFailedHeading; + + /// Skip reason: stock never overwrites an existing channel (#576). + /// + /// In en, this message translates to: + /// **'already on this device, so it was left unchanged'** + String get importConfig_reasonAlreadyPresent; + + /// Skip reason: every channel slot is occupied (#576). + /// + /// In en, this message translates to: + /// **'no free channel slot on the device'** + String get importConfig_reasonNoFreeSlot; + + /// Failure reason: the file did not contain the section (#576). + /// + /// In en, this message translates to: + /// **'not present in this file'** + String get importConfig_reasonAbsentFromFile; + + /// Failure reason: no answer from the device (#576). + /// + /// In en, this message translates to: + /// **'the device did not respond'** + String get importConfig_reasonNoReply; + + /// Failure reason: firmware lacks the feature entirely (#576). + /// + /// In en, this message translates to: + /// **'this radio\'s firmware was built without it'** + String get importConfig_reasonUnsupported; + + /// Failure reason: the device refused the request (#576). + /// + /// In en, this message translates to: + /// **'the device refused it'** + String get importConfig_reasonRejected; + + /// Failure reason: no supported way to write the value (#576). + /// + /// In en, this message translates to: + /// **'this app cannot write every value in it'** + String get importConfig_reasonNotWritable; + + /// One line pairing a channel or section with why it was skipped (#576). + /// + /// In en, this message translates to: + /// **'{item}: {reason}'** + String importConfig_entryLine(String item, String reason); + + /// Dismisses the import result dialog (#576). + /// + /// In en, this message translates to: + /// **'Close'** + String get importConfig_close; + + /// Settings entry opening the config export screen (#568). + /// + /// In en, this message translates to: + /// **'Export Config'** + String get settings_exportConfig; + + /// Settings entry opening the config import screen (#568). + /// + /// In en, this message translates to: + /// **'Import Config'** + String get settings_importConfig; + + /// Explains what the config export and import entries do (#568). + /// + /// In en, this message translates to: + /// **'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'** + String get settings_configBackupSubtitle; + + /// Persistent banner title when the radio sent fewer contacts than it reported (#668). + /// + /// In en, this message translates to: + /// **'Contact sync incomplete'** + String get contactSyncShortfallTitle; + + /// Persistent banner body for a short contact sync (#668). + /// + /// In en, this message translates to: + /// **'The radio reported {declared} contacts; after checking again the app has {received}. Your saved contacts were kept.'** + String contactSyncShortfallBody(int declared, int received); + + /// Persistent banner body for a contact sync whose total the radio did not report (#668). + /// + /// In en, this message translates to: + /// **'The radio did not report how many contacts it holds; after checking again the app has {received}. Your saved contacts were kept.'** + String contactSyncShortfallBodyNoTotal(int received); + + /// Dialog title after the automatic retry of a short contact sync was also short (#668). + /// + /// In en, this message translates to: + /// **'Contact sync still incomplete'** + String get contactSyncDecisionTitle; + + /// Dialog body asking whether to keep saved contacts or accept the radio's shorter list (#668). + /// + /// In en, this message translates to: + /// **'After checking again the app still has only {received} of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes {removed} contacts from this app.'** + String contactSyncDecisionBody(int received, int removed); + + /// Default dialog action: keep the saved contact list after a short sync (#668). + /// + /// In en, this message translates to: + /// **'Keep my contacts'** + String get contactSyncKeep; + + /// Dialog action: replace the saved contacts with the radio's shorter list (#668). + /// + /// In en, this message translates to: + /// **'Use the radio\'s list'** + String get contactSyncUseRadio; + + /// Extra sentence on the short-sync banner and dialog: saved contacts the radio answered 'not found' for (#764). + /// + /// In en, this message translates to: + /// **'{count, plural, =1{1 saved contact is no longer on the radio.} other{{count} saved contacts are no longer on the radio.}}'** + String contactSyncConfirmedGone(int count); } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 7e27684f..2fd77ebc 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -290,6 +290,26 @@ class AppLocalizationsBg extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Моля, активирайте Bluetooth, за да сканирате за устройства.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Изисква се браузър Chrome'; @@ -540,6 +560,47 @@ class AppLocalizationsBg extends AppLocalizations { @override String get settings_debug => 'Отстрани'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Лог за отстраняване на грешки (за съпътстваща програма)'; @@ -571,10 +632,29 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_aboutDescription => 'Отворен софтуер за Flutter клиент за MeshCore LoRa мрежови устройства.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Данни за надморска височина на LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Име'; @@ -621,6 +701,31 @@ class AppLocalizationsBg extends AppLocalizations { @override String get settings_presets => 'Предварителни настройки'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Честота (MHz)'; @@ -1071,6 +1176,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_manageRepeater => 'Управление на Повтарящ се Елемент'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Управление на сървър за стая'; @@ -1442,6 +1550,23 @@ class AppLocalizationsBg extends AppLocalizations { return 'Съобщението е твърде дълго (макс $maxBytes байта).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Съобщението е копирано'; @@ -1661,6 +1786,66 @@ class AppLocalizationsBg extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Успехи'; @@ -2472,6 +2657,25 @@ class AppLocalizationsBg extends AppLocalizations { @override String get repeater_codingRate => 'Такса за кодиране'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Настройки на местоположението'; @@ -2821,6 +3025,11 @@ class AppLocalizationsBg extends AppLocalizations { return 'Грешка: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Получи име'; @@ -4214,6 +4423,112 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Добави контакт от клипборда'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Копирай контакт в клипборда'; @@ -4735,4 +5050,254 @@ class AppLocalizationsBg extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index ae9c2652..1f63620c 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -293,6 +293,26 @@ class AppLocalizationsDe extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Bitte aktivieren Sie Bluetooth, um nach Geräten zu suchen.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome Browser erforderlich'; @@ -537,6 +557,47 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_debug => 'Fehlerbehebung'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Debug-Protokoll für die Begleitsoftware'; @@ -566,10 +627,29 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_aboutDescription => 'Ein Open-Source-Flutter-Client für MeshCore LoRa-Meshnetzwerkgeräte.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS-Höhendaten: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Name'; @@ -616,6 +696,31 @@ class AppLocalizationsDe extends AppLocalizations { @override String get settings_presets => 'Voreinstellungen'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frequenz (MHz)'; @@ -1066,6 +1171,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contacts_manageRepeater => 'Repeater verwalten'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Raum-Server verwalten'; @@ -1440,6 +1548,23 @@ class AppLocalizationsDe extends AppLocalizations { return 'Nachricht ist zu lang (max $maxBytes Bytes).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Nachricht kopiert'; @@ -1659,6 +1784,66 @@ class AppLocalizationsDe extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Erfolgreich'; @@ -2467,6 +2652,25 @@ class AppLocalizationsDe extends AppLocalizations { @override String get repeater_codingRate => 'Kodierungsrate'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Standort Einstellungen'; @@ -2824,6 +3028,11 @@ class AppLocalizationsDe extends AppLocalizations { return 'Fehler: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Name erhalten'; @@ -4226,6 +4435,112 @@ class AppLocalizationsDe extends AppLocalizations { String get contacts_addContactFromClipboard => 'Kontakt aus Zwischenablage hinzufügen'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Kontakt in die Zwischenablage kopieren'; @@ -4752,4 +5067,254 @@ class AppLocalizationsDe extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 33597a4f..7ebc75d8 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -287,6 +287,26 @@ class AppLocalizationsEn extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Please turn on Bluetooth to scan for devices'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome Browser Required'; @@ -528,6 +548,47 @@ class AppLocalizationsEn extends AppLocalizations { @override String get settings_debug => 'Debug'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Companion Debug Log'; @@ -550,16 +611,36 @@ class AppLocalizationsEn extends AppLocalizations { } @override - String get settings_aboutLegalese => '2026 MeshCore Open Source Project'; + String get settings_aboutLegalese => + '© 2026 Offband. Based on MeshCore Open by zjs81, MIT licensed.'; @override String get settings_aboutDescription => - 'An open-source Flutter client for MeshCore LoRa mesh networking devices.'; + 'Offband Meshcore is an open-source client for MeshCore LoRa mesh networking devices.'; + + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; @override String get settings_aboutOpenMeteoAttribution => 'LOS elevation data: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Name'; @@ -606,6 +687,31 @@ class AppLocalizationsEn extends AppLocalizations { @override String get settings_presets => 'Presets'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frequency (MHz)'; @@ -1049,6 +1155,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_manageRepeater => 'Manage Repeater'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Manage Room Server'; @@ -1412,6 +1521,23 @@ class AppLocalizationsEn extends AppLocalizations { return 'Message too long (max $maxBytes bytes).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Message copied'; @@ -1629,6 +1755,66 @@ class AppLocalizationsEn extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'successes'; @@ -2422,6 +2608,25 @@ class AppLocalizationsEn extends AppLocalizations { @override String get repeater_codingRate => 'Coding Rate'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Location Settings'; @@ -2764,6 +2969,11 @@ class AppLocalizationsEn extends AppLocalizations { return 'Error: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Get Name'; @@ -4147,6 +4357,112 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Add Contact from Clipboard'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Copy contact to Clipboard'; @@ -4657,4 +4973,254 @@ class AppLocalizationsEn extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index a3d52524..0d527d9f 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -291,6 +291,26 @@ class AppLocalizationsEs extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Por favor, active el Bluetooth para escanear dispositivos.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Navegador Chrome requerido'; @@ -538,6 +558,47 @@ class AppLocalizationsEs extends AppLocalizations { @override String get settings_debug => 'Depurar'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Registro de depuración asociado'; @@ -567,10 +628,29 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_aboutDescription => 'Un cliente de código abierto de Flutter para dispositivos de red mesh LoRa de MeshCore.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Datos de elevación LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Nombre'; @@ -617,6 +697,31 @@ class AppLocalizationsEs extends AppLocalizations { @override String get settings_presets => 'Preajustes'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frecuencia (MHz)'; @@ -1065,6 +1170,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get contacts_manageRepeater => 'Gestionar Repetidor'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Gestionar Servidor de Habitación'; @@ -1439,6 +1547,23 @@ class AppLocalizationsEs extends AppLocalizations { return 'Mensaje demasiado largo (máximo $maxBytes bytes).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Mensaje copiado'; @@ -1656,6 +1781,66 @@ class AppLocalizationsEs extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Éxitos'; @@ -2464,6 +2649,25 @@ class AppLocalizationsEs extends AppLocalizations { @override String get repeater_codingRate => 'Tasa de Programación'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Configuración de Ubicación'; @@ -2815,6 +3019,11 @@ class AppLocalizationsEs extends AppLocalizations { return 'Error: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Obtener Nombre'; @@ -4215,6 +4424,112 @@ class AppLocalizationsEs extends AppLocalizations { String get contacts_addContactFromClipboard => 'Agregar contacto desde el portapapeles'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Copiar contacto al Portapapeles'; @@ -4740,4 +5055,254 @@ class AppLocalizationsEs extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index eba4521c..d1cf3027 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -293,6 +293,26 @@ class AppLocalizationsFr extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Veuillez activer le Bluetooth pour rechercher des appareils.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Navigateur Chrome requis'; @@ -542,6 +562,47 @@ class AppLocalizationsFr extends AppLocalizations { @override String get settings_debug => 'Déboguer'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Journal de débogage associé'; @@ -571,10 +632,29 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_aboutDescription => 'Un client Flutter open source pour les appareils de réseau mesh MeshCore LoRa.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Données d\'élévation LOS : Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Nom'; @@ -621,6 +701,31 @@ class AppLocalizationsFr extends AppLocalizations { @override String get settings_presets => 'Préréglages'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Fréquence (MHz)'; @@ -1071,6 +1176,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get contacts_manageRepeater => 'Gérer le répéteur'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Gérer le Room Server'; @@ -1444,6 +1552,23 @@ class AppLocalizationsFr extends AppLocalizations { return 'Message trop long (max $maxBytes octets).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Message copié'; @@ -1663,6 +1788,66 @@ class AppLocalizationsFr extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Succès'; @@ -2476,6 +2661,25 @@ class AppLocalizationsFr extends AppLocalizations { @override String get repeater_codingRate => 'Taux de codage (CR)'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Paramètres de localisation'; @@ -2837,6 +3041,11 @@ class AppLocalizationsFr extends AppLocalizations { return 'Erreur : $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Obtenir le nom'; @@ -4237,6 +4446,112 @@ class AppLocalizationsFr extends AppLocalizations { String get contacts_addContactFromClipboard => 'Ajouter un contact depuis le presse-papiers'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Copier le contact dans le presse-papiers'; @@ -4768,4 +5083,254 @@ class AppLocalizationsFr extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fb42803b..a516594c 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -290,6 +290,26 @@ class AppLocalizationsHu extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Kérjük, kapcsolja be a Bluetooth-ot, hogy eszközök keresése lehessen.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome böngésző szükséges'; @@ -540,6 +560,47 @@ class AppLocalizationsHu extends AppLocalizations { @override String get settings_debug => 'Hibakeresés'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Párhuzamos hibakeresési napló'; @@ -569,10 +630,29 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_aboutDescription => 'Egy nyílt forráskódú Flutter kliens a MeshCore LoRa hálózati eszközök számára.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS magassági adatok: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Név'; @@ -619,6 +699,31 @@ class AppLocalizationsHu extends AppLocalizations { @override String get settings_presets => 'Előre beállított beállítások'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frekvencia (MHz)'; @@ -1072,6 +1177,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get contacts_manageRepeater => 'Ellenőriző eszköz kezelése'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'A szobai szerver kezelése'; @@ -1447,6 +1555,23 @@ class AppLocalizationsHu extends AppLocalizations { return 'A üzenet túl hosszú (a maximális $maxBytes bájt).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Üzenet másolva'; @@ -1668,6 +1793,66 @@ class AppLocalizationsHu extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'sikerek'; @@ -2480,6 +2665,25 @@ class AppLocalizationsHu extends AppLocalizations { @override String get repeater_codingRate => 'Kódolási sebesség'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Helyszínbeállítások'; @@ -2828,6 +3032,11 @@ class AppLocalizationsHu extends AppLocalizations { return 'Hiba: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Kapcsold össze a nevet'; @@ -4232,6 +4441,112 @@ class AppLocalizationsHu extends AppLocalizations { String get contacts_addContactFromClipboard => 'Adjon hozzá egy kapcsolatot a kiválasztott listából'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Másolja a kapcsolatot a kiválasztóba'; @@ -4757,4 +5072,254 @@ class AppLocalizationsHu extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 5cd6761f..de89e16b 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -293,6 +293,26 @@ class AppLocalizationsIt extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Si prega di attivare il Bluetooth per effettuare la scansione dei dispositivi.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Browser Chrome richiesto'; @@ -540,6 +560,47 @@ class AppLocalizationsIt extends AppLocalizations { @override String get settings_debug => 'Risoluzione dei problemi'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Registro di debug per il supporto'; @@ -569,10 +630,29 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_aboutDescription => 'Un client Flutter open-source per i dispositivi di rete mesh LoRa Core di MeshCore.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Dati di elevazione LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Nome'; @@ -619,6 +699,31 @@ class AppLocalizationsIt extends AppLocalizations { @override String get settings_presets => 'Preset'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frequenza (MHz)'; @@ -1067,6 +1172,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get contacts_manageRepeater => 'Gestisci Ripetitore'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Gestisci Server Camera'; @@ -1441,6 +1549,23 @@ class AppLocalizationsIt extends AppLocalizations { return 'Messaggio troppo lungo (massimo $maxBytes byte).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Messaggio copiato'; @@ -1658,6 +1783,66 @@ class AppLocalizationsIt extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'successi'; @@ -2468,6 +2653,25 @@ class AppLocalizationsIt extends AppLocalizations { @override String get repeater_codingRate => 'Tasso di Codifica'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Impostazioni Luogo'; @@ -2821,6 +3025,11 @@ class AppLocalizationsIt extends AppLocalizations { return 'Errore: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Ottieni Nome'; @@ -4220,6 +4429,112 @@ class AppLocalizationsIt extends AppLocalizations { String get contacts_addContactFromClipboard => 'Aggiungere contatto dalla clipboard'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Copia contatto negli Appunti'; @@ -4745,4 +5060,254 @@ class AppLocalizationsIt extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 4dd94a1b..b8362371 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -280,6 +280,26 @@ class AppLocalizationsJa extends AppLocalizations { @override String get scanner_bluetoothOffMessage => 'Bluetoothを有効にして、デバイスを検索してください。'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome ブラウザが必須です'; @@ -514,6 +534,47 @@ class AppLocalizationsJa extends AppLocalizations { @override String get settings_debug => 'デバッグ'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => '同伴デバッグログ'; @@ -542,10 +603,29 @@ class AppLocalizationsJa extends AppLocalizations { String get settings_aboutDescription => 'MeshCore LoRaメッシュネットワークデバイス用の、オープンソースのFlutterクライアント。'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS 標高データ:Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => '名前'; @@ -592,6 +672,31 @@ class AppLocalizationsJa extends AppLocalizations { @override String get settings_presets => 'プリセット'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => '周波数 (MHz)'; @@ -1019,6 +1124,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_manageRepeater => 'リピーターの管理'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'ルームサーバーの管理'; @@ -1378,6 +1486,23 @@ class AppLocalizationsJa extends AppLocalizations { return 'メッセージが長すぎる($maxBytes バイトを超える)。'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'メッセージがコピーされました'; @@ -1593,6 +1718,66 @@ class AppLocalizationsJa extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => '成功事例'; @@ -2374,6 +2559,25 @@ class AppLocalizationsJa extends AppLocalizations { @override String get repeater_codingRate => 'コーディング速度'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => '場所設定'; @@ -2701,6 +2905,11 @@ class AppLocalizationsJa extends AppLocalizations { return 'エラー:$error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => '名前を取得する'; @@ -4017,6 +4226,112 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'クリップボードから連絡先を追加する'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => '連絡先をクリップボードにコピー'; @@ -4511,4 +4826,254 @@ class AppLocalizationsJa extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index f9a1fec5..1de3d95f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -279,6 +279,26 @@ class AppLocalizationsKo extends AppLocalizations { @override String get scanner_bluetoothOffMessage => '블루투스를 켜서 장치를 검색해주세요.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => '크롬 브라우저 필요'; @@ -514,6 +534,47 @@ class AppLocalizationsKo extends AppLocalizations { @override String get settings_debug => '디버깅'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => '동반 디버깅 로그'; @@ -542,10 +603,29 @@ class AppLocalizationsKo extends AppLocalizations { String get settings_aboutDescription => 'MeshCore LoRa 메시 네트워크 장치를 위한 오픈 소스 Flutter 클라이언트.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS 고도 데이터: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => '이름'; @@ -592,6 +672,31 @@ class AppLocalizationsKo extends AppLocalizations { @override String get settings_presets => '기본 설정'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => '주파수 (MHz)'; @@ -1014,6 +1119,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_manageRepeater => '리피터 관리'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => '방 서버 관리'; @@ -1373,6 +1481,23 @@ class AppLocalizationsKo extends AppLocalizations { return '메시지가 너무 길어서 (최대 $maxBytes 바이트).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => '메시지가 복사되었습니다'; @@ -1589,6 +1714,66 @@ class AppLocalizationsKo extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => '성공 사례'; @@ -2371,6 +2556,25 @@ class AppLocalizationsKo extends AppLocalizations { @override String get repeater_codingRate => '코딩 속도'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => '위치 설정'; @@ -2699,6 +2903,11 @@ class AppLocalizationsKo extends AppLocalizations { return '오류: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => '이름을 알려주세요'; @@ -4019,6 +4228,112 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_addContactFromClipboard => '복사본에서 연락처 추가'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => '연락처를 복사'; @@ -4512,4 +4827,254 @@ class AppLocalizationsKo extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 0dc6d77d..da8decb5 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -289,6 +289,26 @@ class AppLocalizationsNl extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Zorg ervoor dat Bluetooth is ingeschakeld om naar apparaten te zoeken.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome-browser vereist'; @@ -534,6 +554,47 @@ class AppLocalizationsNl extends AppLocalizations { @override String get settings_debug => 'Foutopsporing'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Debuglog voor aanvullende informatie'; @@ -563,10 +624,29 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_aboutDescription => 'Een open-source Flutter client voor MeshCore LoRa mesh netwerkapparaten.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS-hoogtegegevens: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Naam'; @@ -613,6 +693,31 @@ class AppLocalizationsNl extends AppLocalizations { @override String get settings_presets => 'Voorgeprogrammeerde instellingen'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frequentie (MHz)'; @@ -1060,6 +1165,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contacts_manageRepeater => 'Beheer Repeater'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Beheer Ruimte Server'; @@ -1429,6 +1537,23 @@ class AppLocalizationsNl extends AppLocalizations { return 'Bericht is te lang (max $maxBytes bytes).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Bericht gekopieerd'; @@ -1646,6 +1771,66 @@ class AppLocalizationsNl extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Succesvol'; @@ -2451,6 +2636,25 @@ class AppLocalizationsNl extends AppLocalizations { @override String get repeater_codingRate => 'Codeertarief'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Locatie-instellingen'; @@ -2801,6 +3005,11 @@ class AppLocalizationsNl extends AppLocalizations { return 'Fout: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Naam opvragen'; @@ -4200,6 +4409,112 @@ class AppLocalizationsNl extends AppLocalizations { String get contacts_addContactFromClipboard => 'Contact uit klembord toevoegen'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Contact naar Klembord kopiëren'; @@ -4720,4 +5035,254 @@ class AppLocalizationsNl extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 15d33586..e5e4f026 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -294,6 +294,26 @@ class AppLocalizationsPl extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Prosimy włączyć Bluetooth, aby przeskanować urządzenia.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Wymagana przeglądarka Chrome'; @@ -542,6 +562,47 @@ class AppLocalizationsPl extends AppLocalizations { @override String get settings_debug => 'Naprawianie błędów'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Log debugowania (dla pomocy w rozwiązywaniu problemów)'; @@ -571,10 +632,29 @@ class AppLocalizationsPl extends AppLocalizations { String get settings_aboutDescription => 'Otwartoźródłowy klient Flutter dla urządzeń MeshCore LoRa do sieci mesh.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Dane wysokościowe LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Nazwa'; @@ -621,6 +701,31 @@ class AppLocalizationsPl extends AppLocalizations { @override String get settings_presets => 'Presety'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Częstotliwość (MHz)'; @@ -1077,6 +1182,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_manageRepeater => 'Zarządzaj przekaźnikiem'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Zarządzaj Serwerem Pokoju'; @@ -1451,6 +1559,23 @@ class AppLocalizationsPl extends AppLocalizations { return 'Wiadomość jest za długa (maksymalnie $maxBytes bajtów).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Wiadomość skopiowana'; @@ -1671,6 +1796,66 @@ class AppLocalizationsPl extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Sukcesy'; @@ -2482,6 +2667,25 @@ class AppLocalizationsPl extends AppLocalizations { @override String get repeater_codingRate => 'Współczynnik kodowania'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Ustawienia Lokalizacji'; @@ -2829,6 +3033,11 @@ class AppLocalizationsPl extends AppLocalizations { return 'Błąd: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Pobierz nazwę'; @@ -4230,6 +4439,112 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Dodaj kontakt z schowka'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Kopiuj kontakt do schowka'; @@ -4757,4 +5072,254 @@ class AppLocalizationsPl extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index ae4d686d..d4b996fe 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -292,6 +292,26 @@ class AppLocalizationsPt extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Por favor, ative o Bluetooth para escanear por dispositivos.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Navegador Chrome necessário'; @@ -540,6 +560,47 @@ class AppLocalizationsPt extends AppLocalizations { @override String get settings_debug => 'Depurar'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Registro de depuração auxiliar'; @@ -569,10 +630,29 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_aboutDescription => 'Um cliente Flutter de código aberto para dispositivos de rede mesh LoRa Core da MeshCore.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Dados de elevação LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Nome'; @@ -619,6 +699,31 @@ class AppLocalizationsPt extends AppLocalizations { @override String get settings_presets => 'Configurações pré-definidas'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frequência (MHz)'; @@ -1067,6 +1172,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contacts_manageRepeater => 'Gerenciar Repetidor'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Gerenciar Servidor de Sala'; @@ -1438,6 +1546,23 @@ class AppLocalizationsPt extends AppLocalizations { return 'Mensagem muito longa (máximo $maxBytes bytes).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Mensagem copiada'; @@ -1655,6 +1780,66 @@ class AppLocalizationsPt extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Sucessos'; @@ -2462,6 +2647,25 @@ class AppLocalizationsPt extends AppLocalizations { @override String get repeater_codingRate => 'Taxa de Codificação'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Configurações de Localização'; @@ -2813,6 +3017,11 @@ class AppLocalizationsPt extends AppLocalizations { return 'Erro: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Obter Nome'; @@ -4212,6 +4421,112 @@ class AppLocalizationsPt extends AppLocalizations { String get contacts_addContactFromClipboard => 'Adicionar Contato da Área de Transferência'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Copiar contato para Área de Transferência'; @@ -4733,4 +5048,254 @@ class AppLocalizationsPt extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index fd7434e1..09fe6091 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -292,6 +292,26 @@ class AppLocalizationsRu extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Пожалуйста, включите Bluetooth, чтобы найти устройства.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Требуется браузер Chrome'; @@ -539,6 +559,47 @@ class AppLocalizationsRu extends AppLocalizations { @override String get settings_debug => 'Отладка'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Журнал отладки (для сопутствующего приложения)'; @@ -568,10 +629,29 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_aboutDescription => 'Открытое клиентское приложение на Flutter для устройств MeshCore с LoRa-сетями.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Данные о высоте LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Имя'; @@ -618,6 +698,31 @@ class AppLocalizationsRu extends AppLocalizations { @override String get settings_presets => 'Пресеты'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Частота (МГц)'; @@ -1068,6 +1173,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_manageRepeater => 'Управление репитером'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Управление сервером комнат'; @@ -1439,6 +1547,23 @@ class AppLocalizationsRu extends AppLocalizations { return 'Сообщение слишком длинное (макс. $maxBytes байт).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Сообщение скопировано'; @@ -1659,6 +1784,66 @@ class AppLocalizationsRu extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'успешно'; @@ -2468,6 +2653,25 @@ class AppLocalizationsRu extends AppLocalizations { @override String get repeater_codingRate => 'Коэффициент кодирования'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Настройки местоположения'; @@ -2819,6 +3023,11 @@ class AppLocalizationsRu extends AppLocalizations { return 'Ошибка: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Получить имя'; @@ -4222,6 +4431,112 @@ class AppLocalizationsRu extends AppLocalizations { String get contacts_addContactFromClipboard => 'Добавить контакт из буфера обмена'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Копировать контакт в буфер обмена'; @@ -4751,4 +5066,254 @@ class AppLocalizationsRu extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 3e2938a3..b6f39379 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -291,6 +291,26 @@ class AppLocalizationsSk extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Prosím, zapnite Bluetooth, aby ste mohli skenovať pre zariadenia.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Vyžaduje sa prehliadač Chrome'; @@ -534,6 +554,47 @@ class AppLocalizationsSk extends AppLocalizations { @override String get settings_debug => 'Ladenie'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Logovanie pre ladenie (sprievodný log)'; @@ -563,10 +624,29 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_aboutDescription => 'Otvorený zdrojový Flutter klient pre MeshCore LoRa sieťové zariadenia.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Údaje o nadmorskej výške LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Meno'; @@ -613,6 +693,31 @@ class AppLocalizationsSk extends AppLocalizations { @override String get settings_presets => 'Prednastavenia'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frekvencia (MHz)'; @@ -1057,6 +1162,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_manageRepeater => 'Spravovať opakované zoznamy'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Spravovať server miestnosti'; @@ -1429,6 +1537,23 @@ class AppLocalizationsSk extends AppLocalizations { return 'Správa je príliš dlhá (max $maxBytes bytov).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Správa skopírovaná'; @@ -1648,6 +1773,66 @@ class AppLocalizationsSk extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Úspechy'; @@ -2454,6 +2639,25 @@ class AppLocalizationsSk extends AppLocalizations { @override String get repeater_codingRate => 'Rýchlosť kódovania'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Nastavenia polohy'; @@ -2800,6 +3004,11 @@ class AppLocalizationsSk extends AppLocalizations { return 'Chyba: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Zísť meno'; @@ -4196,6 +4405,112 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Pridať kontakt z schránky'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Kopírovať kontakt do schránky'; @@ -4717,4 +5032,254 @@ class AppLocalizationsSk extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index f46ad308..e6703edb 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -289,6 +289,26 @@ class AppLocalizationsSl extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Prosimo, vklopite Bluetooth, da lahko poiščete naprave.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Zahtevan brskalnik Chrome'; @@ -532,6 +552,47 @@ class AppLocalizationsSl extends AppLocalizations { @override String get settings_debug => 'Odpravljanje napak'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Log zapis za odpravljanje napak'; @@ -560,10 +621,29 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_aboutDescription => 'Odprtokodni Flutter klient za naprave za LoRa omrežje MeshCore.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Podatki o višini LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Ime'; @@ -610,6 +690,31 @@ class AppLocalizationsSl extends AppLocalizations { @override String get settings_presets => 'Prednastavitve'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frekvenca (MHz)'; @@ -1056,6 +1161,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_manageRepeater => 'Upravljaj Ponovitve'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Upravljajte strežnik sobe'; @@ -1427,6 +1535,23 @@ class AppLocalizationsSl extends AppLocalizations { return 'Pošiljanje sporočila je onemogočeno, saj je preveliko (maksimalno $maxBytes byte-ov).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Sporočilo poslano'; @@ -1644,6 +1769,66 @@ class AppLocalizationsSl extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Uspešni'; @@ -2450,6 +2635,25 @@ class AppLocalizationsSl extends AppLocalizations { @override String get repeater_codingRate => 'Programska hitrost'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Nastavitve lokacije'; @@ -2799,6 +3003,11 @@ class AppLocalizationsSl extends AppLocalizations { return 'Napaka: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Pridobi ime'; @@ -4190,6 +4399,112 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Dodaj stik iz odložišča'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Kopiraj stik v Odložišče'; @@ -4715,4 +5030,254 @@ class AppLocalizationsSl extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 232c592b..6496c2c5 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -288,6 +288,26 @@ class AppLocalizationsSv extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Vänligen aktivera Bluetooth för att söka efter enheter.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Chrome-webbläsare krävs'; @@ -529,6 +549,47 @@ class AppLocalizationsSv extends AppLocalizations { @override String get settings_debug => 'Felsök'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Följande felsökningslogg'; @@ -558,10 +619,29 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_aboutDescription => 'En öppen källkods Flutter-klient för MeshCore LoRa meshnätverksenheter.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS-höjddata: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Namn'; @@ -608,6 +688,31 @@ class AppLocalizationsSv extends AppLocalizations { @override String get settings_presets => 'Fördefinierade inställningar'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Frekvens (MHz)'; @@ -1051,6 +1156,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contacts_manageRepeater => 'Hantera Upprepare'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Hantera Rumserver'; @@ -1421,6 +1529,23 @@ class AppLocalizationsSv extends AppLocalizations { return 'Meddelandet är för långt (max $maxBytes byte).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Meddelandet kopierades'; @@ -1639,6 +1764,66 @@ class AppLocalizationsSv extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'framgångar'; @@ -2439,6 +2624,25 @@ class AppLocalizationsSv extends AppLocalizations { @override String get repeater_codingRate => 'Kodningsgrad'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Platsinställningar'; @@ -2785,6 +2989,11 @@ class AppLocalizationsSv extends AppLocalizations { return 'Fel: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Hämta namn'; @@ -4169,6 +4378,112 @@ class AppLocalizationsSv extends AppLocalizations { String get contacts_addContactFromClipboard => 'Lägg till kontakt från urklipp'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Kopiera kontakt till Urklipp'; @@ -4690,4 +5005,254 @@ class AppLocalizationsSv extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index a3f4b374..ed5534da 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -291,6 +291,26 @@ class AppLocalizationsUk extends AppLocalizations { String get scanner_bluetoothOffMessage => 'Будь ласка, увімкніть Bluetooth, щоб сканувати пристрої.'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => 'Потрібен браузер Chrome'; @@ -536,6 +556,47 @@ class AppLocalizationsUk extends AppLocalizations { @override String get settings_debug => 'Налагодження'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => 'Журнал відлачування (для супутника)'; @@ -566,10 +627,29 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_aboutDescription => 'Клієнт Flutter з відкритим вихідним кодом для пристроїв мережі MeshCore LoRa.'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'Дані про висоту LOS: Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => 'Ім\'я'; @@ -616,6 +696,31 @@ class AppLocalizationsUk extends AppLocalizations { @override String get settings_presets => 'Попередні налаштування'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => 'Частота (МГц)'; @@ -1063,6 +1168,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_manageRepeater => 'Керувати ретранслятором'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => 'Керувати сервером кімнати'; @@ -1433,6 +1541,23 @@ class AppLocalizationsUk extends AppLocalizations { return 'Повідомлення занадто довге (макс. $maxBytes байт).'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => 'Повідомлення скопійовано'; @@ -1654,6 +1779,66 @@ class AppLocalizationsUk extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => 'Успішно'; @@ -2465,6 +2650,25 @@ class AppLocalizationsUk extends AppLocalizations { @override String get repeater_codingRate => 'Швидкість кодування'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => 'Налаштування геопозиції'; @@ -2817,6 +3021,11 @@ class AppLocalizationsUk extends AppLocalizations { return 'Помилка: $error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => 'Отримати ім\'я'; @@ -4221,6 +4430,112 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_addContactFromClipboard => 'Додати контакт з буфера'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => 'Копіювати контакт у буфер обміну'; @@ -4752,4 +5067,254 @@ class AppLocalizationsUk extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index ab4a0533..939a329a 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -277,6 +277,26 @@ class AppLocalizationsZh extends AppLocalizations { @override String get scanner_bluetoothOffMessage => '请开启蓝牙以搜索设备'; + @override + String get scanner_connectFailedTransient => + 'The radio refused the connection (a common transient Bluetooth error). It was already retried; wait a few seconds and try again.'; + + @override + String get scanner_connectFailedTimeout => + 'The connection timed out. Check that the radio is powered, in range, and not already connected to another device.'; + + @override + String get scanner_connectFailedGeneric => + 'Could not connect to the radio. Details are in the App Debug Log.'; + + @override + String get scanner_bleReleaseWarning => + 'Radio may still be held by this device'; + + @override + String get scanner_bleReleaseWarningMessage => + 'The disconnect was not confirmed. If the radio does not reappear, toggle Bluetooth off and on, or force-stop the app.'; + @override String get scanner_chromeRequired => '需要 Chrome 浏览器'; @@ -507,6 +527,47 @@ class AppLocalizationsZh extends AppLocalizations { @override String get settings_debug => '调试'; + @override + String get settings_experimental => 'Experimental'; + + @override + String get settings_experimentalSubtitle => + 'Advanced and in-development features'; + + @override + String get settings_experimentalDescription => + 'These features are experimental and may change or be removed at any time. They default to off.'; + + @override + String get settings_coreScopeObserverCount => 'CoreScope observer counts'; + + @override + String get settings_coreScopeObserverCountSubtitle => + 'On outgoing channel messages, show how many CoreScope observers heard the packet, alongside radio-heard repeats. Needs internet.'; + + @override + String get settings_coreScopeObserverCountUnsupported => + 'Requires a firmware build with packet-hash support (v22+).'; + + @override + String get settings_experimentalDisable => 'Disable experimental features'; + + @override + String get settings_experimentalDisableSubtitle => + 'Turns off all experimental features and hides this section. Unlock again with 7 taps on the Build row.'; + + @override + String get settings_experimentalUnlocked => 'Experimental features unlocked'; + + @override + String get settings_experimentalAlreadyUnlocked => + 'Experimental features are already unlocked'; + + @override + String settings_experimentalCountdown(int count) { + return '$count more taps to unlock experimental features'; + } + @override String get settings_companionDebugLog => '调试日志'; @@ -534,10 +595,29 @@ class AppLocalizationsZh extends AppLocalizations { String get settings_aboutDescription => '一个开源的 Flutter 客户端,用于 MeshCore LoRa 无线网络设备。'; + @override + String get settings_aboutLicenses => 'View licenses'; + + @override + String get settings_aboutWebsite => 'Offband website'; + + @override + String get settings_aboutPlayStore => 'Google Play'; + + @override + String get settings_aboutDonate => 'Donate or sponsor'; + + @override + String get settings_aboutLinkFailed => 'Could not open the link'; + @override String get settings_aboutOpenMeteoAttribution => 'LOS 高程数据:Open-Meteo (CC BY 4.0)'; + @override + String get settings_aboutPresetsAttribution => + 'Regional radio presets: MeshCore\'s suggested settings, maintained by Liam Cottle (api.meshcore.nz), with Offband additions.'; + @override String get settings_infoName => '名称'; @@ -584,6 +664,31 @@ class AppLocalizationsZh extends AppLocalizations { @override String get settings_presets => '预设'; + @override + String get settings_presetSourceMeshCore => 'MeshCore'; + + @override + String get settings_presetSourceOffband => 'Offband'; + + @override + String get settings_presetsRefresh => 'Update presets'; + + @override + String get settings_presetsUpdating => 'Updating presets...'; + + @override + String get settings_presetsUpdateFailed => + 'Couldn\'t update presets. Showing the saved list.'; + + @override + String settings_presetsUpdatedAt(String date) { + return 'Presets updated $date'; + } + + @override + String get settings_presetsBundled => + 'Presets included with this version of the app'; + @override String get settings_frequency => '频率 (MHz)'; @@ -1000,6 +1105,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_manageRepeater => '管理转发节点'; + @override + String get contacts_manageSensor => 'Manage Sensor'; + @override String get contacts_manageRoom => '管理房间服务器'; @@ -1359,6 +1467,23 @@ class AppLocalizationsZh extends AppLocalizations { return '消息过长(最多 $maxBytes 字节)'; } + @override + String get composerBudgetBlockedTitle => + 'Can\'t send messages on this connection'; + + @override + String composerBudgetLimitedTitle(int maxBytes) { + return 'Only $maxBytes characters will fit'; + } + + @override + String get composerBudgetBluetoothCause => + 'The Bluetooth link negotiated a very small packet size, which leaves no room for message text. Try reconnecting, or connect by USB or Wi-Fi instead.'; + + @override + String get composerBudgetGenericCause => + 'The connection to the radio left no room for message text. Try reconnecting.'; + @override String get chat_messageCopied => '消息已复制'; @@ -1568,6 +1693,66 @@ class AppLocalizationsZh extends AppLocalizations { return 'Heard $_temp0'; } + @override + String channel_coreScopeTooltip(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count CoreScope observers', + one: '1 CoreScope observer', + ); + return 'Seen by $_temp0'; + } + + @override + String get channel_coreScopeRefresh => 'Refresh CoreScope observers'; + + @override + String get channel_coreScopeRefreshFailed => 'CoreScope unreachable'; + + @override + String get channel_coreScopeNotFound => 'Not seen by CoreScope yet'; + + @override + String channel_coreScopeCounts(int observers, int observations) { + String _temp0 = intl.Intl.pluralLogic( + observers, + locale: localeName, + other: '$observers observers', + one: '1 observer', + ); + return '$_temp0 · $observations observations'; + } + + @override + String get channel_senderNameUnknown => 'No node known by that name'; + + @override + String get channel_senderNameUnknownHint => + 'Adding needs an advert from this node'; + + @override + String get channel_senderAlreadyContact => 'Already in contacts'; + + @override + String channel_senderMultipleMatches(int count) { + return '$count nodes use this name'; + } + + @override + String get channel_senderAddNotConnected => + 'Not connected to a radio, so this sender can\'t be added yet'; + + @override + String channel_senderAddFailed(String error) { + return 'Couldn\'t add this sender: $error'; + } + + @override + String channel_senderCandidate(String keyPrefix, String type) { + return '$keyPrefix · $type'; + } + @override String get chat_successes => '成功'; @@ -2330,6 +2515,25 @@ class AppLocalizationsZh extends AppLocalizations { @override String get repeater_codingRate => '编码速率'; + @override + String get repeater_tempRadio => 'Apply temporarily'; + + @override + String get repeater_tempRadioSubtitle => + 'Uses tempradio: the node switches now and goes back to its saved radio settings after the duration. Nothing is saved on the node.'; + + @override + String get repeater_tempRadioMinutes => 'Duration (minutes)'; + + @override + String get repeater_tempRadioPathHashNote => + 'This preset\'s path hash size isn\'t applied with a temporary change: the node can\'t revert it on its own. It stays pending for a normal save.'; + + @override + String repeater_tempRadioMinutesInvalid(int max) { + return '1 to $max minutes'; + } + @override String get repeater_locationSettings => '位置设置'; @@ -2653,6 +2857,11 @@ class AppLocalizationsZh extends AppLocalizations { return '错误:$error'; } + @override + String repeater_cliCommandTimeout(String seconds) { + return 'Command timed out after $seconds seconds'; + } + @override String get repeater_cliQuickGetName => '获取名称'; @@ -3920,6 +4129,112 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_addContactFromClipboard => '从剪贴板添加联系人'; + @override + String get contacts_addByKey => 'Add by public key'; + + @override + String get contacts_addByKeyDescription => + 'Add someone using the public key they gave you. Works even if you have never heard their advert.'; + + @override + String get contacts_publicKeyLabel => 'Public key'; + + @override + String get contacts_publicKeyHelper => + '64 hex characters, or paste a meshcore:// contact link'; + + @override + String get contacts_publicKeyInvalid => + 'Enter 64 hex characters, or a meshcore:// contact link'; + + @override + String get contacts_nameLabel => 'Name'; + + @override + String get contacts_typeLabel => 'Type'; + + @override + String get contacts_addByKeyUnverifiedNote => + 'Not confirmed on air yet. The name is whatever you type here until this node sends an advert.'; + + @override + String contacts_addByKeyAdded(String name) { + return 'Added $name'; + } + + @override + String get contacts_addByKeyFailed => + 'Could not add the contact. Check the radio connection.'; + + @override + String get contacts_myContactQr => 'My contact QR'; + + @override + String get contacts_myContactQrInstructions => + 'Have them scan this, or send them the link below. It works even if they have never heard your advert.'; + + @override + String get contacts_contactLinkCopied => 'Contact link copied'; + + @override + String get contacts_qrNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + + @override + String get contacts_scanContactQr => 'Scan contact QR'; + + @override + String get contacts_scanContactQrInstructions => + 'Point the camera at a MeshCore contact QR'; + + @override + String get contacts_invalidContactQr => 'That QR is not a MeshCore contact'; + + @override + String get contacts_verifiedByAdvert => + 'Confirmed on air. This node sent a signed advert.'; + + @override + String get contacts_verifiedByMessage => + 'Key confirmed. A message with this contact went through, which only works with the matching key.'; + + @override + String get contacts_verifiedKeyOnly => + 'Added from a key. Nothing has confirmed it on air yet.'; + + @override + String get contacts_lastSeenNever => 'Not heard yet'; + + @override + String contacts_cardAddContact(String name) { + return 'Add $name'; + } + + @override + String contacts_cardAlreadyAdded(String name) { + return '$name'; + } + + @override + String get contacts_cardAlreadyAddedTooltip => 'Already in your contacts'; + + @override + String get chat_attachTooltip => 'Add to message'; + + @override + String get chat_attachGif => 'GIF'; + + @override + String get chat_attachMyContact => 'My contact card'; + + @override + String get chat_attachMyContactSubtitle => + 'Puts your public key in the message so anyone here can add you'; + + @override + String get chat_contactCardNeedsConnection => + 'Connect to a radio first, so the app knows your public key.'; + @override String get contacts_ShareContact => '复制联系人信息到剪贴板'; @@ -4385,4 +4700,254 @@ class AppLocalizationsZh extends AppLocalizations { @override String get batteryOptimizationOpenFailed => 'Couldn\'t open battery settings'; + + @override + String get stockConfig_selectAll => 'Select All'; + + @override + String get stockConfig_deselectAll => 'Deselect All'; + + @override + String get stockConfig_sectionName => 'Name'; + + @override + String get stockConfig_sectionIdentity => 'Private Identity Key'; + + @override + String get stockConfig_sectionRadio => 'Radio Settings'; + + @override + String get stockConfig_sectionPosition => 'Position Settings'; + + @override + String get stockConfig_sectionOther => 'Other Settings'; + + @override + String get stockConfig_sectionAutoAdd => 'Auto Add Settings'; + + @override + String stockConfig_sectionChannels(int count) { + return 'Channels ($count)'; + } + + @override + String stockConfig_sectionContacts(int count) { + return 'Contacts ($count)'; + } + + @override + String get stockConfig_identityWarning => + 'Your private key must be kept secret. It should only be exported as a backup.'; + + @override + String stockConfig_publicKeyLabel(String key) { + return 'Public Key: $key'; + } + + @override + String get stockConfig_privateKeyHidden => 'Private Key: hidden'; + + @override + String get exportConfig_title => 'Export Config'; + + @override + String get exportConfig_instruction => 'Please select data to export.'; + + @override + String get exportConfig_allChannels => 'All channels will be exported.'; + + @override + String get exportConfig_allContacts => 'All contacts will be exported.'; + + @override + String get exportConfig_nothingSelected => + 'Select at least one section to export.'; + + @override + String get exportConfig_lossyNotice => + 'This is the MeshCore stock format, so it cannot carry Offband-only data such as path overrides. Importing this file back into Offband will not restore that data.'; + + @override + String get exportConfig_omittedTitle => 'Some sections could not be exported'; + + @override + String exportConfig_omittedUnsupported(String section) { + return '$section: this radio\'s firmware was built without it.'; + } + + @override + String exportConfig_omittedNoReply(String section) { + return '$section: the device did not respond.'; + } + + @override + String exportConfig_omittedRejected(String section) { + return '$section: the device refused the request.'; + } + + @override + String exportConfig_omittedUnavailable(String section) { + return '$section: the device has not reported this yet.'; + } + + @override + String get exportConfig_exportAnyway => 'Export anyway'; + + @override + String get exportConfig_cancel => 'Cancel'; + + @override + String get exportConfig_shareSubject => 'MeshCore config'; + + @override + String exportConfig_failed(String message) { + return 'Export failed: $message'; + } + + @override + String get exportConfig_notConnected => + 'Connect to a device before exporting.'; + + @override + String get importConfig_title => 'Import Config'; + + @override + String get importConfig_instruction => 'Please select data to import.'; + + @override + String get importConfig_chooseFile => 'Choose a config file'; + + @override + String get importConfig_identityWarning => + 'Importing this private key will overwrite your current identity.'; + + @override + String get importConfig_channelsNote => + 'New channels will be added. Existing channels will not change.'; + + @override + String get importConfig_contactsNote => + 'New contacts will be added. Existing contacts will be updated.'; + + @override + String get importConfig_nothingSelected => + 'Select at least one section to import.'; + + @override + String get importConfig_notConnected => + 'Connect to a device before importing.'; + + @override + String importConfig_parseFailed(String message) { + return 'That file is not a MeshCore config. $message'; + } + + @override + String get importConfig_confirmIdentityTitle => + 'Overwrite this node\'s identity?'; + + @override + String get importConfig_confirmIdentityBody => + 'The node\'s current identity will be replaced with the one in this file, and every contact\'s record of this node becomes stale. This cannot be undone except by importing the previous key.'; + + @override + String get importConfig_confirmIdentityAccept => 'Overwrite identity'; + + @override + String get importConfig_cancel => 'Cancel'; + + @override + String get importConfig_resultTitle => 'Import finished'; + + @override + String importConfig_resultCounts(int contacts, int channels) { + return 'Sent $contacts contacts and $channels channels to the device.'; + } + + @override + String get importConfig_resultSkippedHeading => 'Channels not imported'; + + @override + String get importConfig_resultFailedHeading => 'Sections not applied'; + + @override + String get importConfig_reasonAlreadyPresent => + 'already on this device, so it was left unchanged'; + + @override + String get importConfig_reasonNoFreeSlot => + 'no free channel slot on the device'; + + @override + String get importConfig_reasonAbsentFromFile => 'not present in this file'; + + @override + String get importConfig_reasonNoReply => 'the device did not respond'; + + @override + String get importConfig_reasonUnsupported => + 'this radio\'s firmware was built without it'; + + @override + String get importConfig_reasonRejected => 'the device refused it'; + + @override + String get importConfig_reasonNotWritable => + 'this app cannot write every value in it'; + + @override + String importConfig_entryLine(String item, String reason) { + return '$item: $reason'; + } + + @override + String get importConfig_close => 'Close'; + + @override + String get settings_exportConfig => 'Export Config'; + + @override + String get settings_importConfig => 'Import Config'; + + @override + String get settings_configBackupSubtitle => + 'Back up or restore contacts, channels, radio settings and identity, in the MeshCore stock format.'; + + @override + String get contactSyncShortfallTitle => 'Contact sync incomplete'; + + @override + String contactSyncShortfallBody(int declared, int received) { + return 'The radio reported $declared contacts; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String contactSyncShortfallBodyNoTotal(int received) { + return 'The radio did not report how many contacts it holds; after checking again the app has $received. Your saved contacts were kept.'; + } + + @override + String get contactSyncDecisionTitle => 'Contact sync still incomplete'; + + @override + String contactSyncDecisionBody(int received, int removed) { + return 'After checking again the app still has only $received of the radio\'s contacts. Keep your saved contacts, or use the radio\'s list? Using the radio\'s list removes $removed contacts from this app.'; + } + + @override + String get contactSyncKeep => 'Keep my contacts'; + + @override + String get contactSyncUseRadio => 'Use the radio\'s list'; + + @override + String contactSyncConfirmedGone(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count saved contacts are no longer on the radio.', + one: '1 saved contact is no longer on the radio.', + ); + return '$_temp0'; + } } diff --git a/lib/main.dart b/lib/main.dart index c9e76ac4..b5e6bd5b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -30,7 +30,9 @@ import 'services/block_service.dart'; import 'services/window_geometry_service.dart'; import 'services/store_consolidation_service.dart'; import 'services/storage_health_service.dart'; +import 'services/radio_preset_service.dart'; import 'storage/drift/blob_store.dart'; +import 'widgets/contact_sync_shortfall_banner.dart'; import 'widgets/storage_unavailable_banner.dart'; import 'storage/prefs_manager.dart'; import 'utils/app_logger.dart'; @@ -118,6 +120,11 @@ void main() async { await timeoutPredictionService.initialize(); await blockService.load(); + // Regional radio presets (#728): the last good copy, or the one bundled with + // the app. The picker refreshes it from config-profiles when opened. + final radioPresetService = RadioPresetService(); + await radioPresetService.load(); + // Wire up connector with services connector.initialize( retryService: retryService, @@ -157,6 +164,7 @@ void main() async { uiViewStateService: uiViewStateService, timeoutPredictionService: timeoutPredictionService, blockService: blockService, + radioPresetService: radioPresetService, ), ); } @@ -177,6 +185,18 @@ https://open-meteo.com/en/docs/elevation-api Attribution license reference: Creative Commons Attribution 4.0 International (CC BY 4.0) https://creativecommons.org/licenses/by/4.0/ +''', + ); + yield const LicenseEntryWithLineBreaks( + ['MeshCore suggested radio presets'], + ''' +Regional radio presets are MeshCore's suggested settings, maintained by Liam +Cottle for MeshCore and published at https://api.meshcore.nz/api/v1/config. +Offband mirrors them unmodified in OffbandMesh/config-profiles and adds its +own regional presets alongside. + +MeshCore: https://github.com/meshcore-dev/MeshCore +Mirror and credit: https://github.com/OffbandMesh/config-profiles#credit ''', ); }); @@ -198,6 +218,7 @@ class MeshCoreApp extends StatelessWidget { final UiViewStateService uiViewStateService; final TimeoutPredictionService timeoutPredictionService; final BlockService blockService; + final RadioPresetService radioPresetService; const MeshCoreApp({ super.key, @@ -216,6 +237,7 @@ class MeshCoreApp extends StatelessWidget { required this.uiViewStateService, required this.timeoutPredictionService, required this.blockService, + required this.radioPresetService, }); @override @@ -237,6 +259,7 @@ class MeshCoreApp extends StatelessWidget { Provider.value(value: mapTileCacheService), ChangeNotifierProvider.value(value: timeoutPredictionService), ChangeNotifierProvider.value(value: blockService), + ChangeNotifierProvider.value(value: radioPresetService), ChangeNotifierProvider(create: (_) => ObserverConfigService(connector)), ], child: Consumer( @@ -284,7 +307,20 @@ class MeshCoreApp extends StatelessWidget { child: Consumer( builder: (context, health, _) => StorageUnavailableBanner( show: !health.available, - child: child ?? const SizedBox.shrink(), + child: Consumer( + builder: (context, connector, _) => + ContactSyncShortfallBanner( + shortfall: connector.contactSyncShortfall, + decisionPending: + connector.contactSyncDecisionPending, + undeliveredCount: + connector.contactSyncUndeliveredCount, + onDismiss: connector.dismissContactSyncShortfall, + onKeep: connector.resolveContactSyncKeepLocal, + onUseRadio: connector.resolveContactSyncUseRadio, + child: child ?? const SizedBox.shrink(), + ), + ), ), ), ), diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 4997403c..7e95baa1 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -139,6 +139,16 @@ class AppSettings { final String themeMode; final String? languageOverride; // null = system default final bool appDebugLogEnabled; + + /// Owner-only Experimental settings section, revealed by a 7-tap gesture on + /// the version row (#509). Not a security boundary, just keeps advanced/ + /// me-centric toggles out of the default UI. Persists across restarts. + final bool experimentalUnlocked; + + /// Owner-only: show CoreScope-observed repeat counts on outgoing channel + /// messages (#524). Lives under the Experimental section, default off, and + /// only takes effect when the firmware supports the 0xC6 packet-hash query. + final bool coreScopeObserverCountEnabled; final Map batteryChemistryByDeviceId; final Map batteryChemistryByRepeaterId; final UnitSystem unitSystem; @@ -217,6 +227,8 @@ class AppSettings { this.themeMode = 'system', this.languageOverride, this.appDebugLogEnabled = false, + this.experimentalUnlocked = false, + this.coreScopeObserverCountEnabled = false, Map? batteryChemistryByDeviceId, Map? batteryChemistryByRepeaterId, this.unitSystem = UnitSystem.metric, @@ -283,6 +295,8 @@ class AppSettings { 'theme_mode': themeMode, 'language_override': languageOverride, 'app_debug_log_enabled': appDebugLogEnabled, + 'experimental_unlocked': experimentalUnlocked, + 'corescope_observer_count_enabled': coreScopeObserverCountEnabled, 'battery_chemistry_by_device_id': batteryChemistryByDeviceId, 'battery_chemistry_by_repeater_id': batteryChemistryByRepeaterId, 'unit_system': unitSystem.value, @@ -380,6 +394,9 @@ class AppSettings { themeMode: json['theme_mode'] as String? ?? 'system', languageOverride: json['language_override'] as String?, appDebugLogEnabled: json['app_debug_log_enabled'] as bool? ?? false, + experimentalUnlocked: json['experimental_unlocked'] as bool? ?? false, + coreScopeObserverCountEnabled: + json['corescope_observer_count_enabled'] as bool? ?? false, batteryChemistryByDeviceId: (json['battery_chemistry_by_device_id'] as Map?)?.map( (key, value) => MapEntry(key.toString(), value.toString()), @@ -497,6 +514,8 @@ class AppSettings { String? themeMode, Object? languageOverride = _unset, bool? appDebugLogEnabled, + bool? experimentalUnlocked, + bool? coreScopeObserverCountEnabled, Map? batteryChemistryByDeviceId, Map? batteryChemistryByRepeaterId, UnitSystem? unitSystem, @@ -556,6 +575,9 @@ class AppSettings { ? this.languageOverride : languageOverride as String?, appDebugLogEnabled: appDebugLogEnabled ?? this.appDebugLogEnabled, + experimentalUnlocked: experimentalUnlocked ?? this.experimentalUnlocked, + coreScopeObserverCountEnabled: + coreScopeObserverCountEnabled ?? this.coreScopeObserverCountEnabled, batteryChemistryByDeviceId: batteryChemistryByDeviceId ?? this.batteryChemistryByDeviceId, batteryChemistryByRepeaterId: diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index 092f00a4..b84a69bc 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -46,6 +46,20 @@ class ChannelMessage { final int? channelIndex; final String messageId; final String? packetHash; + + /// Firmware-reported on-air packet hash for an outgoing channel message + /// (from the 0xC6 query, #524/#611). Distinct from [packetHash], which for + /// received messages is the content hash used for repeat dedup. Used only to + /// query CoreScope for observer counts. Transient (not persisted). + final String? onAirHash; + + /// Unique observers CoreScope reports for this message's on-air packet + /// (#524). Null until queried / when the feature is off. Transient. + final int? coreScopeObserverCount; + + /// Total observations (sightings) CoreScope reports for the same packet, the + /// "Observations (N)" number in its UI. Transient. See [coreScopeObserverCount]. + final int? coreScopeObservationCount; final String? replyToMessageId; final String? replyToSenderName; final String? replyToText; @@ -84,6 +98,9 @@ class ChannelMessage { this.channelIndex, String? messageId, this.packetHash, + this.onAirHash, + this.coreScopeObserverCount, + this.coreScopeObservationCount, this.replyToMessageId, this.replyToSenderName, this.replyToText, @@ -130,6 +147,9 @@ class ChannelMessage { Uint8List? pathBytes, List? pathVariants, String? packetHash, + String? onAirHash, + int? coreScopeObserverCount, + int? coreScopeObservationCount, String? replyToMessageId, String? replyToSenderName, String? replyToText, @@ -170,6 +190,11 @@ class ChannelMessage { channelIndex: channelIndex, messageId: messageId, packetHash: packetHash ?? this.packetHash, + onAirHash: onAirHash ?? this.onAirHash, + coreScopeObserverCount: + coreScopeObserverCount ?? this.coreScopeObserverCount, + coreScopeObservationCount: + coreScopeObservationCount ?? this.coreScopeObservationCount, replyToMessageId: replyToMessageId ?? this.replyToMessageId, replyToSenderName: replyToSenderName ?? this.replyToSenderName, replyToText: replyToText ?? this.replyToText, @@ -261,6 +286,7 @@ class ChannelMessage { String text, String senderName, int channelIndex, { + int? timestampSecs, String? originalText, String? translatedLanguageCode, String? translationModelId, @@ -272,7 +298,11 @@ class ChannelMessage { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, - timestamp: DateTime.now(), + // When supplied, match the exact seconds put in the send frame so the + // 0xC6 (ts, channel) key correlates (#524); else fall back to now. + timestamp: timestampSecs != null + ? DateTime.fromMillisecondsSinceEpoch(timestampSecs * 1000) + : DateTime.now(), isOutgoing: true, status: ChannelMessageStatus.pending, pathLength: null, diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 972c04ff..f4d1dc6b 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -260,6 +260,213 @@ class Contact { } } + /// True once this contact has been confirmed on air by a signed advert. + /// + /// [lastSeen] maps to the firmware `last_advert_timestamp`, which a contact + /// created from a bare key deliberately carries as the epoch so the advert + /// replay guard cannot mute it (#627). That same sentinel doubles as the + /// verification signal, for free, and it clears itself the moment a genuine + /// advert arrives and the radio rewrites the field. (#630) + bool get isAdvertVerified => lastSeen.millisecondsSinceEpoch != 0; + + /// Reference-app contact share URI for this contact, the inverse of + /// [fromShareUri]. This is what the stock app accepts, so emitting it is + /// what makes Offband cards and QRs importable by non-Offband users. (#626) + /// + /// Note this shares only the identity. It carries no path and no advert, so + /// the receiving side gets an unverified stub exactly as we do. + String toShareUri() => + buildShareUri(publicKeyHex: publicKeyHex, name: name, type: type); + + /// Builds the reference-app contact share URI from raw parts. + /// + /// Separate from [toShareUri] so the local device can share its OWN identity, + /// which is a public key and a node name rather than a [Contact]. (#626) + /// + /// Spaces are percent-encoded rather than emitted as `+`. Both decode to a + /// space, and this matches [Channel.toShareUri], which is already documented + /// as round-tripping with the reference app's QR. (#161) + static String buildShareUri({ + required String publicKeyHex, + required String name, + int type = advTypeChat, + }) => + 'meshcore://contact/add' + '?name=${Uri.encodeComponent(name)}' + '&public_key=$publicKeyHex' + '&type=$type'; + + /// The body of one compact channel share, ``, captured + /// without its delimiters. `[^>]*` cannot cross a closing bracket, so each + /// card matches individually even when several sit in one message. + static final RegExp _channelShareBody = RegExp( + r'<([0-9a-fA-F]{64}:\d+:[^>]*)>', + ); + + /// Compact contact share for a CHANNEL message, ``. (#611) + /// + /// This is a second, different format from [toShareUri], and deliberately so. + /// It is what real clients put on the air, observed live in `#test` and + /// `#hamradio`, and it is far cheaper: about 75 bytes against 117 for the + /// equivalent URI. Channel text shares a 160-byte payload with the + /// `Sender: ` prefix, so that difference is airtime, not neatness. + /// + /// Use the URI form for a QR, a DM, or an out-of-band paste. Use this for a + /// channel. + String toChannelShare() => + buildChannelShare(publicKeyHex: publicKeyHex, name: name, type: type); + + /// Builds the compact channel share from raw parts, so this device can share + /// its OWN identity without constructing a [Contact]. (#611) + /// + /// Angle brackets are the delimiters, so any in [name] are dropped: a name + /// carrying one would truncate the payload for every parser reading it. A + /// colon is left alone, because the name is the final field and a correct + /// parser splits on the first two colons only. + static String buildChannelShare({ + required String publicKeyHex, + required String name, + int type = advTypeChat, + }) { + final safeName = name.replaceAll('<', '').replaceAll('>', ''); + return '<$publicKeyHex:$type:$safeName>'; + } + + /// Parses the compact channel share ``, or null. (#611) + /// + /// The counterpart to [toChannelShare]. Without this the app would emit a + /// format it could not itself accept, and a user copying a card out of a + /// channel and pasting it into the add dialog would be rejected. + /// + /// Splits on the FIRST TWO colons only. The name is the final field and may + /// contain colons, spaces, emoji and CJK, so splitting on the last colon or + /// on every colon corrupts real names. + /// + /// Rendering a received card as a tappable Add Contact affordance is #610 and + /// is separate; this only handles text pasted or scanned into the add flow. + static Contact? fromChannelShare(String text) { + // Tolerate a card embedded in a longer message, which is how it arrives, + // and take the FIRST well-formed one. + // + // Deliberately not a scan from the first `<` to the last `>`: a message + // carrying two cards would then be read as a single span running from the + // first key to the last name and parse as garbage. That is reachable, + // because the add dialog passes raw pasted text straight to here. + // (Gemini review, #610) + final match = _channelShareBody.firstMatch(text); + if (match == null) return null; + final body = match.group(1)!; + + final firstColon = body.indexOf(':'); + if (firstColon < 0) return null; + final secondColon = body.indexOf(':', firstColon + 1); + if (secondColon < 0) return null; + + final keyHex = body.substring(0, firstColon).toLowerCase(); + if (keyHex.length != pubKeySize * 2) return null; + final Uint8List publicKey; + try { + publicKey = hex2Uint8List(keyHex); + } on FormatException { + return null; + } + + final type = int.tryParse(body.substring(firstColon + 1, secondColon)); + if (type == null || type < advTypeChat || type > advTypeSensor) return null; + + final name = body.substring(secondColon + 1); + + return Contact( + publicKey: publicKey, + name: name.isEmpty ? 'Unknown' : name, + type: type, + flags: 0, + pathLength: -1, + path: Uint8List(0), + // Same unverified stub as the URI path, and for the same reason: the + // epoch keeps the firmware advert replay guard from muting it. (#620) + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + rawPacket: null, + ); + } + + /// Parses a contact from the reference-app share URI, or null if malformed. + /// + /// `meshcore://contact/add?name=&public_key=<64 hex>&type=<1-4>` + /// + /// Spec: MeshCore firmware `docs/qr_codes.md`, the format the stock mobile + /// app emits for both its contact QR and its share link. The payload is a + /// BARE public key, not a signed advert, so the result is an identity stub: + /// no path, no position, nothing the mesh has confirmed. A QR is this same + /// URI rendered visually, so scanning shares this parser. (#625) + /// + /// Returns null for the fork's older `meshcore://` form, + /// whose host is the leading hex rather than `contact`. Callers keep handling + /// that separately: it carries a full signed advert and is strictly richer. + static Contact? fromShareUri(String uri) { + final parsed = Uri.tryParse(uri.trim()); + if (parsed == null || parsed.scheme != 'meshcore') return null; + if (parsed.host != 'contact') return null; + if (parsed.path.replaceAll('/', '') != 'add') return null; + + final keyHex = parsed.queryParameters['public_key']; + if (keyHex == null || keyHex.length != pubKeySize * 2) return null; + + final Uint8List publicKey; + try { + publicKey = hex2Uint8List(keyHex); + } on FormatException { + return null; + } + + // `type` is optional; stock always emits it, but a key alone is still a + // usable identity. Out-of-range values are rejected rather than clamped: + // in a three-parameter URI an impossible type signals corruption, and + // silently mis-typing a contact is a user-visible defect. Widen this + // deliberately if the spec ever adds a type. + final typeRaw = parsed.queryParameters['type']; + int type = advTypeChat; + if (typeRaw != null && typeRaw.isNotEmpty) { + final parsedType = int.tryParse(typeRaw); + if (parsedType == null || + parsedType < advTypeChat || + parsedType > advTypeSensor) { + return null; + } + type = parsedType; + } + + final name = parsed.queryParameters['name']; + + return Contact( + publicKey: publicKey, + // Matches fromFrame's convention for a nameless contact. + name: (name == null || name.isEmpty) ? 'Unknown' : name, + type: type, + flags: 0, + // Flood until the mesh teaches us a path. Mirrors the firmware's + // OUT_PATH_UNKNOWN for a contact that has never been routed to. + pathLength: -1, + path: Uint8List(0), + // Deliberately the epoch, NOT DateTime.now(). + // + // This maps to the firmware's `last_advert_timestamp`, which the advert + // handler compares with `timestamp <= last_advert_timestamp` and treats + // a non-greater value as a replay attack (`BaseChatMesh.cpp:142-145`). + // Stamping "now" would leave this contact permanently deaf to its own + // adverts, because advert timestamps come from the SENDER's clock and + // clocks in the field run years behind. Zero lets any genuine advert win + // and upgrade the stub in place. (#620) + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + // No advert packet, so this contact cannot be re-shared until one + // arrives. The share path already gates on rawPacket. + rawPacket: null, + ); + } + + /// True if [uri] is a valid reference-app contact share URI. (#625) + static bool isValidShareUri(String uri) => fromShareUri(uri) != null; + @override bool operator ==(Object other) => other is Contact && publicKeyHex == other.publicKeyHex; diff --git a/lib/models/radio_preset.dart b/lib/models/radio_preset.dart new file mode 100644 index 00000000..b04cf33a --- /dev/null +++ b/lib/models/radio_preset.dart @@ -0,0 +1,294 @@ +import 'dart:convert'; + +import 'radio_settings.dart'; + +// Regional radio presets (#647). Two sources, both published in the +// OffbandMesh/config-profiles repo under radio-presets/ (schema in its SCHEMA.md): +// - meshcore-upstream.json: MeshCore's suggested presets (maintained by Liam +// Cottle), mirrored unmodified; numbers arrive as strings. +// - offband.json: Offband's overlay; numbers are JSON numbers. +// Parsing is resilient: a malformed entry is skipped and counted, never fatal, +// but a file of the wrong format or a newer format_version is rejected. + +const String kUpstreamPresetFormat = 'meshcore-upstream-radio-presets'; +const String kOverlayPresetFormat = 'offband-radio-presets'; + +/// Highest format_version this build understands, for both files. +const int kRadioPresetFormatVersion = 1; + +enum RadioPresetSource { meshcore, offband } + +class RadioPreset { + const RadioPreset({ + required this.id, + required this.title, + required this.region, + required this.frequencyMHz, + required this.bandwidth, + required this.spreadingFactor, + required this.codingRate, + required this.source, + this.txPowerDbm, + this.pathHashBytes, + this.offGrid = false, + }); + + final String id; + final String title; + + /// Picker group, e.g. "USA", "Australia", "Off-Grid". + final String region; + final double frequencyMHz; + final LoRaBandwidth bandwidth; + final LoRaSpreadingFactor spreadingFactor; + final LoRaCodingRate codingRate; + final RadioPresetSource source; + + /// Null leaves the radio's TX power alone (upstream presets never set it). + final int? txPowerDbm; + + /// Path hash size in bytes (1-3), as published. Null leaves the radio's + /// setting alone. + final int? pathHashBytes; + + /// A client-repeat (off-grid) frequency rather than a regional preset. + final bool offGrid; + + /// Frequency in kHz, the unit CMD_SET_RADIO_PARAMS carries. + int get frequencyKHz => (frequencyMHz * 1000).round(); + + /// The firmware's path hash mode for [pathHashBytes], or null to leave it. + /// + /// Presets publish the size in bytes; firmware takes a zero-based mode + /// (`sendFlood(..., path_hash_mode + 1)`): 1 byte = mode 0, 2 bytes = mode 1, + /// 3 bytes = mode 2. Passing a published 2 straight through would select + /// 3-byte hashes and put the node off its mesh. + int? get pathHashMode => pathHashModeForBytes(pathHashBytes); +} + +/// Whether a radio using [radioPathHashBytes] fits [preset]'s path hash +/// (#747). Presets without a path hash fit any radio; one with a size only +/// fits a radio on that size. Without this, presets that differ only by path +/// hash (MeshCore's "Canada" 3-byte and "USA") are indistinguishable. +bool presetPathHashMatches(RadioPreset preset, int radioPathHashBytes) => + preset.pathHashBytes == null || preset.pathHashBytes == radioPathHashBytes; + +/// Zero-based firmware path hash mode for a published size in bytes (1-3). +/// Null for null or out-of-range input, so nothing is sent. +int? pathHashModeForBytes(int? bytes) { + if (bytes == null || bytes < 1 || bytes > 3) return null; + return bytes - 1; +} + +class RadioPresetFormatException implements Exception { + const RadioPresetFormatException(this.message); + final String message; + @override + String toString() => 'RadioPresetFormatException: $message'; +} + +class RadioPresetParseResult { + const RadioPresetParseResult(this.presets, this.skipped); + final List presets; + + /// Malformed entries left out, so a partly bad file never looks complete. + final int skipped; +} + +/// Parse the mirrored MeshCore list (`meshcore-upstream.json`). +RadioPresetParseResult parseUpstreamPresets(String source) { + final doc = _decodeObject(source, kUpstreamPresetFormat); + final srs = doc['suggested_radio_settings']; + final entries = srs is Map ? srs['entries'] : null; + if (entries is! List) { + throw const RadioPresetFormatException( + 'suggested_radio_settings.entries must be a list', + ); + } + final presets = []; + var skipped = 0; + for (final e in entries) { + final preset = e is Map ? _upstreamEntry(e) : null; + if (preset == null) { + skipped++; + } else { + presets.add(preset); + } + } + return RadioPresetParseResult(presets, skipped); +} + +/// Parse the Offband overlay (`offband.json`). Retired entries are dropped. +RadioPresetParseResult parseOverlayPresets(String source) { + final doc = _decodeObject(source, kOverlayPresetFormat); + final entries = doc['presets']; + if (entries is! List) { + throw const RadioPresetFormatException('presets must be a list'); + } + final presets = []; + var skipped = 0; + for (final e in entries) { + if (e is Map && e['status'] == 'retired') continue; + final preset = e is Map ? _overlayEntry(e) : null; + if (preset == null) { + skipped++; + } else { + presets.add(preset); + } + } + return RadioPresetParseResult(presets, skipped); +} + +Map _decodeObject(String source, String format) { + final dynamic doc; + try { + doc = jsonDecode(source); + } on FormatException catch (e) { + throw RadioPresetFormatException('not valid JSON: ${e.message}'); + } + if (doc is! Map) { + throw const RadioPresetFormatException('must be a JSON object'); + } + if (doc['format'] != format) { + throw RadioPresetFormatException('format must be "$format"'); + } + final version = doc['format_version']; + if (version is! int) { + throw const RadioPresetFormatException('format_version is required'); + } + if (version > kRadioPresetFormatVersion) { + throw RadioPresetFormatException( + 'format_version $version is newer than this app supports ' + '($kRadioPresetFormatVersion). Update the app.', + ); + } + return doc; +} + +RadioPreset? _upstreamEntry(Map e) { + final title = e['title']; + if (title is! String || title.trim().isEmpty) return null; + final ns = e['network_settings']; + final hash = ns is Map ? _asInt(ns['path_hash_size']) : null; + if (ns is Map && ns.containsKey('path_hash_size') && !_validHash(hash)) { + return null; + } + return _build( + id: 'meshcore:$title', + title: title, + region: upstreamRegionFor(title), + frequency: _asDouble(e['frequency']), + bandwidthKHz: _asDouble(e['bandwidth']), + sf: _asInt(e['spreading_factor']), + cr: _asInt(e['coding_rate']), + source: RadioPresetSource.meshcore, + pathHashBytes: hash, + ); +} + +RadioPreset? _overlayEntry(Map e) { + final id = e['id']; + final title = e['title']; + final region = e['region']; + if (id is! String || id.isEmpty) return null; + if (title is! String || title.trim().isEmpty) return null; + if (region is! String || region.trim().isEmpty) return null; + // The overlay is hand-edited: numbers must be JSON numbers, not strings. + for (final key in const [ + 'frequency', + 'bandwidth', + 'spreading_factor', + 'coding_rate', + ]) { + if (e[key] is! num) return null; + } + final tx = e['tx_power']; + if (tx != null && (tx is! int || tx < -9 || tx > 30)) return null; + final hash = e['path_hash_size']; + if (hash != null && (hash is! int || !_validHash(hash))) return null; + final offGrid = e['off_grid']; + if (offGrid != null && offGrid is! bool) return null; + return _build( + id: 'offband:$id', + title: title, + region: region, + frequency: (e['frequency'] as num).toDouble(), + bandwidthKHz: (e['bandwidth'] as num).toDouble(), + sf: _asInt(e['spreading_factor']), + cr: _asInt(e['coding_rate']), + source: RadioPresetSource.offband, + txPowerDbm: tx as int?, + pathHashBytes: hash as int?, + offGrid: offGrid == true, + ); +} + +RadioPreset? _build({ + required String id, + required String title, + required String region, + required double? frequency, + required double? bandwidthKHz, + required int? sf, + required int? cr, + required RadioPresetSource source, + int? txPowerDbm, + int? pathHashBytes, + bool offGrid = false, +}) { + if (frequency == null || frequency < 150 || frequency > 2500) return null; + if (bandwidthKHz == null) return null; + final bwHz = (bandwidthKHz * 1000).round(); + final bandwidth = LoRaBandwidth.values + .where((b) => (b.hz - bwHz).abs() <= 50) + .firstOrNull; + final spreading = LoRaSpreadingFactor.values + .where((s) => s.value == sf) + .firstOrNull; + final coding = LoRaCodingRate.values.where((c) => c.value == cr).firstOrNull; + if (bandwidth == null || spreading == null || coding == null) return null; + return RadioPreset( + id: id, + title: title.trim(), + region: region.trim(), + frequencyMHz: frequency, + bandwidth: bandwidth, + spreadingFactor: spreading, + codingRate: coding, + source: source, + txPowerDbm: txPowerDbm, + pathHashBytes: pathHashBytes, + offGrid: offGrid, + ); +} + +bool _validHash(int? bytes) => bytes != null && bytes >= 1 && bytes <= 3; + +double? _asDouble(Object? v) { + if (v is num) return v.toDouble(); + if (v is String) return double.tryParse(v.trim()); + return null; +} + +int? _asInt(Object? v) { + final d = _asDouble(v); + if (d == null || d != d.roundToDouble()) return null; + return d.round(); +} + +/// The picker group for an upstream title, which carries no region field: +/// the part before " - ", ":" or " (" ("USA - Southern California" -> "USA", +/// "Australia: QLD" -> "Australia", "EU/UK (Narrow)" -> "EU/UK"), otherwise the +/// title without a trailing band number ("Portugal 433" -> "Portugal"), +/// otherwise the whole title ("Costa Rica"). +String upstreamRegionFor(String title) { + final t = title.trim(); + var cut = t.length; + for (final sep in const [' - ', ':', ' (']) { + final i = t.indexOf(sep); + if (i > 0 && i < cut) cut = i; + } + if (cut < t.length) return t.substring(0, cut).trim(); + final band = RegExp(r'^(.+?)\s+\d+$').firstMatch(t); + return band != null ? band.group(1)! : t; +} diff --git a/lib/models/radio_settings.dart b/lib/models/radio_settings.dart index e74cf209..9e8efe10 100644 --- a/lib/models/radio_settings.dart +++ b/lib/models/radio_settings.dart @@ -1,3 +1,6 @@ +// LoRa radio parameter values. The regional presets that combine them live in +// radio_preset.dart and come from OffbandMesh/config-profiles (#647). + enum LoRaBandwidth { bw7_8(7800, '7.8 kHz'), bw10_4(10400, '10.4 kHz'), @@ -43,489 +46,3 @@ enum LoRaCodingRate { const LoRaCodingRate(this.value, this.label); } - -class RadioSettings { - final double frequencyMHz; - final LoRaBandwidth bandwidth; - final LoRaSpreadingFactor spreadingFactor; - final LoRaCodingRate codingRate; - final int txPowerDbm; - - RadioSettings({ - required this.frequencyMHz, - required this.bandwidth, - required this.spreadingFactor, - required this.codingRate, - required this.txPowerDbm, - }); - - // Regional preset configurations - static final List<(String, RadioSettings)> presets = [ - ( - 'Australia', - RadioSettings( - frequencyMHz: 915.8, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf10, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Australia (Narrow)', - RadioSettings( - frequencyMHz: 916.575, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Australia SA, WA, QLD', - RadioSettings( - frequencyMHz: 923.125, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Czech Republic', - RadioSettings( - frequencyMHz: 869.432, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'EU 433MHz', - RadioSettings( - frequencyMHz: 433.650, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'EU/UK (Long Range)', - RadioSettings( - frequencyMHz: 869.525, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'EU/UK (Medium Range)', - RadioSettings( - frequencyMHz: 869.525, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf10, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'EU/UK (Narrow)', - RadioSettings( - frequencyMHz: 869.618, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'New Zealand', - RadioSettings( - frequencyMHz: 917.375, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'New Zealand (Narrow)', - RadioSettings( - frequencyMHz: 917.375, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Portugal 433', - RadioSettings( - frequencyMHz: 433.375, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf9, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Portugal 869', - RadioSettings( - frequencyMHz: 869.618, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'Russia Artyom (VVO)', - RadioSettings( - frequencyMHz: 864.281, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Biysk (BSK)', - RadioSettings( - frequencyMHz: 869.000, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Russia Chelyabinsk (CEK)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Cherepovets (CEE)', - RadioSettings( - frequencyMHz: 868.570, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Irkutsk (IKT)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Ivanovo (IWA)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Izhevsk (IJK)', - RadioSettings( - frequencyMHz: 868.732, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Kaluga (KLF)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Kazan (KZN)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Khabarovsk (KHV)', - RadioSettings( - frequencyMHz: 864.281, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Kirov (KVX)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Lipetsk (LPK)', - RadioSettings( - frequencyMHz: 868.950, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf9, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Moscow (MOW)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Nizhny Novgorod (GOJ)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Novosibirsk (OVB)', - RadioSettings( - frequencyMHz: 869.000, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf9, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Rostov-on-Don (ROV)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf9, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Ryazan (RZN)', - RadioSettings( - frequencyMHz: 868.880, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf9, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Russia Samara (KUF)', - RadioSettings( - frequencyMHz: 864.281, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Saratov (GSV)', - RadioSettings( - frequencyMHz: 864.281, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia St. Petersburg (LED)', - RadioSettings( - frequencyMHz: 868.856, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Tambov (TBW)', - RadioSettings( - frequencyMHz: 868.950, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf10, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Russia Tula (TYA)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Tver (KLD)', - RadioSettings( - frequencyMHz: 869.169, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Ufa (UFA)', - RadioSettings( - frequencyMHz: 868.732, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Russia Volgograd (VOG)', - RadioSettings( - frequencyMHz: 869.525, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Russia Voronezh (VOZ)', - RadioSettings( - frequencyMHz: 868.731, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_6, - txPowerDbm: 20, - ), - ), - ( - 'Russia Yekaterinburg (SVX)', - RadioSettings( - frequencyMHz: 869.046, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_7, - txPowerDbm: 20, - ), - ), - ( - 'Switzerland', - RadioSettings( - frequencyMHz: 869.618, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf8, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 14, - ), - ), - ( - 'USA Arizona', - RadioSettings( - frequencyMHz: 908.205, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf10, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'USA/Canada', - RadioSettings( - frequencyMHz: 910.525, - bandwidth: LoRaBandwidth.bw62_5, - spreadingFactor: LoRaSpreadingFactor.sf7, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - ( - 'Vietnam', - RadioSettings( - frequencyMHz: 920.250, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_5, - txPowerDbm: 20, - ), - ), - // Off-grid repeat presets (valid client_repeat frequencies) - ( - 'Off-Grid 433', - RadioSettings( - frequencyMHz: 433.0, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ( - 'Off-Grid 869', - RadioSettings( - frequencyMHz: 869.0, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 14, - ), - ), - ( - 'Off-Grid 918', - RadioSettings( - frequencyMHz: 918.0, - bandwidth: LoRaBandwidth.bw250, - spreadingFactor: LoRaSpreadingFactor.sf11, - codingRate: LoRaCodingRate.cr4_8, - txPowerDbm: 20, - ), - ), - ]; - - int get frequencyHz => (frequencyMHz * 1000).round(); - int get bandwidthHz => bandwidth.hz; - int get sf => spreadingFactor.value; - int get cr => codingRate.value; -} diff --git a/lib/models/stock_config.dart b/lib/models/stock_config.dart new file mode 100644 index 00000000..086c91c9 --- /dev/null +++ b/lib/models/stock_config.dart @@ -0,0 +1,624 @@ +/// MeshCore stock companion config export format (#572, epic #568). +/// +/// This is a faithful model of the JSON file the official MeshCore Companion +/// app writes from its Export Config screen, so that a stock export imports +/// into Offband and an Offband export imports into stock. The shape was +/// reverse-engineered from ten real exports across five radios (2359 contacts, +/// 76 channels); the evidence is recorded on issue #569. +/// +/// Rules the format imposes, none of them obvious: +/// +/// * **There is no version field.** Stock writes none, so we write none, and +/// validation is by shape alone. Every top-level section is independently +/// optional because the export screen lets the user deselect any of them. +/// * `public_key` and `private_key` are one unit: stock's single "Private +/// Identity Key" control emits both or neither. +/// * `radio_settings` mixes units: `frequency` is kHz, `bandwidth` is Hz, and +/// `coding_rate` is a bare denominator (5 means 4/5). +/// * Latitudes and longitudes are JSON **strings**, never numbers. +/// * `channels` has no index field; array position is the channel index. +/// * Contact timestamps are whatever the mesh reported and are not sanitized. +/// The real corpus contains values from epoch 14 to the year 2095. +library; + +import 'dart:convert'; +import 'dart:typed_data'; + +import '../connector/meshcore_protocol.dart' show pubKeyToHex; + +/// Thrown when a config file does not match the stock format. +/// +/// Carries the offending JSON path so an import screen can tell the user which +/// part of the file is wrong rather than just "invalid file". +class StockConfigFormatException implements Exception { + StockConfigFormatException(this.message, {this.path}); + + final String message; + + /// Dotted path to the offending value, e.g. `contacts[3].out_path_list`. + final String? path; + + @override + String toString() => path == null + ? 'StockConfigFormatException: $message' + : 'StockConfigFormatException at $path: $message'; +} + +/// Firmware caps a contact name at `char name[32]`, so 31 usable characters. +const int kStockMaxContactNameChars = 31; + +const int _publicKeyBytes = 32; +const int _privateKeyBytes = 64; +const int _channelSecretBytes = 16; + +/// Hop-hash widths the parser will accept, in bytes. +/// +/// Only width 2 has been observed in the wild (a single path across the whole +/// corpus). 1 and 3 are accepted because the firmware path-length byte encodes +/// widths 1..3 (#309) and there is no reason stock would refuse to emit them. +/// Anything else is rejected rather than guessed at. +const Set kStockPathHashWidths = {1, 2, 3}; + +Uint8List _parseHex(String value, String path, {int? expectBytes}) { + if (value.length.isOdd) { + throw StockConfigFormatException( + 'expected hex, got an odd number of characters (${value.length})', + path: path, + ); + } + final bytes = Uint8List(value.length ~/ 2); + for (var i = 0; i < bytes.length; i++) { + final byte = int.tryParse(value.substring(i * 2, i * 2 + 2), radix: 16); + if (byte == null) { + throw StockConfigFormatException('expected hex characters', path: path); + } + bytes[i] = byte; + } + if (expectBytes != null && bytes.length != expectBytes) { + throw StockConfigFormatException( + 'expected $expectBytes bytes, got ${bytes.length}', + path: path, + ); + } + return bytes; +} + +Map _asObject(Object? value, String path) { + if (value is! Map) { + throw StockConfigFormatException('expected an object', path: path); + } + return value.cast(); +} + +int _asInt(Object? value, String path) { + if (value is int) return value; + throw StockConfigFormatException('expected an integer', path: path); +} + +bool _asBool(Object? value, String path) { + if (value is bool) return value; + throw StockConfigFormatException('expected a boolean', path: path); +} + +String _asString(Object? value, String path) { + if (value is String) return value; + throw StockConfigFormatException('expected a string', path: path); +} + +/// Stock writes coordinates as decimal strings, so `0.0` and `39.561991` both +/// appear verbatim. Dart's shortest-round-trip `double.toString()` reproduces +/// exactly that, which is why [_coordToJson] is a plain `toString`. +double _parseCoord(Object? value, String path) { + final text = _asString(value, path); + final parsed = double.tryParse(text); + if (parsed == null) { + throw StockConfigFormatException( + 'expected a decimal coordinate string', + path: path, + ); + } + return parsed; +} + +String _coordToJson(double value) => value.toString(); + +/// LoRa parameters. Units differ per field. See the class doc on [StockConfig]. +class StockRadioSettings { + const StockRadioSettings({ + required this.frequencyKhz, + required this.bandwidthHz, + required this.spreadingFactor, + required this.codingRate, + required this.txPower, + }); + + /// `frequency`, in **kHz** (910525 means 910.525 MHz). + final int frequencyKhz; + + /// `bandwidth`, in **Hz** (62500 means 62.5 kHz). + final int bandwidthHz; + + final int spreadingFactor; + + /// `coding_rate`, the **denominator only**, 5 means 4/5. + final int codingRate; + + /// `tx_power`, in dBm. + final int txPower; + + factory StockRadioSettings.fromJson(Map json, String path) { + return StockRadioSettings( + frequencyKhz: _asInt(json['frequency'], '$path.frequency'), + bandwidthHz: _asInt(json['bandwidth'], '$path.bandwidth'), + spreadingFactor: _asInt( + json['spreading_factor'], + '$path.spreading_factor', + ), + codingRate: _asInt(json['coding_rate'], '$path.coding_rate'), + txPower: _asInt(json['tx_power'], '$path.tx_power'), + ); + } + + Map toJson() => { + 'frequency': frequencyKhz, + 'bandwidth': bandwidthHz, + 'spreading_factor': spreadingFactor, + 'coding_rate': codingRate, + 'tx_power': txPower, + }; +} + +/// The device's own advertised position. Both values are strings on the wire. +class StockPositionSettings { + const StockPositionSettings({ + required this.latitude, + required this.longitude, + }); + + final double latitude; + final double longitude; + + factory StockPositionSettings.fromJson( + Map json, + String path, + ) { + return StockPositionSettings( + latitude: _parseCoord(json['latitude'], '$path.latitude'), + longitude: _parseCoord(json['longitude'], '$path.longitude'), + ); + } + + Map toJson() => { + 'latitude': _coordToJson(latitude), + 'longitude': _coordToJson(longitude), + }; +} + +/// Stock's "Other Settings". Both fields are ints on the wire even though they +/// read as booleans in the UI: `manual_add_contacts` is emitted as 0/1, not +/// true/false, unlike the [StockAutoAddSettings] block. +class StockOtherSettings { + const StockOtherSettings({ + required this.manualAddContacts, + required this.advertLocationPolicy, + }); + + final int manualAddContacts; + + /// Shown in stock's UI as "Share Position in Advert". + final int advertLocationPolicy; + + factory StockOtherSettings.fromJson(Map json, String path) { + return StockOtherSettings( + manualAddContacts: _asInt( + json['manual_add_contacts'], + '$path.manual_add_contacts', + ), + advertLocationPolicy: _asInt( + json['advert_location_policy'], + '$path.advert_location_policy', + ), + ); + } + + Map toJson() => { + 'manual_add_contacts': manualAddContacts, + 'advert_location_policy': advertLocationPolicy, + }; +} + +/// Stock's "Auto Add Settings". Booleans here really are JSON booleans. +class StockAutoAddSettings { + const StockAutoAddSettings({ + required this.autoAddChat, + required this.autoAddRepeater, + required this.autoAddRoomServer, + required this.autoAddSensor, + required this.overwriteOldest, + required this.autoAddMaxHops, + }); + + final bool autoAddChat; + final bool autoAddRepeater; + final bool autoAddRoomServer; + final bool autoAddSensor; + final bool overwriteOldest; + + /// `auto_add_max_hops`; stock renders 0 as "(no limit)". + final int autoAddMaxHops; + + factory StockAutoAddSettings.fromJson( + Map json, + String path, + ) { + return StockAutoAddSettings( + autoAddChat: _asBool(json['auto_add_chat'], '$path.auto_add_chat'), + autoAddRepeater: _asBool( + json['auto_add_repeater'], + '$path.auto_add_repeater', + ), + autoAddRoomServer: _asBool( + json['auto_add_room_server'], + '$path.auto_add_room_server', + ), + autoAddSensor: _asBool(json['auto_add_sensor'], '$path.auto_add_sensor'), + overwriteOldest: _asBool( + json['overwrite_oldest'], + '$path.overwrite_oldest', + ), + autoAddMaxHops: _asInt( + json['auto_add_max_hops'], + '$path.auto_add_max_hops', + ), + ); + } + + Map toJson() => { + 'auto_add_chat': autoAddChat, + 'auto_add_repeater': autoAddRepeater, + 'auto_add_room_server': autoAddRoomServer, + 'auto_add_sensor': autoAddSensor, + 'overwrite_oldest': overwriteOldest, + 'auto_add_max_hops': autoAddMaxHops, + }; +} + +/// One channel. The array position in [StockConfig.channels] is the index: +/// the record itself carries no index field. +class StockChannel { + const StockChannel({required this.name, required this.secret}); + + final String name; + + /// The 16-byte PSK, hex on the wire. + final Uint8List secret; + + factory StockChannel.fromJson(Map json, String path) { + return StockChannel( + name: _asString(json['name'], '$path.name'), + secret: _parseHex( + _asString(json['secret'], '$path.secret'), + '$path.secret', + expectBytes: _channelSecretBytes, + ), + ); + } + + Map toJson() => { + 'name': name, + 'secret': pubKeyToHex(secret), + }; +} + +/// A contact's routing path, as carried by `out_path_list`. +/// +/// Stock writes one comma-separated element per hop, each element being that +/// hop's hash in hex, so `"a1b2,c3d4"` is two hops at width 2. That maps +/// directly onto our width-aware path model (#309): [hopCount] is our hash +/// count and [hashWidth] is our per-hop width. Neither is inferred. +class StockOutPath { + StockOutPath({required this.hashWidth, required this.bytes}) + : assert(hashWidth > 0), + assert(bytes.length % hashWidth == 0); + + /// The `""` form of the field, as distinct from the key being null. + /// + /// Both mean "no path" and the corpus contains 10 of these against 2448 + /// nulls, but stock writes both and we do not know what distinguishes them. + /// Keeping them apart costs one constructor and makes an Offband re-export + /// byte-identical to its source, so we keep them apart. + StockOutPath.empty() : hashWidth = 0, bytes = _noBytes; + + static final Uint8List _noBytes = Uint8List(0); + + /// Bytes per hop hash, 1..3, or 0 for [StockOutPath.empty]. + /// See [kStockPathHashWidths]. + final int hashWidth; + + /// Flattened hop hashes, `hopCount * hashWidth` bytes. + final Uint8List bytes; + + int get hopCount => hashWidth == 0 ? 0 : bytes.length ~/ hashWidth; + + /// Parses `out_path_list`. A null key returns null; `""` returns + /// [StockOutPath.empty]. Both mean the contact has no route. + static StockOutPath? fromJson(Object? value, String path) { + if (value == null) return null; + final text = _asString(value, path); + if (text.isEmpty) return StockOutPath.empty(); + + final elements = text.split(','); + final widths = elements.map((e) => e.length).toSet(); + if (widths.length != 1) { + throw StockConfigFormatException( + 'hop hashes must all be the same width, got $widths', + path: path, + ); + } + final chars = widths.single; + if (chars.isOdd || !kStockPathHashWidths.contains(chars ~/ 2)) { + throw StockConfigFormatException( + 'unsupported hop hash width of $chars characters', + path: path, + ); + } + + final width = chars ~/ 2; + final bytes = BytesBuilder(); + for (final element in elements) { + bytes.add(_parseHex(element, path, expectBytes: width)); + } + return StockOutPath(hashWidth: width, bytes: bytes.toBytes()); + } + + String toJson() { + if (hashWidth == 0) return ''; + final hops = []; + for (var i = 0; i < bytes.length; i += hashWidth) { + hops.add(pubKeyToHex(Uint8List.sublistView(bytes, i, i + hashWidth))); + } + return hops.join(','); + } +} + +/// One contact. This is a near 1:1 serialization of the firmware's +/// `ContactInfo` struct, with [customName] as the one app-side addition. +class StockContact { + const StockContact({ + required this.type, + required this.name, + required this.publicKey, + required this.flags, + required this.latitude, + required this.longitude, + required this.lastAdvert, + required this.lastModified, + this.customName, + this.outPath, + }); + + /// `ADV_TYPE_*`: 1 chat, 2 repeater, 3 room, 4 sensor. + final int type; + + final String name; + + /// App-side rename. Null in all 2359 contacts of the reference corpus, so + /// its round-trip behavior is carried but unverified (#569). + final String? customName; + + final Uint8List publicKey; + + /// Bit 0 is "favourite" (firmware `flags & 0x01`). + final int flags; + + final double latitude; + final double longitude; + + /// Epoch seconds by THEIR clock. **Not sanitized**: the reference corpus + /// ranges from 14 to the year 2095. Kept as a raw int so no caller mistakes + /// it for a trustworthy time. + final int lastAdvert; + + /// Epoch seconds by OUR clock. Same caveat as [lastAdvert]. + final int lastModified; + + final StockOutPath? outPath; + + bool get isFavourite => flags & 0x01 != 0; + + factory StockContact.fromJson(Map json, String path) { + return StockContact( + type: _asInt(json['type'], '$path.type'), + name: _asString(json['name'], '$path.name'), + customName: json['custom_name'] == null + ? null + : _asString(json['custom_name'], '$path.custom_name'), + publicKey: _parseHex( + _asString(json['public_key'], '$path.public_key'), + '$path.public_key', + expectBytes: _publicKeyBytes, + ), + flags: _asInt(json['flags'], '$path.flags'), + latitude: _parseCoord(json['latitude'], '$path.latitude'), + longitude: _parseCoord(json['longitude'], '$path.longitude'), + lastAdvert: _asInt(json['last_advert'], '$path.last_advert'), + lastModified: _asInt(json['last_modified'], '$path.last_modified'), + outPath: StockOutPath.fromJson( + json['out_path_list'], + '$path.out_path_list', + ), + ); + } + + Map toJson() { + if (name.length > kStockMaxContactNameChars) { + throw StockConfigFormatException( + 'contact name is ${name.length} characters; stock firmware stores at ' + 'most $kStockMaxContactNameChars and would truncate it', + path: 'contacts[].name', + ); + } + return { + 'type': type, + 'name': name, + 'custom_name': customName, + 'public_key': pubKeyToHex(publicKey), + 'flags': flags, + 'latitude': _coordToJson(latitude), + 'longitude': _coordToJson(longitude), + 'last_advert': lastAdvert, + 'last_modified': lastModified, + 'out_path_list': outPath?.toJson(), + }; + } +} + +/// A whole stock config export. +/// +/// Every section is nullable, and null means "the user did not select this +/// section", which is distinct from an empty list. Absent sections are omitted +/// from [toJson] entirely rather than written as null, matching stock. +class StockConfig { + const StockConfig({ + this.name, + this.publicKey, + this.privateKey, + this.radioSettings, + this.positionSettings, + this.otherSettings, + this.autoAddSettings, + this.channels, + this.contacts, + }); + + final String? name; + + /// 32 bytes. Travels as a unit with [privateKey]: stock's identity control + /// emits both or neither. + final Uint8List? publicKey; + + /// 64 bytes. See [publicKey]. + final Uint8List? privateKey; + + final StockRadioSettings? radioSettings; + final StockPositionSettings? positionSettings; + final StockOtherSettings? otherSettings; + final StockAutoAddSettings? autoAddSettings; + + /// Ordered; array position is the channel index. + final List? channels; + + final List? contacts; + + /// Parses a decoded JSON object. + /// + /// Unknown top-level keys are ignored, not rejected: the format has no + /// version field, so tolerating additions is the only way to survive a stock + /// release that adds one. + factory StockConfig.fromJson(Map json) { + final channelsJson = json['channels']; + final contactsJson = json['contacts']; + + return StockConfig( + name: json['name'] == null ? null : _asString(json['name'], 'name'), + publicKey: json['public_key'] == null + ? null + : _parseHex( + _asString(json['public_key'], 'public_key'), + 'public_key', + expectBytes: _publicKeyBytes, + ), + privateKey: json['private_key'] == null + ? null + : _parseHex( + _asString(json['private_key'], 'private_key'), + 'private_key', + expectBytes: _privateKeyBytes, + ), + radioSettings: json['radio_settings'] == null + ? null + : StockRadioSettings.fromJson( + _asObject(json['radio_settings'], 'radio_settings'), + 'radio_settings', + ), + positionSettings: json['position_settings'] == null + ? null + : StockPositionSettings.fromJson( + _asObject(json['position_settings'], 'position_settings'), + 'position_settings', + ), + otherSettings: json['other_settings'] == null + ? null + : StockOtherSettings.fromJson( + _asObject(json['other_settings'], 'other_settings'), + 'other_settings', + ), + autoAddSettings: json['auto_add_settings'] == null + ? null + : StockAutoAddSettings.fromJson( + _asObject(json['auto_add_settings'], 'auto_add_settings'), + 'auto_add_settings', + ), + channels: channelsJson == null + ? null + : _parseList( + channelsJson, + 'channels', + (item, path) => + StockChannel.fromJson(_asObject(item, path), path), + ), + contacts: contactsJson == null + ? null + : _parseList( + contactsJson, + 'contacts', + (item, path) => + StockContact.fromJson(_asObject(item, path), path), + ), + ); + } + + static List _parseList( + Object? value, + String path, + T Function(Object? item, String itemPath) parse, + ) { + if (value is! List) { + throw StockConfigFormatException('expected an array', path: path); + } + final result = []; + for (var i = 0; i < value.length; i++) { + result.add(parse(value[i], '$path[$i]')); + } + return result; + } + + /// Parses raw file text. + factory StockConfig.parse(String source) { + final Object? decoded; + try { + decoded = jsonDecode(source); + } on FormatException catch (e) { + throw StockConfigFormatException('file is not valid JSON: ${e.message}'); + } + return StockConfig.fromJson(_asObject(decoded, r'$')); + } + + Map toJson() { + return { + if (name != null) 'name': name, + if (publicKey != null) 'public_key': pubKeyToHex(publicKey!), + if (privateKey != null) 'private_key': pubKeyToHex(privateKey!), + if (radioSettings != null) 'radio_settings': radioSettings!.toJson(), + if (positionSettings != null) + 'position_settings': positionSettings!.toJson(), + if (otherSettings != null) 'other_settings': otherSettings!.toJson(), + if (autoAddSettings != null) + 'auto_add_settings': autoAddSettings!.toJson(), + if (channels != null) 'channels': [for (final c in channels!) c.toJson()], + if (contacts != null) 'contacts': [for (final c in contacts!) c.toJson()], + }; + } + + String encode() => jsonEncode(toJson()); +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 87799a37..3ccdefd8 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -11,6 +11,7 @@ import 'package:provider/provider.dart'; import '../connector/meshcore_connector.dart'; import '../models/community.dart'; import '../storage/community_store.dart'; +import '../utils/app_logger.dart'; import '../utils/platform_info.dart'; import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; @@ -19,21 +20,26 @@ import '../helpers/gif_helper.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/snack_bar_builder.dart'; import '../l10n/l10n.dart'; +import '../l10n/contact_localization.dart'; import '../models/channel.dart'; import '../models/channel_message.dart'; +import '../models/contact.dart'; import '../models/translation_support.dart'; import '../models/app_settings.dart'; import '../services/app_settings_service.dart'; +import '../services/corescope_service.dart'; import '../widgets/channel_notify_mode.dart'; import '../services/block_service.dart'; import '../services/chat_text_scale_service.dart'; import '../services/translation_service.dart'; import '../utils/emoji_utils.dart'; import '../utils/route_transitions.dart'; +import 'chat_screen.dart'; import 'settings_screen.dart'; import '../utils/dialog_utils.dart'; import '../widgets/app_shell.dart'; import '../widgets/channel_drawer_list.dart'; +import '../widgets/composer_budget_notice.dart'; import '../widgets/mention_autocomplete.dart'; import '../helpers/emoji_shortcodes.dart'; import '../widgets/chat_zoom_wrapper.dart'; @@ -639,7 +645,6 @@ class _ChannelChatScreenState extends State { Future _blockChannelSender(ChannelMessage message) async { final connector = context.read(); final blockService = context.read(); - final messenger = ScaffoldMessenger.of(context); final l10n = context.l10n; final name = message.senderName; final keys = connector.resolveContactKeysByName(name); @@ -648,16 +653,204 @@ class _ChannelChatScreenState extends State { await blockService.block(key); } if (!mounted) return; - messenger.showSnackBar(SnackBar(content: Text(l10n.block_blocked(name)))); + showDismissibleSnackBar(context, content: Text(l10n.block_blocked(name))); } else { await blockService.blockName(name); if (!mounted) return; - messenger.showSnackBar( - SnackBar(content: Text(l10n.block_blockedNameOnly(name))), + showDismissibleSnackBar( + context, + content: Text(l10n.block_blockedNameOnly(name)), ); } } + /// Contact actions for the sender of a channel post (#468). Channel frames + /// carry no key, so the claimed name is resolved against known + discovered + /// contacts. Every node claiming that name gets its own row: an ambiguous + /// namesake is never resolved for the user. + void _showSenderActions(ChannelMessage message) { + if (message.isOutgoing) return; + final connector = context.read(); + final candidates = connector.resolveContactsByName(message.senderName); + final ambiguous = candidates.length > 1; + + showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: _buildAvatar(message.senderName), + title: Text(message.senderName), + subtitle: ambiguous + ? Text( + l10n.channel_senderMultipleMatches(candidates.length), + ) + : null, + ), + const Divider(height: 1), + ..._buildSenderContactEntries(sheetContext, message), + ListTile( + leading: Icon(Icons.block, color: Colors.red.shade700), + title: Text(l10n.block_sender), + onTap: () { + Navigator.pop(sheetContext); + _blockChannelSender(message); + }, + ), + ListTile( + leading: const Icon(Icons.close), + title: Text(l10n.common_cancel), + onTap: () => Navigator.pop(sheetContext), + ), + ], + ), + ); + }, + ); + } + + /// Sender contact rows, shared by the avatar-tap sheet and the long-press + /// menu so both offer exactly the same actions. An unresolved name says so + /// outright instead of silently offering nothing. + List _buildSenderContactEntries( + BuildContext sheetContext, + ChannelMessage message, + ) { + final connector = sheetContext.read(); + final candidates = connector.resolveContactsByName(message.senderName); + if (candidates.isEmpty) { + // States what we actually know: nothing matches this name. Claiming the + // node was never heard would be a guess, since it may be known under an + // older advert name (#579). + return [ + ListTile( + leading: const Icon(Icons.help_outline), + title: Text(sheetContext.l10n.channel_senderNameUnknown), + subtitle: Text(sheetContext.l10n.channel_senderNameUnknownHint), + ), + ]; + } + return [ + for (final candidate in candidates) + ..._buildSenderCandidateTiles( + sheetContext, + candidate, + showIdentity: candidates.length > 1, + ), + ]; + } + + /// Add/view rows for one resolved sender identity. [showIdentity] prefixes an + /// identifying row (pubkey prefix + type) so colliding namesakes stay apart. + List _buildSenderCandidateTiles( + BuildContext sheetContext, + Contact candidate, { + required bool showIdentity, + }) { + final l10n = sheetContext.l10n; + final connector = sheetContext.read(); + final isKnown = connector.contacts.any( + (c) => c.publicKeyHex == candidate.publicKeyHex, + ); + + return [ + if (showIdentity) + ListTile( + dense: true, + leading: const Icon(Icons.fingerprint), + title: Text( + l10n.channel_senderCandidate( + candidate.publicKeyHex.substring( + 0, + math.min(8, candidate.publicKeyHex.length), + ), + candidate.typeLabel(l10n), + ), + ), + ), + if (!isKnown) + ListTile( + leading: const Icon(Icons.add_reaction_sharp), + title: Text(l10n.discoveredContacts_addContact), + onTap: () { + Navigator.pop(sheetContext); + _addSenderContact(candidate); + }, + ) + // A repeater or room server reached through a channel post still needs + // its login flow, which lives on the Contacts screen. Say it is already + // known rather than dropping the user into a chat that cannot work. + else if (candidate.type == advTypeChat) + ListTile( + leading: const Icon(Icons.chat_bubble_outline), + title: Text(l10n.contacts_openChat), + onTap: () { + Navigator.pop(sheetContext); + _openSenderChat(candidate); + }, + ) + else + ListTile( + leading: const Icon(Icons.check_circle_outline), + title: Text(l10n.channel_senderAlreadyContact), + ), + ]; + } + + Future _addSenderContact(Contact candidate) async { + final connector = context.read(); + final l10n = context.l10n; + // importDiscoveredContact silently no-ops without a radio, and sendFrame + // throws on a mid-write disconnect. Neither may reach the user as a tap + // that just did nothing (#565). + if (!connector.isConnected) { + _showSenderError(l10n.channel_senderAddNotConnected); + return; + } + try { + await connector.importDiscoveredContact(candidate); + } catch (e) { + appLogger.error('Adding channel sender ${candidate.name} failed: $e'); + if (!mounted) return; + _showSenderError(l10n.channel_senderAddFailed(e.toString())); + return; + } + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.discoveredContacts_contactAdded), + ); + } + + void _showSenderError(String message) { + showDismissibleSnackBar( + context, + content: Text(message), + backgroundColor: Theme.of(context).colorScheme.error, + persist: true, + ); + } + + void _openSenderChat(Contact candidate) { + final connector = context.read(); + final unread = connector.getUnreadCountForContactKey( + candidate.publicKeyHex, + ); + connector.markContactRead(candidate.publicKeyHex); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + ChatScreen(contact: candidate, initialUnreadCount: unread), + ), + ); + } + /// A channel post is hidden only when its claimed name resolves to at least /// one identity and *every* matching pubkey is blocked (an ambiguous namesake /// with any unblocked match is still shown), or the name is in blockedNames. @@ -712,7 +905,13 @@ class _ChannelChatScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (!isOutgoing) ...[ - _buildAvatar(message.senderName), + // The avatar is the contact-action shortcut (#468). The sender + // name text is deliberately NOT a tap target: on a phone it sits + // too close to the message body to hit reliably. + GestureDetector( + onTap: () => _showSenderActions(message), + child: _buildAvatar(message.senderName), + ), const SizedBox(width: 8), ], Flexible( @@ -1046,6 +1245,76 @@ class _ChannelChatScreenState extends State { ); } + /// The composer `+` picker. (#611) + /// + /// Owner decision: one `+` beside the text entry, offering GIF and Contact + /// for now, rather than a dedicated button per thing you can attach. The + /// sendable set stays small because a channel message shares a 160-byte + /// payload with the `Sender: ` prefix. + void _showAttachPicker(BuildContext context) { + showModalBottomSheet( + context: context, + builder: (sheetContext) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.gif_box), + title: Text(sheetContext.l10n.chat_attachGif), + onTap: () { + Navigator.pop(sheetContext); + _showGifPicker(context); + }, + ), + ListTile( + leading: const Icon(Icons.person_outline), + title: Text(sheetContext.l10n.chat_attachMyContact), + subtitle: Text(sheetContext.l10n.chat_attachMyContactSubtitle), + onTap: () { + Navigator.pop(sheetContext); + _insertMyContactCard(context); + }, + ), + ], + ), + ), + ); + } + + /// Puts this device's own contact card into the composer. (#611) + /// + /// Inserts rather than sends, matching the GIF picker, so the text can be + /// reviewed and captioned before it goes out. + /// + /// Emits the compact `` form observed on the live mesh, NOT + /// the `meshcore://` URI. The URI is ~117 bytes against ~75 here, and the + /// channel payload budget is 160 including the `Sender: ` prefix. + void _insertMyContactCard(BuildContext context) { + final connector = Provider.of(context, listen: false); + final keyHex = connector.selfPublicKeyHex; + if (keyHex.length != pubKeySize * 2) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_contactCardNeedsConnection), + ); + return; + } + + final card = Contact.buildChannelShare( + publicKeyHex: keyHex, + name: connector.selfName ?? '', + // This device is a companion. + type: advTypeChat, + ); + + // Append rather than replace, so a caption already typed is not lost. + final existing = _textController.text.trimRight(); + _textController.text = existing.isEmpty ? card : '$existing $card'; + _textController.selection = TextSelection.collapsed( + offset: _textController.text.length, + ); + } + Widget _buildAvatar(String senderName) { final initial = _getFirstCharacterOrEmoji(senderName); final color = _getColorForName(senderName); @@ -1161,6 +1430,13 @@ class _ChannelChatScreenState extends State { return Column( mainAxisSize: MainAxisSize.min, children: [ + // Says so out loud when the link leaves no room for text, instead of + // presenting a field that silently rejects every keystroke (#684). + ComposerBudgetNotice( + maxBytes: maxBytes, + transport: connector.activeTransport, + isConnected: connector.isConnected, + ), if (_replyingToMessage != null) Builder( builder: (context) { @@ -1185,9 +1461,9 @@ class _ChannelChatScreenState extends State { child: Row( children: [ IconButton( - icon: const Icon(Icons.gif_box), - onPressed: () => _showGifPicker(context), - tooltip: context.l10n.chat_sendGif, + icon: const Icon(Icons.add), + onPressed: () => _showAttachPicker(context), + tooltip: context.l10n.chat_attachTooltip, ), if (settings.translationEnabled) MessageTranslationButton( @@ -1517,6 +1793,33 @@ class _ChannelChatScreenState extends State { ), ), ], + // CoreScope observer count (#524), shown parallel to the radio-heard + // count with a distinct icon, never merged into one number. Tap to + // re-query on demand (the count only ever climbs). + if (isOutgoing && (message.coreScopeObserverCount ?? 0) > 0) ...[ + dot, + Tooltip( + message: _coreScopeLabel(message), + child: InkWell( + onTap: message.onAirHash == null + ? null + : () => _refreshCoreScope(message), + borderRadius: BorderRadius.circular(10), + child: Padding( + // Generous padding so the small badge is a reliable tap target. + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.cloud_outlined, size: 12, color: metaColor), + const SizedBox(width: 4), + Text('${message.coreScopeObserverCount}', style: metaStyle), + ], + ), + ), + ), + ), + ], if (isOutgoing) ...[ const SizedBox(width: 6), Icon( @@ -1613,6 +1916,58 @@ class _ChannelChatScreenState extends State { ); } + String _coreScopeLabel(ChannelMessage message) { + final observers = message.coreScopeObserverCount ?? 0; + final observations = message.coreScopeObservationCount; + return observations == null + ? context.l10n.channel_coreScopeTooltip(observers) + : context.l10n.channel_coreScopeCounts(observers, observations); + } + + Future _refreshCoreScope(ChannelMessage message) async { + final hash = message.onAirHash; + if (hash == null) return; + final connector = context.read(); + final l10n = context.l10n; + final result = await connector.refreshCoreScopeCounts( + message.channelIndex ?? _currentChannel.index, + message.messageId, + hash, + ); + if (!mounted) return; + final text = switch (result.status) { + CoreScopeStatus.found => l10n.channel_coreScopeCounts( + result.counts!.observers, + result.counts!.observations, + ), + CoreScopeStatus.notFound => l10n.channel_coreScopeNotFound, + CoreScopeStatus.unreachable => l10n.channel_coreScopeRefreshFailed, + }; + _showCoreScopeBanner(text); + } + + /// Top banner (out of the way of the composer), auto-dismissed after a few + /// seconds. Used for the CoreScope refresh result (#524). + void _showCoreScopeBanner(String message) { + final messenger = ScaffoldMessenger.of(context); + messenger.clearMaterialBanners(); + messenger.showMaterialBanner( + MaterialBanner( + content: Text(message), + leading: const Icon(Icons.cloud_outlined), + actions: [ + TextButton( + onPressed: messenger.hideCurrentMaterialBanner, + child: Text(context.l10n.common_ok), + ), + ], + ), + ); + Future.delayed(const Duration(seconds: 4), () { + if (mounted) messenger.hideCurrentMaterialBanner(); + }); + } + void _retryChannelMessage(ChannelMessage message) { context.read().sendChannelMessage( _currentChannel, @@ -1666,11 +2021,12 @@ class _ChannelChatScreenState extends State { _showMessagePathInfo(message); }, ), - // Offer resend on an outgoing channel message until its - // ack/repeat-back arrives (status becomes sent). Channel sends are - // not auto-retried, so this is the only recovery path. (#256) - if (message.isOutgoing && - message.status != ChannelMessageStatus.sent) + // Offer resend on an outgoing channel message until a repeater + // repeats it back (repeatCount > 0). The radio-ack checkmark + // (status == sent) does NOT mean a repeat was heard, so gate on the + // repeat-back, not status. Channel sends aren't auto-retried, so + // this is the only recovery path. (#256, #555) + if (message.isOutgoing && message.repeatCount == 0) ListTile( leading: const Icon(Icons.refresh), title: Text(context.l10n.message_sendAgain), @@ -1679,6 +2035,20 @@ class _ChannelChatScreenState extends State { _retryChannelMessage(message); }, ), + // CoreScope observer count refresh (#524), owner feature. A large, + // reliable tap target vs the small inline badge. + if (message.isOutgoing && message.onAirHash != null) + ListTile( + leading: const Icon(Icons.cloud_outlined), + title: Text(context.l10n.channel_coreScopeRefresh), + subtitle: message.coreScopeObserverCount != null + ? Text(_coreScopeLabel(message)) + : null, + onTap: () { + Navigator.pop(sheetContext); + _refreshCoreScope(message); + }, + ), // Can't react to your own messages if (!message.isOutgoing) ListTile( @@ -1729,7 +2099,11 @@ class _ChannelChatScreenState extends State { await _deleteMessage(message); }, ), - if (!message.isOutgoing) + // Same sender contact actions the avatar tap offers (#468), so + // long-press remains a superset of every gesture on the message. + if (!message.isOutgoing) ...[ + const Divider(height: 1), + ..._buildSenderContactEntries(sheetContext, message), ListTile( leading: Icon(Icons.block, color: Colors.red.shade700), title: Text(context.l10n.block_sender), @@ -1738,6 +2112,7 @@ class _ChannelChatScreenState extends State { _blockChannelSender(message); }, ), + ], ListTile( leading: const Icon(Icons.close), title: Text(context.l10n.common_cancel), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 768a54f8..0718a3e7 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -32,6 +32,7 @@ import '../services/chat_text_scale_service.dart'; import '../services/path_history_service.dart'; import '../services/translation_service.dart'; import '../widgets/chat_zoom_wrapper.dart'; +import '../widgets/composer_budget_notice.dart'; import '../widgets/contact_settings_dialog.dart'; import '../widgets/elements_ui.dart'; import '../widgets/mention_autocomplete.dart'; @@ -600,6 +601,28 @@ class _ChatScreenState extends State { ); final colorScheme = Theme.of(context).colorScheme; final settings = context.watch().settings; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Says so out loud when the link leaves no room for text, instead of + // presenting a field that silently rejects every keystroke (#684). + ComposerBudgetNotice( + maxBytes: maxBytes, + transport: connector.activeTransport, + isConnected: connector.isConnected, + ), + _buildComposerBar(context, colorScheme, settings, maxBytes, connector), + ], + ); + } + + Widget _buildComposerBar( + BuildContext context, + ColorScheme colorScheme, + AppSettings settings, + int maxBytes, + MeshCoreConnector connector, + ) { return Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( diff --git a/lib/screens/contact_qr_scanner_screen.dart b/lib/screens/contact_qr_scanner_screen.dart new file mode 100644 index 00000000..4a96095d --- /dev/null +++ b/lib/screens/contact_qr_scanner_screen.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import '../utils/platform_info.dart'; +import '../widgets/qr_scanner_widget.dart'; + +/// Whether a contact QR can be scanned on this platform. +/// +/// `mobile_scanner` covers Android, iOS, macOS and web, but not Windows or +/// Linux. On those the QR half of the exchange is the RENDER side: show your +/// own code from the desktop and let the other person scan it with a phone. +/// +/// Lives here rather than on a caller because both the key-entry field and the +/// contacts menu need it. (#629) +bool get contactQrScanAvailable => + PlatformInfo.isMobile || PlatformInfo.isMacOS || PlatformInfo.isWeb; + +/// Scans a contact QR and pops the raw `meshcore://contact/add` string. (#629) +/// +/// A contact QR is only that URI rendered visually, so this validates with the +/// same [Contact.isValidShareUri] the paste path uses. There is no second +/// format and no second parser. +class ContactQrScannerScreen extends StatelessWidget { + const ContactQrScannerScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(context.l10n.contacts_scanContactQr), + centerTitle: true, + ), + body: QrScannerWidget( + instructions: context.l10n.contacts_scanContactQrInstructions, + validator: Contact.isValidShareUri, + onScanned: (data) => Navigator.of(context).pop(data), + onValidationFailed: (_) => showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_invalidContactQr), + ), + ), + ); + } +} diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 39349739..adc9899b 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -34,10 +34,14 @@ import '../widgets/path_selection_dialog.dart'; import '../widgets/repeater_login_dialog.dart'; import '../widgets/room_login_dialog.dart'; import '../widgets/sync_progress_overlay.dart'; +import '../widgets/add_contact_by_key_dialog.dart'; +import '../widgets/contact_verification_badge.dart'; +import '../widgets/my_contact_qr_dialog.dart'; import '../widgets/unread_badge.dart'; import '../helpers/snack_bar_builder.dart'; import 'channels_screen.dart'; import 'chat_screen.dart'; +import 'contact_qr_scanner_screen.dart'; import 'discovery_screen.dart'; import 'map_screen.dart'; import 'repeater_hub_screen.dart'; @@ -411,6 +415,43 @@ class _ContactsScreenState extends State ), ), ), + // Provisional home so key entry is reachable. The proper + // add-contact surface, split away from the advert affordance, + // is #632 under epic #623. + PopupMenuItem( + child: Row( + children: [ + const Icon(Icons.key_outlined), + const SizedBox(width: 8), + Text(context.l10n.contacts_addByKey), + ], + ), + onTap: () => showAddContactByKeyDialog(context), + ), + // Scanning is a first-class way in, not just a button buried in + // the key field, so it gets its own entry here and routes + // straight into the add flow already filled in. (#629) + if (contactQrScanAvailable) + PopupMenuItem( + child: Row( + children: [ + const Icon(Icons.qr_code_scanner), + const SizedBox(width: 8), + Text(context.l10n.contacts_scanContactQr), + ], + ), + onTap: () => _scanContactQr(context), + ), + PopupMenuItem( + child: Row( + children: [ + const Icon(Icons.qr_code_2), + const SizedBox(width: 8), + Text(context.l10n.contacts_myContactQr), + ], + ), + onTap: () => showMyContactQrDialog(context), + ), ], icon: const Icon(Icons.more_vert), ), @@ -916,6 +957,20 @@ class _ContactsScreenState extends State } } + /// Scan a contact QR from the contacts menu, then hand the result to the add + /// dialog already populated. (#629) + /// + /// Same scanner and same parser as the key-field button; only the entry point + /// differs. Scanning is how most people will actually add someone, so it + /// should not be reachable only from inside a field they have to open first. + Future _scanContactQr(BuildContext context) async { + final scanned = await Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const ContactQrScannerScreen()), + ); + if (!context.mounted || scanned == null) return; + await showAddContactByKeyDialog(context, initialKeyText: scanned); + } + DateTime _resolveLastSeen(Contact contact) { if (contact.type != advTypeChat) return contact.lastSeen; return contact.lastMessageAt.isAfter(contact.lastSeen) @@ -1454,6 +1509,20 @@ class _ContactsScreenState extends State }, ), ] else ...[ + // Sensors run the same admin login and CLI as repeaters + // (stock SensorMesh), so they share the repeater admin hub (#745). + if (contact.type == advTypeSensor) + ListTile( + leading: const Icon( + Icons.sensors_outlined, + color: Colors.orange, + ), + title: Text(context.l10n.contacts_manageSensor), + onTap: () { + Navigator.pop(sheetContext); + _showRepeaterLogin(context, contact); + }, + ), if (contact.pathLength > 0) ListTile( leading: const Icon(Icons.radar, color: Colors.green), @@ -1616,7 +1685,22 @@ class _ContactTile extends StatelessWidget { ), ], ) - : Text(contact.name, maxLines: 1, overflow: TextOverflow.ellipsis), + : Row( + children: [ + // Reads as a column of state down the list. Calm by design: + // a key-added contact is not a problem, just less confirmed + // (#630). + ContactVerificationBadge(contact: contact), + const SizedBox(width: 6), + Expanded( + child: Text( + contact.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -1722,6 +1806,14 @@ class _ContactTile extends StatelessWidget { } String _formatLastSeen(BuildContext context, DateTime lastSeen) { + // A contact added from a bare key carries the epoch deliberately, so the + // firmware advert replay guard cannot mute it (#627). Rendering that + // through the relative formatter would claim it was last seen tens of + // thousands of days ago, which is worse than saying nothing. (#630) + if (lastSeen.millisecondsSinceEpoch == 0) { + return context.l10n.contacts_lastSeenNever; + } + final now = DateTime.now(); final diff = now.difference(lastSeen); diff --git a/lib/screens/export_config_screen.dart b/lib/screens/export_config_screen.dart new file mode 100644 index 00000000..b8c66620 --- /dev/null +++ b/lib/screens/export_config_screen.dart @@ -0,0 +1,310 @@ +/// Stock-compatible config export (#574, epic #568). +/// +/// Mirrors the stock app's Export Config screen: a list of sections, Select All +/// and Deselect All, and **everything checked by default**. The asymmetry with +/// the import screen (which starts with nothing checked) is deliberate and +/// copied from stock: opt out on the way out, opt in on the way in. +library; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../services/stock_config_export_service.dart'; +import '../utils/stock_config_file.dart'; +import '../widgets/adaptive_app_bar_title.dart'; + +class ExportConfigScreen extends StatefulWidget { + const ExportConfigScreen({super.key}); + + @override + State createState() => _ExportConfigScreenState(); +} + +class _ExportConfigScreenState extends State { + /// Every section starts selected, matching stock. + final Set _selected = StockConfigSection.values.toSet(); + bool _busy = false; + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final connector = context.watch(); + + return Scaffold( + appBar: AppBar( + title: AdaptiveAppBarTitle(l10n.exportConfig_title), + centerTitle: true, + actions: [ + IconButton( + icon: const Icon(Icons.check), + onPressed: _busy ? null : () => _export(connector), + tooltip: l10n.exportConfig_title, + ), + ], + ), + body: ListView( + children: [ + _Banner(text: l10n.exportConfig_instruction), + _Banner(text: l10n.exportConfig_lossyNotice, subdued: true), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + TextButton( + onPressed: () => + setState(() => _selected.addAll(StockConfigSection.values)), + child: Text(l10n.stockConfig_selectAll), + ), + TextButton( + onPressed: () => setState(_selected.clear), + child: Text(l10n.stockConfig_deselectAll), + ), + ], + ), + for (final section in StockConfigSection.values) + _SectionTile( + title: sectionLabel(context, section, connector), + subtitle: _subtitleFor(section, connector), + selected: _selected.contains(section), + onChanged: (value) => setState(() { + if (value) { + _selected.add(section); + } else { + _selected.remove(section); + } + }), + ), + ], + ), + ); + } + + String? _subtitleFor( + StockConfigSection section, + MeshCoreConnector connector, + ) { + final l10n = context.l10n; + switch (section) { + case StockConfigSection.name: + return connector.selfName; + case StockConfigSection.identity: + final key = connector.selfPublicKeyHex; + final abbreviated = key.length > 12 + ? '${key.substring(0, 6)}...${key.substring(key.length - 6)}' + : key; + // The private key is never rendered, not even abbreviated. + return '${l10n.stockConfig_identityWarning}\n' + '${l10n.stockConfig_publicKeyLabel(abbreviated)}\n' + '${l10n.stockConfig_privateKeyHidden}'; + case StockConfigSection.radioSettings: + final freq = connector.currentFreqHz; + final bw = connector.currentBwHz; + if (freq == null || bw == null) return null; + // currentFreqHz is kHz despite its name; currentBwHz really is Hz. + return '${l10n.settings_frequency}: ${freq / 1000} MHz\n' + '${l10n.settings_bandwidth}: ${bw / 1000} kHz\n' + '${l10n.settings_spreadingFactor}: ${connector.currentSf}\n' + '${l10n.settings_codingRate}: ${connector.currentCr}\n' + '${l10n.settings_txPower}: ${connector.currentTxPower}'; + case StockConfigSection.positionSettings: + return '${connector.selfLatitude ?? 0}, ${connector.selfLongitude ?? 0}'; + case StockConfigSection.otherSettings: + return null; + case StockConfigSection.autoAddSettings: + return null; + case StockConfigSection.channels: + return l10n.exportConfig_allChannels; + case StockConfigSection.contacts: + return l10n.exportConfig_allContacts; + } + } + + Future _export(MeshCoreConnector connector) async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + + if (!connector.isConnected) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.exportConfig_notConnected)), + ); + return; + } + if (_selected.isEmpty) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.exportConfig_nothingSelected)), + ); + return; + } + + setState(() => _busy = true); + try { + final result = await StockConfigExportService( + connector, + ).build(sections: Set.of(_selected)); + + // A section the user asked for that could not be gathered is surfaced + // before the file is written, never dropped quietly. + if (!result.isComplete) { + if (!mounted) return; + final proceed = await _confirmOmissions(result); + if (proceed != true) return; + } + if (!mounted) return; + + await saveStockConfigFile( + context, + json: result.config.encode(), + fileName: stockConfigFileName(connector.selfName, DateTime.now()), + subject: l10n.exportConfig_shareSubject, + ); + } catch (e) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.exportConfig_failed('$e'))), + ); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _confirmOmissions(StockConfigExportResult result) { + final l10n = context.l10n; + final connector = context.read(); + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.exportConfig_omittedTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final entry in result.omitted.entries) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text( + _omissionText( + context, + sectionLabel(context, entry.key, connector), + entry.value, + ), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(l10n.exportConfig_cancel), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text(l10n.exportConfig_exportAnyway), + ), + ], + ), + ); + } +} + +String _omissionText( + BuildContext context, + String section, + StockConfigOmission reason, +) { + final l10n = context.l10n; + switch (reason) { + case StockConfigOmission.unsupported: + return l10n.exportConfig_omittedUnsupported(section); + case StockConfigOmission.noReply: + return l10n.exportConfig_omittedNoReply(section); + case StockConfigOmission.rejected: + return l10n.exportConfig_omittedRejected(section); + case StockConfigOmission.unavailable: + return l10n.exportConfig_omittedUnavailable(section); + } +} + +/// Section titles, shared with the import screen so the two cannot drift. +String sectionLabel( + BuildContext context, + StockConfigSection section, + MeshCoreConnector connector, +) { + final l10n = context.l10n; + switch (section) { + case StockConfigSection.name: + return l10n.stockConfig_sectionName; + case StockConfigSection.identity: + return l10n.stockConfig_sectionIdentity; + case StockConfigSection.radioSettings: + return l10n.stockConfig_sectionRadio; + case StockConfigSection.positionSettings: + return l10n.stockConfig_sectionPosition; + case StockConfigSection.otherSettings: + return l10n.stockConfig_sectionOther; + case StockConfigSection.autoAddSettings: + return l10n.stockConfig_sectionAutoAdd; + case StockConfigSection.channels: + return l10n.stockConfig_sectionChannels( + connector.channels.where((c) => !c.isEmpty).length, + ); + case StockConfigSection.contacts: + return l10n.stockConfig_sectionContacts(connector.contacts.length); + } +} + +class _SectionTile extends StatelessWidget { + const _SectionTile({ + required this.title, + required this.selected, + required this.onChanged, + this.subtitle, + }); + + final String title; + final String? subtitle; + final bool selected; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + return CheckboxListTile( + value: selected, + onChanged: (value) => onChanged(value ?? false), + controlAffinity: ListTileControlAffinity.trailing, + isThreeLine: subtitle != null, + title: Text(title), + subtitle: subtitle == null ? null : Text(subtitle!), + ); + } +} + +class _Banner extends StatelessWidget { + const _Banner({required this.text, this.subdued = false}); + + final String text; + final bool subdued; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + width: double.infinity, + color: theme.colorScheme.surfaceContainerHighest, + padding: const EdgeInsets.all(12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.info_outline, size: 18, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Expanded( + child: Text( + text, + style: subdued ? theme.textTheme.bodySmall : null, + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/import_config_screen.dart b/lib/screens/import_config_screen.dart new file mode 100644 index 00000000..5f44f8ad --- /dev/null +++ b/lib/screens/import_config_screen.dart @@ -0,0 +1,353 @@ +/// Stock-compatible config import (#576, epic #568). +/// +/// Mirrors the stock app's Import Config screen, including the detail that +/// **nothing is checked by default**. Export opts out, import opts in; that +/// asymmetry is stock's and it is the safe default in each direction. +/// +/// The per-section wording is stock's own, because the behavior is stock's own: +/// contacts are upserted, existing channels are never overwritten, and +/// importing an identity is destructive. +library; + +import 'dart:convert'; + +import 'package:file_selector/file_selector.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../models/stock_config.dart'; +import '../services/stock_config_export_service.dart' show StockConfigSection; +import '../services/stock_config_import_service.dart'; +import '../widgets/adaptive_app_bar_title.dart'; +import 'export_config_screen.dart' show sectionLabel; + +class ImportConfigScreen extends StatefulWidget { + const ImportConfigScreen({super.key}); + + @override + State createState() => _ImportConfigScreenState(); +} + +class _ImportConfigScreenState extends State { + StockConfig? _config; + + /// Starts empty: import is opt-in, matching stock. + final Set _selected = {}; + bool _busy = false; + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final connector = context.watch(); + final config = _config; + + return Scaffold( + appBar: AppBar( + title: AdaptiveAppBarTitle(l10n.importConfig_title), + centerTitle: true, + actions: [ + if (config != null) + IconButton( + icon: const Icon(Icons.check), + onPressed: _busy ? null : () => _import(connector, config), + tooltip: l10n.importConfig_title, + ), + ], + ), + body: config == null + ? Center( + child: FilledButton.icon( + onPressed: _busy ? null : _pickFile, + icon: const Icon(Icons.folder_open), + label: Text(l10n.importConfig_chooseFile), + ), + ) + : ListView( + children: [ + _Banner(text: l10n.importConfig_instruction), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + TextButton( + onPressed: () => + setState(() => _selected.addAll(_present(config))), + child: Text(l10n.stockConfig_selectAll), + ), + TextButton( + onPressed: () => setState(_selected.clear), + child: Text(l10n.stockConfig_deselectAll), + ), + ], + ), + // Only sections the file actually carries are offered. + for (final section in _present(config)) + CheckboxListTile( + value: _selected.contains(section), + controlAffinity: ListTileControlAffinity.trailing, + isThreeLine: _noteFor(section) != null, + title: Text(_titleFor(section, config, connector)), + subtitle: _noteFor(section) == null + ? null + : Text(_noteFor(section)!), + onChanged: (value) => setState(() { + if (value ?? false) { + _selected.add(section); + } else { + _selected.remove(section); + } + }), + ), + ], + ), + ); + } + + /// The sections this particular file carries. A stock export omits whatever + /// the exporting user deselected, so an absent section is normal. + List _present(StockConfig config) { + return [ + if (config.name != null) StockConfigSection.name, + if (config.privateKey != null) StockConfigSection.identity, + if (config.radioSettings != null) StockConfigSection.radioSettings, + if (config.positionSettings != null) StockConfigSection.positionSettings, + if (config.otherSettings != null) StockConfigSection.otherSettings, + if (config.autoAddSettings != null) StockConfigSection.autoAddSettings, + if (config.channels != null) StockConfigSection.channels, + if (config.contacts != null) StockConfigSection.contacts, + ]; + } + + String _titleFor( + StockConfigSection section, + StockConfig config, + MeshCoreConnector connector, + ) { + final l10n = context.l10n; + // Channel and contact counts come from the FILE here, not the device. + switch (section) { + case StockConfigSection.channels: + return l10n.stockConfig_sectionChannels(config.channels?.length ?? 0); + case StockConfigSection.contacts: + return l10n.stockConfig_sectionContacts(config.contacts?.length ?? 0); + default: + return sectionLabel(context, section, connector); + } + } + + String? _noteFor(StockConfigSection section) { + final l10n = context.l10n; + switch (section) { + case StockConfigSection.identity: + return l10n.importConfig_identityWarning; + case StockConfigSection.channels: + return l10n.importConfig_channelsNote; + case StockConfigSection.contacts: + return l10n.importConfig_contactsNote; + default: + return null; + } + } + + Future _pickFile() async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + setState(() => _busy = true); + try { + final file = await openFile( + acceptedTypeGroups: const [ + XTypeGroup(label: 'JSON', extensions: ['json']), + ], + ); + if (file == null) return; + final source = utf8.decode( + await file.readAsBytes(), + allowMalformed: true, + ); + final parsed = StockConfig.parse(source); + if (!mounted) return; + setState(() { + _config = parsed; + _selected.clear(); + }); + } on StockConfigFormatException catch (e) { + // The exception carries the offending JSON path, so the user is told + // which part of the file is wrong rather than just "invalid". + messenger.showSnackBar( + SnackBar(content: Text(l10n.importConfig_parseFailed(e.toString()))), + ); + } catch (e) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.importConfig_parseFailed('$e'))), + ); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _import(MeshCoreConnector connector, StockConfig config) async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + + if (!connector.isConnected) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.importConfig_notConnected)), + ); + return; + } + if (_selected.isEmpty) { + messenger.showSnackBar( + SnackBar(content: Text(l10n.importConfig_nothingSelected)), + ); + return; + } + // Replacing the node identity is irreversible, so it gets its own explicit + // confirmation rather than riding along with the rest of the selection. + if (_selected.contains(StockConfigSection.identity)) { + final confirmed = await _confirmIdentityOverwrite(); + if (confirmed != true) return; + if (!mounted) return; + } + + setState(() => _busy = true); + try { + final result = await StockConfigImportService( + connector, + ).apply(config: config, sections: Set.of(_selected)); + if (!mounted) return; + await _showResult(result, connector); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _confirmIdentityOverwrite() { + final l10n = context.l10n; + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.importConfig_confirmIdentityTitle), + content: Text(l10n.importConfig_confirmIdentityBody), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(l10n.importConfig_cancel), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text(l10n.importConfig_confirmIdentityAccept), + ), + ], + ), + ); + } + + /// Shows what actually happened. Skipped channels and unapplied sections are + /// listed by name with a reason; an import that quietly did less than the + /// user asked for is the silent failure SAFELANE section 6 forbids. + Future _showResult( + StockConfigImportResult result, + MeshCoreConnector connector, + ) { + final l10n = context.l10n; + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.importConfig_resultTitle), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.importConfig_resultCounts( + result.contactsWritten, + result.channelsAdded, + ), + ), + if (result.failed.isNotEmpty) ...[ + const SizedBox(height: 12), + Text( + l10n.importConfig_resultFailedHeading, + style: Theme.of(context).textTheme.titleSmall, + ), + for (final entry in result.failed.entries) + Text( + l10n.importConfig_entryLine( + sectionLabel(context, entry.key, connector), + _reasonText(context, entry.value), + ), + ), + ], + if (result.skippedChannels.isNotEmpty) ...[ + const SizedBox(height: 12), + Text( + l10n.importConfig_resultSkippedHeading, + style: Theme.of(context).textTheme.titleSmall, + ), + for (final skipped in result.skippedChannels) + Text( + l10n.importConfig_entryLine( + skipped.name, + _reasonText(context, skipped.reason), + ), + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.importConfig_close), + ), + ], + ), + ); + } +} + +String _reasonText(BuildContext context, StockConfigImportIssue reason) { + final l10n = context.l10n; + switch (reason) { + case StockConfigImportIssue.absentFromFile: + return l10n.importConfig_reasonAbsentFromFile; + case StockConfigImportIssue.noReply: + return l10n.importConfig_reasonNoReply; + case StockConfigImportIssue.unsupported: + return l10n.importConfig_reasonUnsupported; + case StockConfigImportIssue.rejected: + return l10n.importConfig_reasonRejected; + case StockConfigImportIssue.alreadyPresent: + return l10n.importConfig_reasonAlreadyPresent; + case StockConfigImportIssue.noFreeSlot: + return l10n.importConfig_reasonNoFreeSlot; + case StockConfigImportIssue.notWritable: + return l10n.importConfig_reasonNotWritable; + } +} + +class _Banner extends StatelessWidget { + const _Banner({required this.text}); + + final String text; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + width: double.infinity, + color: theme.colorScheme.surfaceContainerHighest, + padding: const EdgeInsets.all(12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.info_outline, size: 18, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Expanded(child: Text(text)), + ], + ), + ); + } +} diff --git a/lib/screens/repeater_cli_screen.dart b/lib/screens/repeater_cli_screen.dart index 10e325ac..33e84324 100644 --- a/lib/screens/repeater_cli_screen.dart +++ b/lib/screens/repeater_cli_screen.dart @@ -103,11 +103,10 @@ class _RepeaterCliScreenState extends State { if (parsed == null) return; if (!_matchesRepeaterPrefix(parsed.senderPrefix)) return; - // Notify command service of response (for retry handling) + // Goes to the waiting command's future, which _sendCommand appends to the + // transcript. A reply whose window already closed is logged by the service + // to the app log and deliberately not shown here (#589). _commandService?.handleResponse(widget.repeater, parsed.text); - - // Note: The command service will handle the response via the Future - // We don't need to add it to history here anymore as _sendCommand will do it } bool _matchesRepeaterPrefix(Uint8List prefix) { @@ -170,10 +169,15 @@ class _RepeaterCliScreenState extends State { } } catch (e) { if (mounted) { + // A timeout knows the exact window that was armed, so it reports that + // rather than a rounded-up guess (#531). + final text = e is RepeaterCommandTimeout + ? context.l10n.repeater_cliCommandTimeout(e.secondsText) + : context.l10n.repeater_cliCommandError(e.toString()); setState(() { _commandHistory.add({ 'type': 'response', - 'text': context.l10n.repeater_cliCommandError(e.toString()), + 'text': text, 'timestamp': DateTime.now().toString(), }); }); @@ -184,7 +188,10 @@ class _RepeaterCliScreenState extends State { _historyIndex = -1; _commandFocusNode.requestFocus(); - // Auto-scroll to bottom + _scrollToBottom(); + } + + void _scrollToBottom() { Future.delayed(const Duration(milliseconds: 100), () { if (_scrollController.hasClients) { _scrollController.animateTo( @@ -450,6 +457,15 @@ class _RepeaterCliScreenState extends State { itemBuilder: (context, index) { final entry = _commandHistory[index]; final isCommand = entry['type'] == 'command'; + final scheme = Theme.of(context).colorScheme; + + final badgeColor = isCommand + ? scheme.primaryContainer + : scheme.secondaryContainer; + final badgeIconColor = isCommand + ? scheme.onPrimaryContainer + : scheme.onSecondaryContainer; + final badgeIcon = isCommand ? Icons.chevron_right : Icons.arrow_back; return Padding( padding: const EdgeInsets.only(bottom: 12), @@ -459,18 +475,10 @@ class _RepeaterCliScreenState extends State { Container( padding: const EdgeInsets.all(6), decoration: BoxDecoration( - color: isCommand - ? Theme.of(context).colorScheme.primaryContainer - : Theme.of(context).colorScheme.secondaryContainer, + color: badgeColor, borderRadius: BorderRadius.circular(4), ), - child: Icon( - isCommand ? Icons.chevron_right : Icons.arrow_back, - size: 16, - color: isCommand - ? Theme.of(context).colorScheme.onPrimaryContainer - : Theme.of(context).colorScheme.onSecondaryContainer, - ), + child: Icon(badgeIcon, size: 16, color: badgeIconColor), ), const SizedBox(width: 12), Expanded( @@ -482,9 +490,7 @@ class _RepeaterCliScreenState extends State { style: TextStyle( fontFamily: 'monospace', fontSize: 13, - color: isCommand - ? Theme.of(context).colorScheme.primary - : Theme.of(context).colorScheme.onSurface, + color: isCommand ? scheme.primary : scheme.onSurface, ), ), ], diff --git a/lib/screens/repeater_settings_screen.dart b/lib/screens/repeater_settings_screen.dart index 8e5c8922..f1a87478 100644 --- a/lib/screens/repeater_settings_screen.dart +++ b/lib/screens/repeater_settings_screen.dart @@ -6,9 +6,13 @@ import '../l10n/l10n.dart'; import '../models/contact.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +import '../models/radio_preset.dart'; +import '../services/radio_preset_service.dart'; import '../services/repeater_command_service.dart'; import '../services/storage_service.dart'; import '../widgets/path_management_dialog.dart'; +import '../widgets/radio_preset_picker.dart'; +import '../helpers/remote_radio_commands.dart'; import '../helpers/snack_bar_builder.dart'; class RepeaterSettingsScreen extends StatefulWidget { @@ -123,6 +127,12 @@ class _RepeaterSettingsScreenState extends State { int? _spreadingFactor; int? _codingRate; + /// Apply the radio params with `tempradio` (reverting after the duration) + /// instead of persisting them with `set radio` (#662). + bool _tempRadio = false; + final TextEditingController _tempRadioMinutesController = + TextEditingController(text: '$kTempRadioDefaultMinutes'); + // Location settings final TextEditingController _latController = TextEditingController(); final TextEditingController _lonController = TextEditingController(); @@ -150,6 +160,9 @@ class _RepeaterSettingsScreenState extends State { // Advanced int _pathHashMode = 0; // 0-2 + + /// The pending path hash came from a preset rather than the user (#735). + bool _pathHashFromPreset = false; final TextEditingController _txDelayController = TextEditingController(); final TextEditingController _directTxDelayController = TextEditingController(); @@ -185,8 +198,47 @@ class _RepeaterSettingsScreenState extends State { _commandService = RepeaterCommandService(connector); _setupMessageListener(); _loadSettings(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + Provider.of(context, listen: false).refreshIfStale(); + }); + } + + /// Fill the radio fields from a preset (#734). TX power is not part of a + /// remote preset: it is a separate command on these nodes. + void _applyPreset(RadioPreset preset) { + setState(() { + _freqController.text = preset.frequencyMHz.toStringAsFixed(3); + final bw = preset.bandwidth.hz; + if (!_bandwidthOptions.contains(bw)) { + _bandwidthOptions + ..add(bw) + ..sort(); + } + _bandwidth = bw; + _spreadingFactor = preset.spreadingFactor.value; + _codingRate = preset.codingRate.value; + final hashMode = preset.pathHashMode; + if (hashMode != null) { + _pathHashMode = hashMode; + _pathHashFromPreset = true; + } + }); + _markChanged(_SettingField.radio); + if (preset.pathHashMode != null) { + _markChanged(_SettingField.pathHashMode); + } } + String? _selectedPresetId(List presets) => matchRemotePresetId( + presets, + frequencyText: _freqController.text, + bandwidthHz: _bandwidth, + spreadingFactor: _spreadingFactor, + codingRate: _codingRate, + pathHashMode: _pathHashMode, + ); + @override void dispose() { _frameSubscription?.cancel(); @@ -196,6 +248,7 @@ class _RepeaterSettingsScreenState extends State { _guestPasswordController.dispose(); _freqController.dispose(); _txPowerController.dispose(); + _tempRadioMinutesController.dispose(); _latController.dispose(); _lonController.dispose(); _ownerInfoController.dispose(); @@ -709,6 +762,22 @@ class _RepeaterSettingsScreenState extends State { final connector = Provider.of(context, listen: false); final repeater = _resolveRepeater(connector); + final tempRadioMinutes = parseTempRadioMinutes( + _tempRadioMinutesController.text, + ); + if (_tempRadio && + _dirtyFields.contains(_SettingField.radio) && + tempRadioMinutes == null) { + showDismissibleSnackBar( + context, + content: Text( + context.l10n.repeater_tempRadioMinutesInvalid(kTempRadioMaxMinutes), + ), + backgroundColor: Colors.red, + ); + return; + } + setState(() { _isLoading = true; }); @@ -750,11 +819,22 @@ class _RepeaterSettingsScreenState extends State { _codingRate != null) { final freqText = _freqController.text.trim(); if (double.tryParse(freqText) != null) { - final bwKHz = _bandwidth! / 1000; pending.add(( field: _SettingField.radio, - command: - 'set radio $freqText,$bwKHz,$_spreadingFactor,$_codingRate', + command: _tempRadio + ? tempRadioCommand( + freqText, + _bandwidth!, + _spreadingFactor!, + _codingRate!, + tempRadioMinutes!, + ) + : setRadioCommand( + freqText, + _bandwidth!, + _spreadingFactor!, + _codingRate!, + ), )); } } @@ -846,10 +926,15 @@ class _RepeaterSettingsScreenState extends State { command: 'set owner.info $encoded', )); } - if (_dirtyFields.contains(_SettingField.pathHashMode)) { + final holdPresetPathHash = !sendsPresetPathHash( + temporaryRadio: _tempRadio, + pathHashFromPreset: _pathHashFromPreset, + ); + if (_dirtyFields.contains(_SettingField.pathHashMode) && + !holdPresetPathHash) { pending.add(( field: _SettingField.pathHashMode, - command: 'set path.hash.mode $_pathHashMode', + command: setPathHashModeCommand(_pathHashMode), )); } if (_dirtyFields.contains(_SettingField.txDelay) && @@ -893,7 +978,10 @@ class _RepeaterSettingsScreenState extends State { final retainDirty = <_SettingField>{}; var passwordsFailed = false; var rebootNeeded = false; - for (final entry in pending) { + for (final entry in withRetuneLast( + pending, + (e) => isRetuneCommand(e.command), + )) { var failed = false; try { final response = await _commandService!.sendCommand( @@ -924,6 +1012,15 @@ class _RepeaterSettingsScreenState extends State { await Future.delayed(const Duration(milliseconds: 200)); } + // A preset path hash held back from a temporary save stays pending, + // so a later normal save can still apply it. + if (holdPresetPathHash && + _dirtyFields.contains(_SettingField.pathHashMode)) { + retainDirty.add(_SettingField.pathHashMode); + } else if (!retainDirty.contains(_SettingField.pathHashMode)) { + _pathHashFromPreset = false; + } + // Only clear password fields if every password command succeeded, // otherwise the user keeps their typed value to retry. if (!passwordsFailed) { @@ -1249,6 +1346,20 @@ class _RepeaterSettingsScreenState extends State { onRefresh: _refreshRadioSettings, ), const Divider(), + Consumer( + builder: (context, service, _) { + final presets = service.presets + .where((p) => !p.offGrid) + .toList(); + return RadioPresetPicker( + service: service, + presets: presets, + selectedId: _selectedPresetId(presets), + onSelected: _applyPreset, + ); + }, + ), + const SizedBox(height: 8), TextField( controller: _freqController, decoration: InputDecoration( @@ -1347,6 +1458,43 @@ class _RepeaterSettingsScreenState extends State { } }, ), + CheckboxListTile( + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + title: Text(l10n.repeater_tempRadio), + subtitle: Text(l10n.repeater_tempRadioSubtitle), + value: _tempRadio, + onChanged: (value) { + setState(() => _tempRadio = value ?? false); + _markChanged(_SettingField.radio); + }, + ), + if (_tempRadio) + TextField( + controller: _tempRadioMinutesController, + decoration: InputDecoration( + labelText: l10n.repeater_tempRadioMinutes, + helperText: l10n.repeater_tempRadioMinutesInvalid( + kTempRadioMaxMinutes, + ), + border: const OutlineInputBorder(), + suffixText: 'min', + ), + keyboardType: TextInputType.number, + onChanged: (_) => _markChanged(_SettingField.radio), + ), + if (_tempRadio && + _pathHashFromPreset && + _dirtyFields.contains(_SettingField.pathHashMode)) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + l10n.repeater_tempRadioPathHashNote, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), const SizedBox(height: 8), _buildFeatureToggleRow( title: l10n.repeater_rxGain, @@ -1976,7 +2124,10 @@ class _RepeaterSettingsScreenState extends State { ], onChanged: (v) { if (v != null) { - setState(() => _pathHashMode = v); + setState(() { + _pathHashMode = v; + _pathHashFromPreset = false; + }); _markChanged(_SettingField.pathHashMode); } }, diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index 1ad1dc05..359d8ee6 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -133,6 +133,13 @@ class _ScannerScreenState extends State { if (_bluetoothState == BluetoothAdapterState.off) _bluetoothOffWarning(context), + // Unconfirmed BLE release: the OS never confirmed the last + // disconnect, so this device may still hold the radio and + // keep it from advertising (#689). Persistent until + // dismissed, per the error-visibility standard. + if (connector.bleReleaseUnconfirmed) + _bleReleaseWarning(context, connector), + // Status bar _buildStatusBar(context, connector), @@ -339,16 +346,35 @@ class _ScannerScreenState extends State { ); return; } + // Never show a raw exception to the user (#522/#698): the full detail + // goes to the log, the snackbar gets a plain-language message and + // persists until dismissed. + appLogger.error('Connect failed: $e', tag: 'ScannerScreen'); if (context.mounted) { showDismissibleSnackBar( context, - content: Text(context.l10n.scanner_connectionFailed(e.toString())), + content: Text( + context.l10n.scanner_connectionFailed(_describeConnectError(e)), + ), backgroundColor: Colors.red, + persist: true, ); } } } + String _describeConnectError(Object e) { + final l10n = context.l10n; + if (e is FlutterBluePlusException && e.code == 133) { + return l10n.scanner_connectFailedTransient; + } + if (e is TimeoutException || + (e is FlutterBluePlusException && e.function == 'connect')) { + return l10n.scanner_connectFailedTimeout; + } + return l10n.scanner_connectFailedGeneric; + } + Future _promptLinuxPairingPin( BuildContext context, String deviceName, @@ -435,6 +461,48 @@ class _ScannerScreenState extends State { return pin; } + Widget _bleReleaseWarning(BuildContext context, MeshCoreConnector connector) { + final errorColor = Theme.of(context).colorScheme.error; + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + color: errorColor.withValues(alpha: 0.15), + child: Row( + children: [ + Icon(Icons.bluetooth_connected, size: 24, color: errorColor), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + context.l10n.scanner_bleReleaseWarning, + style: TextStyle( + color: errorColor, + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + const SizedBox(height: 4), + Text( + context.l10n.scanner_bleReleaseWarningMessage, + style: TextStyle( + color: errorColor.withValues(alpha: 0.85), + fontSize: 12, + ), + ), + ], + ), + ), + TextButton( + onPressed: connector.clearBleReleaseWarning, + child: Text(context.l10n.common_ok), + ), + ], + ), + ); + } + Widget _bluetoothOffWarning(BuildContext context) { final errorColor = Theme.of(context).colorScheme.error; return Container( diff --git a/lib/screens/serial_capture_screen.dart b/lib/screens/serial_capture_screen.dart index f5a749de..a9d6465e 100644 --- a/lib/screens/serial_capture_screen.dart +++ b/lib/screens/serial_capture_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -8,6 +9,7 @@ import 'package:provider/provider.dart'; import '../connector/caplog_reassembler.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +import '../helpers/snack_bar_builder.dart'; import '../utils/log_export.dart'; /// Serial-capture diagnostics screen (#430). @@ -37,6 +39,7 @@ class _SerialCaptureScreenState extends State { int _durationMinutes = 5; bool _busy = false; String? _error; + String? _warning; bool _wasConnected = false; DateTime? _startedAt; @@ -247,27 +250,48 @@ class _SerialCaptureScreenState extends State { setState(() { _busy = true; _error = null; + _warning = null; }); try { - final bytes = await c.downloadCaplog(); + final result = await c.downloadCaplog(); if (!mounted) return; - if (bytes.isEmpty) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Buffer is empty, nothing to download.'), - ), + if (result.bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: const Text('Buffer is empty, nothing to download.'), ); return; } + // A truncated capture is kept, not discarded: mark the file partial (so a + // partial log is never mistaken for a complete one) and warn the user, but + // still write and offer to save/share it (#580). final dir = await getTemporaryDirectory(); final ts = DateTime.now(); final name = 'serial-capture-' '${ts.year}${_pad2(ts.month)}${_pad2(ts.day)}-' - '${_pad2(ts.hour)}${_pad2(ts.minute)}${_pad2(ts.second)}.txt'; + '${_pad2(ts.hour)}${_pad2(ts.minute)}${_pad2(ts.second)}' + '${result.truncated ? '-partial' : ''}.txt'; final file = File('${dir.path}${Platform.pathSeparator}$name'); - await file.writeAsBytes(bytes); + if (result.truncated) { + final header = utf8.encode( + '# PARTIAL Offband serial capture: ' + '${result.received} of ${result.expected} bytes in ' + '${result.chunks} chunks. Incomplete ' + '(see OffbandMesh/meshcore-firmware#711).\n\n', + ); + await file.writeAsBytes([...header, ...result.bytes]); + } else { + await file.writeAsBytes(result.bytes); + } if (!mounted) return; + if (result.truncated) { + setState( + () => _warning = + 'Partial capture: ${result.received} of ${result.expected} ' + 'bytes. Saving what was captured.', + ); + } await LogExport.shareFile( context, file, @@ -279,8 +303,6 @@ class _SerialCaptureScreenState extends State { () => _error = 'Device busy (another transfer in progress). Retry.', ); } - } on CaplogTruncatedException catch (e) { - if (mounted) setState(() => _error = 'Capture truncated: $e'); } on TimeoutException { if (mounted) setState(() => _error = 'No response from device.'); } catch (e) { @@ -381,6 +403,24 @@ class _SerialCaptureScreenState extends State { ), ), ), + if (_warning != null) + Card( + color: Theme.of(context).colorScheme.tertiaryContainer, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + const Icon(Icons.warning_amber_outlined), + const SizedBox(width: 8), + Expanded(child: Text(_warning!)), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => setState(() => _warning = null), + ), + ], + ), + ), + ), Card( child: Padding( padding: const EdgeInsets.all(16), @@ -451,7 +491,7 @@ class _SerialCaptureScreenState extends State { OutlinedButton.icon( onPressed: _busy || capturing ? null : _download, icon: Icon(LogExport.icon), - label: const Text('Download & share'), + label: Text('Download & ${LogExport.actionVerb}'), ), const SizedBox(height: 8), TextButton.icon( diff --git a/lib/screens/settings/broker_editor_screen.dart b/lib/screens/settings/broker_editor_screen.dart index 2dc78ab9..6b6edb52 100644 --- a/lib/screens/settings/broker_editor_screen.dart +++ b/lib/screens/settings/broker_editor_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; +import '../../helpers/snack_bar_builder.dart'; import '../../models/observer_config.dart'; import '../../services/observer_config_service.dart'; @@ -133,11 +134,10 @@ class _BrokerEditorScreenState extends State { } void _snack(String msg, {bool isError = false}) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(msg), - backgroundColor: isError ? Theme.of(context).colorScheme.error : null, - ), + showDismissibleSnackBar( + context, + content: Text(msg), + backgroundColor: isError ? Theme.of(context).colorScheme.error : null, ); } diff --git a/lib/screens/settings/config_profile_preview_screen.dart b/lib/screens/settings/config_profile_preview_screen.dart index a790fc7a..e3853315 100644 --- a/lib/screens/settings/config_profile_preview_screen.dart +++ b/lib/screens/settings/config_profile_preview_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../helpers/config_profile_diff.dart'; import '../../helpers/config_profile_writes.dart'; +import '../../helpers/snack_bar_builder.dart'; import '../../models/config_profile.dart'; import '../../services/observer_apply_service.dart'; import '../../services/observer_config_service.dart'; @@ -79,13 +80,12 @@ class _ConfigProfilePreviewScreenState ? '$what applied.' : '$what: ${result.failures.length} of ${result.items.length} failed ' '(${result.failures.first.error ?? 'error'}).'; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(msg), - backgroundColor: result.allOk - ? null - : Theme.of(context).colorScheme.error, - ), + showDismissibleSnackBar( + context, + content: Text(msg), + backgroundColor: result.allOk + ? null + : Theme.of(context).colorScheme.error, ); await _load(); // re-diff against true state (partial-save recovery) } finally { diff --git a/lib/screens/settings/observer_settings_view.dart b/lib/screens/settings/observer_settings_view.dart index 64297a61..51704096 100644 --- a/lib/screens/settings/observer_settings_view.dart +++ b/lib/screens/settings/observer_settings_view.dart @@ -4,6 +4,7 @@ import 'package:provider/provider.dart'; import '../../connector/meshcore_connector.dart'; import '../../models/observer_config.dart'; +import '../../helpers/snack_bar_builder.dart'; import '../../services/observer_config_service.dart'; import 'config_profile_import_screen.dart'; import 'mqtt_brokers_screen.dart'; @@ -163,18 +164,16 @@ class _ObserverSettingsViewState extends State { _seedFromConfig(svc.config); if (!mounted) return; setState(() => _saving = false); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - invalidInterval - ? 'Status interval must be 10–3600 seconds' - : ok - ? 'Observer settings saved' - : (svc.lastError ?? - 'Some changes failed. Re-read from the device'), - ), - backgroundColor: ok ? null : Theme.of(context).colorScheme.error, + showDismissibleSnackBar( + context, + content: Text( + invalidInterval + ? 'Status interval must be 10–3600 seconds' + : ok + ? 'Observer settings saved' + : (svc.lastError ?? 'Some changes failed. Re-read from the device'), ), + backgroundColor: ok ? null : Theme.of(context).colorScheme.error, ); } diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 01654664..9b6f9c14 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -5,14 +7,17 @@ import 'package:meshcore_open/utils/gpx_export.dart'; import 'package:meshcore_open/widgets/elements_ui.dart'; import 'package:provider/provider.dart'; import 'package:package_info_plus/package_info_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../l10n/l10n.dart'; import '../models/offband_gps_status.dart'; +import '../models/radio_preset.dart'; import '../models/radio_settings.dart'; import '../services/app_debug_log_service.dart'; import '../services/app_settings_service.dart'; +import '../services/radio_preset_service.dart'; import '../connector/observer_config_client.dart'; import '../helpers/snack_bar_builder.dart'; import '../utils/build_info.dart'; @@ -24,9 +29,12 @@ import 'settings/blocked_view.dart'; import 'settings/device_ui_view.dart'; import 'app_debug_log_screen.dart'; import 'ble_debug_log_screen.dart'; +import 'export_config_screen.dart'; +import 'import_config_screen.dart'; import 'serial_capture_screen.dart'; import 'topology_debug_screen.dart'; import 'companion_radio_stats_screen.dart'; +import '../widgets/radio_preset_picker.dart'; import '../widgets/sync_progress_overlay.dart'; /// Convert device coding-rate value (1-4 on some firmware, 5-8 on others) @@ -55,12 +63,29 @@ class _SettingsScreenState extends State { bool _showBatteryVoltage = false; String _appVersion = ''; + // #509 hidden unlock: 7 taps on the version row within a rolling window + // reveals the Experimental settings section. + static const int _experimentalUnlockTaps = 7; + static const Duration _experimentalTapWindow = Duration(seconds: 3); + int _versionTapCount = 0; + DateTime? _lastVersionTap; + // Inline feedback shown in the version row itself (no snackbar: a bottom + // snackbar overlaps the very row being tapped and blocks the next tap). + String? _versionHint; + Timer? _versionHintTimer; + @override void initState() { super.initState(); _loadVersionInfo(); } + @override + void dispose() { + _versionHintTimer?.cancel(); + super.dispose(); + } + Future _loadVersionInfo() async { final packageInfo = await PackageInfo.fromPlatform(); if (!mounted) return; @@ -69,6 +94,42 @@ class _SettingsScreenState extends State { }); } + void _handleUnlockTap() { + final l10n = context.l10n; + final settingsService = context.read(); + + if (settingsService.settings.experimentalUnlocked) { + _versionTapCount = 0; + _setVersionHint(l10n.settings_experimentalAlreadyUnlocked); + return; + } + + final now = DateTime.now(); + if (_lastVersionTap == null || + now.difference(_lastVersionTap!) > _experimentalTapWindow) { + _versionTapCount = 0; + } + _lastVersionTap = now; + _versionTapCount++; + + final remaining = _experimentalUnlockTaps - _versionTapCount; + if (remaining <= 0) { + _versionTapCount = 0; + settingsService.setExperimentalUnlocked(true); + _setVersionHint(l10n.settings_experimentalUnlocked); + } else if (remaining <= 3) { + _setVersionHint(l10n.settings_experimentalCountdown(remaining)); + } + } + + void _setVersionHint(String hint) { + _versionHintTimer?.cancel(); + setState(() => _versionHint = hint); + _versionHintTimer = Timer(const Duration(seconds: 2), () { + if (mounted) setState(() => _versionHint = null); + }); + } + @override Widget build(BuildContext context) { final l10n = context.l10n; @@ -90,6 +151,12 @@ class _SettingsScreenState extends State { offbandCaps: c.offbandCaps ?? 0, ), ); + // Owner-only Experimental section (#509), revealed by the 7-tap gesture on + // the About version row. Selects narrowly so the category list only rebuilds + // when the flag flips, not on every connector update (same reason as above). + final experimentalUnlocked = context.select( + (s) => s.settings.experimentalUnlocked, + ); return [ SettingsCategory( icon: Icons.badge_outlined, @@ -155,14 +222,75 @@ class _SettingsScreenState extends State { title: l10n.settings_actions, builder: _actionsPane, ), + if (experimentalUnlocked) + SettingsCategory( + icon: Icons.science_outlined, + title: l10n.settings_experimental, + subtitle: l10n.settings_experimentalSubtitle, + builder: _experimentalPane, + ), SettingsCategory( icon: Icons.build_outlined, title: l10n.settings_debug, builder: _diagnosticsPane, ), + SettingsCategory( + icon: Icons.info_outline, + title: l10n.settings_about, + builder: _aboutPane, + ), ]; } + Widget _experimentalPane(BuildContext context) { + final l10n = context.l10n; + final settingsService = context.watch(); + final supportsPktHash = context.select( + (c) => c.supportsPktHash, + ); + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Text(l10n.settings_experimentalDescription), + ), + ), + const SizedBox(height: 16), + // CoreScope observer counts (#524). Disabled until the connected radio + // advertises the 0xC6 packet-hash capability. + Card( + child: SwitchListTile( + secondary: const Icon(Icons.cloud_outlined), + title: Text(l10n.settings_coreScopeObserverCount), + subtitle: Text( + supportsPktHash + ? l10n.settings_coreScopeObserverCountSubtitle + : l10n.settings_coreScopeObserverCountUnsupported, + ), + value: settingsService.settings.coreScopeObserverCountEnabled, + onChanged: supportsPktHash + ? (value) => + settingsService.setCoreScopeObserverCountEnabled(value) + : null, + ), + ), + const SizedBox(height: 16), + // Disable, not just hide: turns off every experimental toggle and + // re-locks the section, so nothing keeps running invisibly (#553). + Card( + child: ListTile( + leading: const Icon(Icons.block), + title: Text(l10n.settings_experimentalDisable), + subtitle: Text(l10n.settings_experimentalDisableSubtitle), + onTap: () => settingsService.disableExperimental(), + ), + ), + ], + ); + } + Widget _observerPane(BuildContext context) => const ObserverSettingsView(); Widget _blockedPane(BuildContext context) => const BlockedView(); @@ -409,8 +537,6 @@ class _SettingsScreenState extends State { _buildDebugCard(context), const SizedBox(height: 16), _buildExportCard(connector), - const SizedBox(height: 16), - _buildAboutCard(context), ], ); } @@ -504,11 +630,25 @@ class _SettingsScreenState extends State { // #397: identity of the running binary, injected at build time and // independent of the marketing version. Its own line so "which build // am I on" is answerable at a glance; copyable for bug reports. + // Also the hidden 7-tap Experimental unlock anchor (#509/#553), + // mirroring Android's Software-info build-number gesture. _buildInfoRow( l10n.settings_infoBuild, BuildInfo.stamp, copyValue: BuildInfo.stamp, + onTap: _handleUnlockTap, ), + if (_versionHint != null) + Padding( + padding: const EdgeInsets.only(top: 2, bottom: 6), + child: Text( + _versionHint!, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), + ), ], ), ), @@ -631,22 +771,105 @@ class _SettingsScreenState extends State { ); } - Widget _buildAboutCard(BuildContext context) { + // About is its own top-level Settings category (#525/#526), no longer a card + // in the Debug pane. Outbound links (offband.org / Play / donate) added by + // #527 between the info block and the licenses row. + Widget _aboutPane(BuildContext context) { final l10n = context.l10n; - return Card( - child: ListTile( - leading: const Icon(Icons.info_outline), - title: Text(l10n.settings_about), - subtitle: Text( - l10n.settings_aboutVersion( - _appVersion.isEmpty ? l10n.common_loading : _appVersion, + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListTile( + leading: const Icon(Icons.info_outline), + title: Text(l10n.appTitle), + subtitle: Text( + l10n.settings_aboutVersion( + _appVersion.isEmpty ? l10n.common_loading : _appVersion, + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.settings_aboutDescription), + const SizedBox(height: 12), + Text( + l10n.settings_aboutLegalese, + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 4), + Text( + l10n.settings_aboutPresetsAttribution, + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.language), + title: Text(l10n.settings_aboutWebsite), + trailing: const Icon(Icons.open_in_new, size: 18), + onTap: () => _openExternalUrl('https://offband.org'), + ), + ListTile( + leading: const Icon(Icons.shop_outlined), + title: Text(l10n.settings_aboutPlayStore), + trailing: const Icon(Icons.open_in_new, size: 18), + onTap: () => _openExternalUrl( + 'https://play.google.com/store/apps/details?id=app.offband.meshcore', + ), + ), + ListTile( + leading: const Icon(Icons.favorite_outline), + title: Text(l10n.settings_aboutDonate), + trailing: const Icon(Icons.open_in_new, size: 18), + onTap: () => _openExternalUrl('https://offband.org/donate'), + ), + const Divider(height: 1), + ListTile( + leading: const Icon(Icons.description_outlined), + title: Text(l10n.settings_aboutLicenses), + trailing: const Icon(Icons.chevron_right), + onTap: () => showLicensePage( + context: context, + applicationName: l10n.appTitle, + applicationVersion: _appVersion.isEmpty ? null : _appVersion, + applicationLegalese: l10n.settings_aboutLegalese, + ), + ), + ], ), ), - onTap: () => _showAbout(context), - ), + ], ); } + Future _openExternalUrl(String url) async { + try { + if (await launchUrl( + Uri.parse(url), + mode: LaunchMode.externalApplication, + )) { + return; + } + } catch (_) { + // fall through to the failure message + } + if (mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.settings_aboutLinkFailed), + ); + } + } + Widget _buildDebugCard(BuildContext context) { final l10n = context.l10n; final settingsService = context.watch(); @@ -823,13 +1046,25 @@ class _SettingsScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( - child: SelectableText( - value, - style: theme.textTheme.bodyLarge?.copyWith( - color: valueColor, - fontWeight: FontWeight.w500, - ), - ), + // When the row is tappable, use a plain Text so the value is + // part of the InkWell tap target (a SelectableText would eat + // the tap for selection). Copy is still available via the + // button. (#553) + child: onTap != null + ? Text( + value, + style: theme.textTheme.bodyLarge?.copyWith( + color: valueColor, + fontWeight: FontWeight.w500, + ), + ) + : SelectableText( + value, + style: theme.textTheme.bodyLarge?.copyWith( + color: valueColor, + fontWeight: FontWeight.w500, + ), + ), ), IconButton( icon: const Icon(Icons.copy, size: 18), @@ -838,10 +1073,9 @@ class _SettingsScreenState extends State { onPressed: () async { await Clipboard.setData(ClipboardData(text: copyValue)); if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(context.l10n.settings_publicKeyCopied), - ), + showDismissibleSnackBar( + context, + content: Text(context.l10n.settings_publicKeyCopied), ); }, ), @@ -1279,22 +1513,6 @@ class _SettingsScreenState extends State { ); } - void _showAbout(BuildContext context) { - final l10n = context.l10n; - showAboutDialog( - context: context, - applicationName: l10n.appTitle, - applicationVersion: _appVersion.isEmpty - ? l10n.common_loading - : _appVersion, - applicationLegalese: l10n.settings_aboutLegalese, - children: [ - const SizedBox(height: 16), - Text(l10n.settings_aboutDescription), - ], - ); - } - Future _gpxExport( GpxExport exporter, String name, @@ -1344,6 +1562,30 @@ class _SettingsScreenState extends State { return Card( child: Column( children: [ + // Stock-compatible whole-device backup and restore (#568), distinct + // from the GPX exports below, which are map data only. + ListTile( + leading: const Icon(Icons.save_alt), + title: Text(l10n.settings_exportConfig), + subtitle: Text(l10n.settings_configBackupSubtitle), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const ExportConfigScreen(), + ), + ), + ), + ListTile( + leading: const Icon(Icons.upload_file), + title: Text(l10n.settings_importConfig), + trailing: const Icon(Icons.chevron_right), + onTap: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const ImportConfigScreen(), + ), + ), + ), + const Divider(height: 1), ListTile( leading: const Icon(Icons.download_outlined), title: Text(l10n.settings_gpxExportRepeaters), @@ -1795,15 +2037,19 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5; final _txPowerController = TextEditingController(text: '20'); bool _clientRepeat = false; - int? _selectedPresetIndex; + String? _selectedPresetId; _RadioSettingsSnapshot? _lastNonRepeatSnapshot; + late final RadioPresetService _presetService; AppDebugLogService get _appLog => Provider.of(context, listen: false); + List get _presets => _presetService.presets; + @override void initState() { super.initState(); + _presetService = Provider.of(context, listen: false); // Populate with current settings if available if (widget.connector.currentFreqHz != null) { @@ -1851,64 +2097,95 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { } _clientRepeat = widget.connector.clientRepeat ?? false; - _selectedPresetIndex = _findMatchingPresetIndex(); + _selectedPresetId = _findMatchingPresetId(); if (_clientRepeat) { _lastNonRepeatSnapshot = _sessionRememberedNonRepeatSnapshot() ?? _inferNonRepeatSnapshotForRepeatEnabled(); - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _selectedPresetId = _findMatchingPresetIdForSnapshot( _lastNonRepeatSnapshot!, ); } else { _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); } + _presetService.addListener(_onPresetsChanged); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; _logRadioSettingsState('Dialog initialized'); + _presetService.refreshIfStale(); }); } @override void dispose() { + _presetService.removeListener(_onPresetsChanged); _frequencyController.dispose(); _txPowerController.dispose(); super.dispose(); } - void _applyPreset(int index) { + /// A refresh can change the list under an open form; re-match the selection. + void _onPresetsChanged() { + if (!mounted) return; + setState(_syncPresetSelection); + } + + RadioPreset? _presetById(String? id) { + if (id == null) return null; + return _presets.where((p) => p.id == id).firstOrNull; + } + + void _applyPreset(RadioPreset preset) { setState(() { - _applyPresetState(index); + _applyPresetState(preset); }); - _logRadioSettingsState( - 'Applied preset ${RadioSettings.presets[index].$1} (#$index)', - ); + _logRadioSettingsState('Applied preset ${preset.title} (${preset.id})'); } - int? _findMatchingPresetIndex() { - return _findMatchingPresetIndexForSnapshot(_currentSnapshot()); + String? _findMatchingPresetId() { + return _findMatchingPresetIdForSnapshot(_currentSnapshot()); } - int? _findMatchingPresetIndexForSnapshot(_RadioSettingsSnapshot snapshot) { - for (final i in _visiblePresetIndexes()) { - final preset = RadioSettings.presets[i].$2; - if (preset.frequencyHz == snapshot.frequencyHz && - preset.bandwidth == snapshot.bandwidth && - preset.spreadingFactor == snapshot.spreadingFactor && - preset.codingRate == snapshot.codingRate && - preset.txPowerDbm == snapshot.txPowerDbm) { - return i; + /// A preset without TX power (every upstream one) matches any power. + bool _presetMatches( + RadioPreset preset, + _RadioSettingsSnapshot snapshot, { + int? frequencyHz, + }) { + // _RadioSettingsSnapshot.frequencyHz is also kHz, despite its name. + return (frequencyHz ?? preset.frequencyKHz) == snapshot.frequencyHz && + preset.bandwidth == snapshot.bandwidth && + preset.spreadingFactor == snapshot.spreadingFactor && + preset.codingRate == snapshot.codingRate && + (preset.txPowerDbm == null || + preset.txPowerDbm == snapshot.txPowerDbm) && + presetPathHashMatches(preset, widget.connector.pathHashByteWidth); + } + + String? _findMatchingPresetIdForSnapshot(_RadioSettingsSnapshot snapshot) { + for (final preset in _visiblePresets()) { + if (_presetMatches(preset, snapshot)) { + return preset.id; } } return null; } - Iterable _visiblePresetIndexes() sync* { - for (var i = 0; i < RadioSettings.presets.length; i++) { - if (_isOffGridPresetIndex(i)) { - continue; - } - yield i; - } + Iterable _visiblePresets() => _presets.where((p) => !p.offGrid); + + /// The snapshot a preset sets; TX power stays as it is when the preset has + /// none. + _RadioSettingsSnapshot _snapshotForPreset( + RadioPreset preset, + int currentTxPowerDbm, + ) { + return _RadioSettingsSnapshot( + frequencyMHz: preset.frequencyMHz, + bandwidth: preset.bandwidth, + spreadingFactor: preset.spreadingFactor, + codingRate: preset.codingRate, + txPowerDbm: preset.txPowerDbm ?? currentTxPowerDbm, + ); } _RadioSettingsSnapshot _currentSnapshot() { @@ -1923,10 +2200,7 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { ); } - bool _isOffGridPresetIndex(int? index) { - if (index == null) return false; - return RadioSettings.presets[index].$1.startsWith('Off-Grid '); - } + bool _isOffGridPreset(String? id) => _presetById(id)?.offGrid ?? false; double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) { if (baseFrequencyMHz < 500) return 433.0; @@ -1954,7 +2228,7 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { _RadioSettingsSnapshot _nonRepeatSnapshotForCurrentSelection() { final current = _currentSnapshot(); - if (!_isOffGridPresetIndex(_selectedPresetIndex)) { + if (!_isOffGridPreset(_selectedPresetId)) { return current; } return _fallbackNonRepeatSnapshot(current.frequencyMHz); @@ -1968,23 +2242,12 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { _RadioSettingsSnapshot _inferNonRepeatSnapshotForRepeatEnabled() { final current = _currentSnapshot(); - for (final i in _visiblePresetIndexes()) { - final preset = RadioSettings.presets[i].$2; + for (final preset in _visiblePresets()) { final offGridFreqHz = (_offGridFrequencyForBaseFrequency(preset.frequencyMHz) * 1000) .round(); - if (offGridFreqHz == current.frequencyHz && - preset.bandwidth == current.bandwidth && - preset.spreadingFactor == current.spreadingFactor && - preset.codingRate == current.codingRate && - preset.txPowerDbm == current.txPowerDbm) { - return _RadioSettingsSnapshot( - frequencyMHz: preset.frequencyMHz, - bandwidth: preset.bandwidth, - spreadingFactor: preset.spreadingFactor, - codingRate: preset.codingRate, - txPowerDbm: preset.txPowerDbm, - ); + if (_presetMatches(preset, current, frequencyHz: offGridFreqHz)) { + return _snapshotForPreset(preset, current.txPowerDbm); } } return _fallbackNonRepeatSnapshot(current.frequencyMHz); @@ -1998,14 +2261,10 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { _txPowerController.text = snapshot.txPowerDbm.toString(); } - void _applyPresetState(int index) { - final preset = RadioSettings.presets[index].$2; - final baseSnapshot = _RadioSettingsSnapshot( - frequencyMHz: preset.frequencyMHz, - bandwidth: preset.bandwidth, - spreadingFactor: preset.spreadingFactor, - codingRate: preset.codingRate, - txPowerDbm: preset.txPowerDbm, + void _applyPresetState(RadioPreset preset) { + final baseSnapshot = _snapshotForPreset( + preset, + int.tryParse(_txPowerController.text) ?? 20, ); final frequencyMHz = _clientRepeat ? _offGridFrequencyForBaseFrequency(baseSnapshot.frequencyMHz) @@ -2014,13 +2273,13 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { _bandwidth = preset.bandwidth; _spreadingFactor = preset.spreadingFactor; _codingRate = preset.codingRate; - _txPowerController.text = preset.txPowerDbm.toString(); - _selectedPresetIndex = index; + _txPowerController.text = baseSnapshot.txPowerDbm.toString(); + _selectedPresetId = preset.id; _lastNonRepeatSnapshot = baseSnapshot; } void _syncPresetSelection() { - final previousPresetIndex = _selectedPresetIndex; + final previousPresetId = _selectedPresetId; final previousLastNonRepeat = _lastNonRepeatSnapshot; if (_clientRepeat) { final baseSnapshot = @@ -2038,25 +2297,25 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { txPowerDbm: int.tryParse(_txPowerController.text) ?? 20, ); } - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _selectedPresetId = _findMatchingPresetIdForSnapshot( _lastNonRepeatSnapshot ?? baseSnapshot, ); - if (previousPresetIndex != _selectedPresetIndex || + if (previousPresetId != _selectedPresetId || previousLastNonRepeat != _lastNonRepeatSnapshot) { _logRadioSettingsState( - 'Preset match updated while repeat enabled: ${_presetLabel(previousPresetIndex)} -> ${_presetLabel(_selectedPresetIndex)}', + 'Preset match updated while repeat enabled: ${_presetLabel(previousPresetId)} -> ${_presetLabel(_selectedPresetId)}', ); } return; } _lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection(); - _selectedPresetIndex = _findMatchingPresetIndexForSnapshot( + _selectedPresetId = _findMatchingPresetIdForSnapshot( _lastNonRepeatSnapshot!, ); - if (previousPresetIndex != _selectedPresetIndex || + if (previousPresetId != _selectedPresetId || previousLastNonRepeat != _lastNonRepeatSnapshot) { _logRadioSettingsState( - 'Preset sync updated state from ${_presetLabel(previousPresetIndex)} to ${_presetLabel(_selectedPresetIndex)}', + 'Preset sync updated state from ${_presetLabel(previousPresetId)} to ${_presetLabel(_selectedPresetId)}', ); } } @@ -2151,6 +2410,15 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { ), ); await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); + // A preset that carries a path hash size sets it too (stock + // CMD_SET_PATH_HASH_MODE, #730). Sent whenever the preset has one, + // rather than compared against the reported width, which reads as 1 + // when device info is short (#240). Setting the same mode is harmless. + final pathHashMode = _presetById(_selectedPresetId)?.pathHashMode; + if (pathHashMode != null) { + _logRadioSettingsState('Setting preset path hash mode $pathHashMode'); + await widget.connector.setPathHashMode(pathHashMode); + } await widget.connector.refreshDeviceInfo(); final rememberedSnapshot = _clientRepeat ? _lastNonRepeatSnapshot @@ -2177,11 +2445,12 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { } } - String _presetLabel(int? index) { - if (index == null) { + String _presetLabel(String? id) { + if (id == null) { return 'custom'; } - return '${RadioSettings.presets[index].$1} (#$index)'; + final preset = _presetById(id); + return preset == null ? id : '${preset.title} ($id)'; } String _formatSnapshot(_RadioSettingsSnapshot? snapshot) { @@ -2205,7 +2474,7 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { 'cr=${_codingRate.label} ' 'tx=${_txPowerController.text}dBm ' 'repeat=$_clientRepeat ' - 'preset=${_presetLabel(_selectedPresetIndex)} ' + 'preset=${_presetLabel(_selectedPresetId)} ' 'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}', tag: 'RadioSettings', ); @@ -2214,31 +2483,18 @@ class _RadioSettingsFormState extends State<_RadioSettingsForm> { @override Widget build(BuildContext context) { final l10n = context.l10n; + final presetService = context.watch(); return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - DropdownButtonFormField( - key: ValueKey(_selectedPresetIndex), - initialValue: _selectedPresetIndex, - decoration: InputDecoration( - labelText: l10n.settings_presets, - border: const OutlineInputBorder(), - ), - items: [ - for (final i in _visiblePresetIndexes()) - DropdownMenuItem( - value: i, - child: Text(RadioSettings.presets[i].$1), - ), - ], - onChanged: (index) { - if (index != null) { - _applyPreset(index); - } - }, + RadioPresetPicker( + service: presetService, + presets: _visiblePresets().toList(), + selectedId: _selectedPresetId, + onSelected: _applyPreset, ), - const SizedBox(height: 16), + const SizedBox(height: 8), TextField( controller: _frequencyController, onChanged: (_) => _handleManualSettingsChanged('frequency'), diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 4352f411..8f41bf0c 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -182,6 +182,27 @@ class AppSettingsService extends ChangeNotifier { appLogger.setEnabled(value); } + Future setExperimentalUnlocked(bool value) async { + await updateSettings(_settings.copyWith(experimentalUnlocked: value)); + } + + Future setCoreScopeObserverCountEnabled(bool value) async { + await updateSettings( + _settings.copyWith(coreScopeObserverCountEnabled: value), + ); + } + + /// Turn off every experimental feature flag and re-lock the section (#553). + /// Add each new experimental toggle here so "Disable" truly disables all. + Future disableExperimental() async { + await updateSettings( + _settings.copyWith( + coreScopeObserverCountEnabled: false, + experimentalUnlocked: false, + ), + ); + } + Future setMapShowDiscoveryContacts(bool value) async { await updateSettings(_settings.copyWith(mapShowDiscoveryContacts: value)); } diff --git a/lib/services/ble_debug_log_service.dart b/lib/services/ble_debug_log_service.dart index b4685f23..33f42ff2 100644 --- a/lib/services/ble_debug_log_service.dart +++ b/lib/services/ble_debug_log_service.dart @@ -167,6 +167,8 @@ class BleDebugLogService extends ChangeNotifier { return 'CMD_RESET_PATH'; case cmdRemoveContact: return 'CMD_REMOVE_CONTACT'; + case cmdGetContactByKey: + return 'CMD_GET_CONTACT_BY_KEY'; case cmdReboot: return 'CMD_REBOOT'; case cmdGetBattAndStorage: diff --git a/lib/services/config_source_service.dart b/lib/services/config_source_service.dart index 0ea976d9..90a3b1dc 100644 --- a/lib/services/config_source_service.dart +++ b/lib/services/config_source_service.dart @@ -76,6 +76,10 @@ class ConfigSourceService { return parseConfigProfile(await _get(url)); } + /// Fetch a file's raw text (radio presets, #728). Same cache-busting and + /// failure messages as the catalog and profile fetches. + Future fetchText(String url) => _get(url); + Future _get(String url) async { final http.Response resp; try { diff --git a/lib/services/corescope_service.dart b/lib/services/corescope_service.dart new file mode 100644 index 00000000..5dc46724 --- /dev/null +++ b/lib/services/corescope_service.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +import '../utils/app_logger.dart'; + +/// Default CoreScope instance (OKIMesh). Owner-run; its read API is public. +const String kDefaultCoreScopeHost = 'map.okimesh.org'; + +/// The two counts CoreScope reports for a packet. [observers] is the number of +/// distinct observers (the meaningful reach); [observations] is the total +/// sightings, which counts one observer hearing the packet via several paths +/// more than once (this is the "Observations (N)" number in CoreScope's UI). +class CoreScopeCounts { + const CoreScopeCounts({required this.observers, required this.observations}); + final int observers; + final int observations; +} + +/// Outcome of a CoreScope query, so the UI can tell "no record of this packet +/// yet" apart from "couldn't reach CoreScope" (#571). +enum CoreScopeStatus { found, notFound, unreachable } + +class CoreScopeResult { + const CoreScopeResult(this.status, [this.counts]); + final CoreScopeStatus status; + final CoreScopeCounts? counts; + + static const CoreScopeResult notFound = CoreScopeResult( + CoreScopeStatus.notFound, + ); + static const CoreScopeResult unreachable = CoreScopeResult( + CoreScopeStatus.unreachable, + ); + factory CoreScopeResult.found(CoreScopeCounts counts) => + CoreScopeResult(CoreScopeStatus.found, counts); +} + +/// Queries a CoreScope instance for how many observers reported a given packet, +/// keyed by the firmware/mesh packet hash (#524). Read-only and best-effort: +/// any failure (offline, timeout, non-200, bad body, unknown packet) returns +/// null so the chat UI can silently fall back to radio-only. Never throws. +class CoreScopeService { + CoreScopeService({ + http.Client? client, + this.host = kDefaultCoreScopeHost, + this.useTls = true, + this.timeout = const Duration(seconds: 6), + }) : _client = client ?? http.Client(); + + final http.Client _client; + final String host; + final bool useTls; + final Duration timeout; + + /// Distinct observers and total observations for [packetHash] (16 lowercase + /// hex chars). `notFound` = CoreScope reachable but has no record of the hash + /// yet; `unreachable` = network/HTTP/parse error. Never throws. + Future fetchCounts(String packetHash) async { + if (packetHash.isEmpty) return CoreScopeResult.unreachable; + final uri = Uri( + scheme: useTls ? 'https' : 'http', + host: host, + path: '/api/packets', + queryParameters: { + 'hash': packetHash, + 'groupByHash': 'true', + 'limit': '1', + }, + ); + appLogger.info('GET $uri', tag: 'CoreScope'); + try { + final resp = await _client.get(uri).timeout(timeout); + if (resp.statusCode != 200) { + appLogger.warn( + 'HTTP ${resp.statusCode} for hash $packetHash', + tag: 'CoreScope', + ); + return CoreScopeResult.unreachable; + } + final body = jsonDecode(resp.body); + if (body is! Map) return CoreScopeResult.unreachable; + final packets = body['packets']; + if (packets is! List) return CoreScopeResult.unreachable; + if (packets.isEmpty) { + appLogger.info('no record yet for $packetHash', tag: 'CoreScope'); + return CoreScopeResult.notFound; + } + final first = packets.first; + if (first is! Map) return CoreScopeResult.unreachable; + final observers = first['observer_count']; + if (observers is! num) return CoreScopeResult.unreachable; + final observations = first['observation_count']; + final counts = CoreScopeCounts( + observers: observers.toInt(), + observations: observations is num + ? observations.toInt() + : observers.toInt(), + ); + appLogger.info( + 'observers=${counts.observers} observations=${counts.observations} ' + 'for $packetHash', + tag: 'CoreScope', + ); + return CoreScopeResult.found(counts); + } catch (e) { + appLogger.warn('Query failed for $packetHash: $e', tag: 'CoreScope'); + return CoreScopeResult.unreachable; + } + } + + void dispose() => _client.close(); +} diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 8d048ed9..64758341 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -391,7 +391,74 @@ class MessageRetryService extends ChangeNotifier { _onMessageResolved(messageId, contact.publicKeyHex); } - bool updateMessageFromSent(int ackHash, int timeoutMs) { + /// Message ids whose send reached the radio but whose RESP_CODE_SENT has not + /// arrived yet. + List get _sendsAwaitingConfirmation => _sentConfirmationTimers.keys + .where((id) => _pendingMessages[id]?.status == MessageStatus.pending) + .toList(); + + /// The radio is authoritative for the expected-ACK hash it reports in + /// RESP_CODE_SENT. Firmware forks build the message payload differently, so + /// the hash recomputed locally can disagree while the send itself is fine. + /// When that happened the message stayed pending, the 8s watchdog from #395 + /// marked an already-delivered DM failed, and the genuine ACK later matched + /// nothing because every downstream map is only populated on the match path. + /// Captured on a Wadamesh radio in #449. + /// + /// This frame is the reply to our own CMD_SEND_TXT_MSG, so adopt the radio's + /// value when exactly one send is awaiting confirmation. With zero or several + /// candidates the correlation would be a guess, so keep the old behaviour. + /// + /// [allowed] is false when a channel message is also awaiting its + /// RESP_CODE_SENT. Channel sends share this frame, so adopting there could + /// attach a channel message's confirmation to an unrelated direct message. + String? _adoptUnpredictedSentHash( + String ackHashHex, + RetryServiceConfig config, { + required bool allowed, + }) { + if (!allowed) { + config.debugLogService?.warn( + 'RESP_CODE_SENT: ACK hash $ackHashHex matches no pending message and a ' + 'channel send is also awaiting confirmation, not adopting', + tag: 'AckHash', + ); + return null; + } + + final awaiting = _sendsAwaitingConfirmation; + if (awaiting.length != 1) { + config.debugLogService?.warn( + 'RESP_CODE_SENT: ACK hash $ackHashHex matches no pending message and ' + '${awaiting.length} sends are awaiting confirmation, ignoring', + tag: 'AckHash', + ); + return null; + } + + final messageId = awaiting.first; + final message = _pendingMessages[messageId]; + final text = message?.text ?? ''; + final shortText = text.length > 20 ? '${text.substring(0, 20)}...' : text; + config.debugLogService?.warn( + 'RESP_CODE_SENT: ACK hash $ackHashHex is not the hash we predicted, ' + 'adopting the radio value for "$shortText" (the radio is authoritative, ' + 'see #449)', + tag: 'AckHash', + ); + + // Drop the stale prediction so it cannot mis-match a later reply. + _expectedHashToMessageId.removeWhere((_, id) => id == messageId); + return messageId; + } + + /// [allowUnpredictedAdoption] must be false when a channel message is also + /// awaiting its RESP_CODE_SENT, because that frame could belong to either. + bool updateMessageFromSent( + int ackHash, + int timeoutMs, { + bool allowUnpredictedAdoption = true, + }) { final config = _config; if (config == null) return false; @@ -424,8 +491,15 @@ class MessageRetryService extends ChangeNotifier { } if (messageId == null || contact == null) { - debugPrint('No pending message found for ACK hash: $ackHashHex'); - return false; + final adopted = _adoptUnpredictedSentHash( + ackHashHex, + config, + allowed: allowUnpredictedAdoption, + ); + if (adopted == null) return false; + messageId = adopted; + contact = _pendingContacts[adopted]; + if (contact == null) return false; } final message = _pendingMessages[messageId]!; diff --git a/lib/services/observer_apply_service.dart b/lib/services/observer_apply_service.dart index fbf37839..74bf9434 100644 --- a/lib/services/observer_apply_service.dart +++ b/lib/services/observer_apply_service.dart @@ -38,16 +38,16 @@ class ObserverApplyService { } for (final b in writes.brokers) { - // Profiles never set broker enabled (#456), preserve the device's current - // state: read wasLive for the safe-save dance and re-enable to the same. - final current = await _svc.getBroker(b.slot); - final wasLive = current?.enabled ?? false; - + // Import NEVER touches enabled state (#470, owner directive): a config + // import carries no enabled/disabled, and the firmware already force- + // disables a slot on any field write (#53). We do not re-enable; the slot + // is left DISABLED and the operator re-enables intentionally. Prior enabled + // state is not carried over. final res = await _svc.saveBroker( b.slot, fields: b.fields, - enable: wasLive, - wasLive: wasLive, + enable: false, + wasLive: false, ); items.add( res.ok diff --git a/lib/services/radio_preset_service.dart b/lib/services/radio_preset_service.dart new file mode 100644 index 00000000..097b3e20 --- /dev/null +++ b/lib/services/radio_preset_service.dart @@ -0,0 +1,217 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart' show rootBundle; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/radio_preset.dart'; +import '../storage/prefs_manager.dart'; +import '../utils/app_logger.dart'; +import 'config_source_service.dart'; + +/// Where the preset files are published (OffbandMesh/config-profiles, #721). +const String kRadioPresetBaseUrl = + 'https://raw.githubusercontent.com/OffbandMesh/config-profiles/main/radio-presets/'; +const String kUpstreamPresetFile = 'meshcore-upstream.json'; +const String kOverlayPresetFile = 'offband.json'; + +/// The copies bundled with the app, so the picker works offline. +const String kRadioPresetAssetDir = 'assets/radio_presets/'; + +const String _prefsPrefix = 'radio_presets_v1_'; +const String _prefsRefreshedKey = '${_prefsPrefix}refreshed_at'; + +typedef PresetTextLoader = Future Function(String location); + +/// The regional radio preset list (#728): MeshCore's upstream presets plus +/// Offband's overlay, merged with the overlay winning on a matching title. +/// +/// Starts from the last good copy (or the bundled one), and refreshes from +/// config-profiles on demand. A file that fails to fetch or parse never +/// replaces a good copy; the failure is logged and kept in [refreshError] so +/// the picker can show it. +class RadioPresetService extends ChangeNotifier { + RadioPresetService({ + PresetTextLoader? fetch, + PresetTextLoader? loadAsset, + SharedPreferences? prefs, + DateTime Function()? clock, + }) : _fetch = fetch, + _loadAsset = loadAsset ?? rootBundle.loadString, + _prefsOverride = prefs, + _clock = clock ?? DateTime.now; + + final PresetTextLoader? _fetch; + final PresetTextLoader _loadAsset; + final SharedPreferences? _prefsOverride; + final DateTime Function() _clock; + ConfigSourceService? _source; + + SharedPreferences get _prefs => _prefsOverride ?? PrefsManager.instance; + + RadioPresetParseResult _upstream = const RadioPresetParseResult([], 0); + RadioPresetParseResult _overlay = const RadioPresetParseResult([], 0); + List _presets = const []; + String? _refreshError; + DateTime? _lastRefreshed; + bool _refreshing = false; + + List get presets => _presets; + + /// Entries left out of the files in use because they were malformed. + int get skipped => _upstream.skipped + _overlay.skipped; + + /// Why the last refresh (or load) failed, or null when it succeeded. + String? get refreshError => _refreshError; + DateTime? get lastRefreshed => _lastRefreshed; + bool get refreshing => _refreshing; + + /// Load the last good copy of each file, falling back to the bundled one. + Future load() async { + final errors = []; + _upstream = await _loadLocal( + kUpstreamPresetFile, + parseUpstreamPresets, + errors, + ); + _overlay = await _loadLocal( + kOverlayPresetFile, + parseOverlayPresets, + errors, + ); + final stamp = _prefs.getString(_prefsRefreshedKey); + _lastRefreshed = stamp == null ? null : DateTime.tryParse(stamp); + _refreshError = errors.isEmpty ? null : errors.join('; '); + _rebuild(); + } + + /// Refresh when the copy in use is older than [maxAge] or was never + /// refreshed. Returns whether a refresh ran and succeeded. + Future refreshIfStale({ + Duration maxAge = const Duration(hours: 12), + }) async { + final last = _lastRefreshed; + if (last != null && _clock().difference(last) < maxAge) return false; + return refresh(); + } + + /// Fetch both files from config-profiles. Each file that parses replaces + /// its copy and is saved as the new last good copy; each that fails keeps + /// the copy in use. Returns true only when both succeeded. + Future refresh() async { + if (_refreshing) return false; + _refreshing = true; + notifyListeners(); + final errors = []; + final upstream = await _fetchRemote( + kUpstreamPresetFile, + parseUpstreamPresets, + errors, + ); + final overlay = await _fetchRemote( + kOverlayPresetFile, + parseOverlayPresets, + errors, + ); + if (upstream != null) _upstream = upstream; + if (overlay != null) _overlay = overlay; + if (errors.isEmpty) { + _lastRefreshed = _clock(); + await _prefs.setString( + _prefsRefreshedKey, + _lastRefreshed!.toIso8601String(), + ); + _refreshError = null; + } else { + _refreshError = errors.join('; '); + } + _refreshing = false; + _rebuild(); + return errors.isEmpty; + } + + Future _loadLocal( + String file, + RadioPresetParseResult Function(String) parse, + List errors, + ) async { + final cached = _prefs.getString('$_prefsPrefix$file'); + if (cached != null) { + try { + return parse(cached); + } catch (e) { + appLogger.warn( + 'Saved copy of $file unusable, using the bundled one: $e', + tag: 'RadioPresets', + ); + } + } + try { + return parse(await _loadAsset('$kRadioPresetAssetDir$file')); + } catch (e) { + appLogger.error('Bundled $file failed to load: $e', tag: 'RadioPresets'); + errors.add('$file: $e'); + return const RadioPresetParseResult([], 0); + } + } + + Future _fetchRemote( + String file, + RadioPresetParseResult Function(String) parse, + List errors, + ) async { + final url = '$kRadioPresetBaseUrl$file'; + try { + final text = _fetch != null + ? await _fetch(url) + : await (_source ??= ConfigSourceService()).fetchText(url); + final parsed = parse(text); + if (parsed.presets.isEmpty) { + throw RadioPresetFormatException('$file has no usable presets'); + } + await _prefs.setString('$_prefsPrefix$file', text); + if (parsed.skipped > 0) { + appLogger.warn( + '$file: ${parsed.skipped} malformed preset(s) skipped', + tag: 'RadioPresets', + ); + } + return parsed; + } catch (e) { + appLogger.warn('Refreshing $file failed: $e', tag: 'RadioPresets'); + errors.add('$file: $e'); + return null; + } + } + + void _rebuild() { + _presets = mergeRadioPresets(_upstream.presets, _overlay.presets); + notifyListeners(); + } + + @override + void dispose() { + _source?.dispose(); + super.dispose(); + } +} + +/// Upstream presets plus the overlay. An overlay entry whose title matches an +/// upstream one (ignoring case) replaces it. Sorted by region, then title. +List mergeRadioPresets( + List upstream, + List overlay, +) { + final byTitle = { + for (final p in upstream) p.title.toLowerCase(): p, + }; + for (final p in overlay) { + byTitle[p.title.toLowerCase()] = p; + } + final merged = byTitle.values.toList() + ..sort((a, b) { + final r = a.region.toLowerCase().compareTo(b.region.toLowerCase()); + return r != 0 + ? r + : a.title.toLowerCase().compareTo(b.title.toLowerCase()); + }); + return merged; +} diff --git a/lib/services/repeater_command_service.dart b/lib/services/repeater_command_service.dart index 61d22c8e..12d4cad4 100644 --- a/lib/services/repeater_command_service.dart +++ b/lib/services/repeater_command_service.dart @@ -1,8 +1,66 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; import '../models/contact.dart'; import '../models/path_selection.dart'; import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; +import '../utils/app_logger.dart'; + +/// A repeater reply that arrived with no command waiting to receive it. +/// +/// [command] carries the original request when the reply could be traced back +/// to one that already timed out, and is null when the reply cannot be +/// attributed to anything this service sent. +class UnmatchedRepeaterResponse { + final String repeaterKeyHex; + final String response; + final String? command; + final Duration? sinceTimeout; + + const UnmatchedRepeaterResponse({ + required this.repeaterKeyHex, + required this.response, + this.command, + this.sinceTimeout, + }); + + /// True when this answers a request that timed out rather than arriving + /// unsolicited. + bool get isLateReply => command != null; +} + +/// Thrown when a CLI command's window closes with no reply. +/// +/// Carries the window that was actually armed, so callers can report the real +/// figure. The previous message printed `(timeoutMs / 1000).ceil()`, so a +/// 4074 ms window announced "timeout after 5 seconds": every window in +/// (4000, 5000] reported the same 5, and the number shown was never the number +/// used (#531). +class RepeaterCommandTimeout implements Exception { + final String command; + final int timeoutMs; + + const RepeaterCommandTimeout({ + required this.command, + required this.timeoutMs, + }); + + /// The armed window in seconds to one decimal, e.g. `28.7`. + String get secondsText => (timeoutMs / 1000).toStringAsFixed(1); + + /// Non-localized fallback for logs and for callers without a + /// [BuildContext]. UI paths should prefer [secondsText] with their own + /// localized string. + @override + String toString() => 'Command timed out after $secondsText seconds'; +} + +class _ExpiredCommand { + final String command; + final DateTime expiredAt; + + const _ExpiredCommand({required this.command, required this.expiredAt}); +} class RepeaterCommandService { final MeshCoreConnector _connector; @@ -10,10 +68,27 @@ class RepeaterCommandService { final Map _commandTimeouts = {}; final Map _commandPrefixes = {}; final Map _pendingByPrefix = {}; + final Map _expiredCommands = {}; int _prefixCounter = 0; static const int maxRetries = 5; + /// How long a timed-out command stays remembered so a reply arriving after + /// its window can still be presented with the request it answers. + static const Duration lateReplyRetention = Duration(minutes: 2); + + /// Invoked when a reply cannot be handed to a waiting command. + /// + /// Every such reply is already written to the app log by + /// [_surfaceUnmatchedResponse], which is the diagnostics channel and is what + /// keeps this from being a silent drop (#528). + /// + /// This sink exists for tests and for any future diagnostics view. **No + /// screen wires it.** Late arrivals became ordinary noise once #529 widened + /// the window, and the owner asked for them off the UI: log them, do not put + /// them in front of users (#589). + void Function(UnmatchedRepeaterResponse)? onUnmatchedResponse; + RepeaterCommandService(this._connector); /// Send a CLI command to a repeater with automatic retries @@ -27,6 +102,7 @@ class RepeaterCommandService { }) async { final attemptCount = retries < 1 ? 1 : retries; final selection = await _connector.preparePathForContactSend(repeater); + final attemptPrefixes = []; for (int attempt = 0; attempt < attemptCount; attempt++) { onAttempt?.call(attempt + 1); @@ -36,7 +112,13 @@ class RepeaterCommandService { command, selection, attempt, + attemptPrefixes, ); + // The caller has its answer, so a straggler from an earlier attempt of + // this same command is noise rather than a lost response. + for (final prefix in attemptPrefixes) { + _expiredCommands.remove(prefix); + } onResponse?.call(response); return response; } catch (e) { @@ -52,14 +134,13 @@ class RepeaterCommandService { String command, PathSelection selection, int attempt, + List attemptPrefixes, ) async { final repeaterKey = repeater.publicKeyHex; final prefix = _nextPrefixToken(); final commandId = '${repeaterKey}_$prefix'; - final completer = Completer(); - _pendingCommands[commandId] = completer; - _commandPrefixes[commandId] = prefix; - _pendingByPrefix[prefix] = commandId; + final completer = _registerPending(commandId, prefix); + attemptPrefixes.add(prefix); try { final framedCommand = '$prefix$command'; @@ -81,11 +162,10 @@ class RepeaterCommandService { final responseBytes = frame.length > maxFrameSize ? frame.length : maxFrameSize; - final timeoutMs = _connector.calculateTimeout( + final timeoutMs = _connector.calculateCliTimeout( pathLength: pathLengthValue, messageBytes: responseBytes, ); - final timeoutSeconds = (timeoutMs / 1000).ceil(); await _connector.sendFrame(frame); _commandTimeouts[commandId]?.cancel(); _commandTimeouts[commandId] = Timer( @@ -93,8 +173,19 @@ class RepeaterCommandService { () { final completer = _pendingCommands[commandId]; if (completer != null && !completer.isCompleted) { + // Prune here as well as on receive. A run of commands that all + // time out with no traffic coming back would otherwise accumulate + // records until disposal, since handleResponse is the only other + // place that prunes and it never runs (Gemini review). + _pruneExpiredCommands(); + // Remember what this prefix asked so a reply arriving after the + // window can still reach the user with its question attached. + _expiredCommands[prefix] = _ExpiredCommand( + command: command, + expiredAt: DateTime.now(), + ); completer.completeError( - 'Command timeout after $timeoutSeconds seconds', + RepeaterCommandTimeout(command: command, timeoutMs: timeoutMs), ); _cleanup(commandId); } @@ -114,29 +205,129 @@ class RepeaterCommandService { /// Call this when a text message response is received from a repeater void handleResponse(Contact repeater, String responseText) { - // Find pending command for this repeater and complete it final repeaterKey = repeater.publicKeyHex; + _pruneExpiredCommands(); - String? commandId; + String? prefix; String responsePayload = responseText; if (responseText.length >= 3 && responseText[2] == '|') { - final prefix = responseText.substring(0, 3); - commandId = _pendingByPrefix[prefix]; + prefix = responseText.substring(0, 3); responsePayload = responseText.substring(3).trimLeft(); } - commandId ??= _pendingCommands.keys.firstWhere( - (id) => id.startsWith(repeaterKey), - orElse: () => '', - ); + // A reply that carries a prefix is self-identifying. If that prefix matches + // nothing pending, the answer belongs to a command that already completed + // or expired, and forcing it onto whatever else is in flight would report + // one command's output as another command's result (#532). Only a reply + // with no prefix at all, which carries no correlation token, may fall back + // to matching by repeater. + final matchedId = prefix != null ? _pendingByPrefix[prefix] : null; + final commandId = + matchedId ?? (prefix != null ? '' : _solePendingFor(repeaterKey)); - if (commandId.isEmpty) return; + if (commandId.isNotEmpty) { + final completer = _pendingCommands[commandId]; + if (completer != null && !completer.isCompleted) { + completer.complete(responsePayload); + _cleanup(commandId); + return; + } + } - final completer = _pendingCommands[commandId]; - if (completer != null && !completer.isCompleted) { - completer.complete(responsePayload); - _cleanup(commandId); + // Nothing is waiting for this reply. It is still a real answer from the + // repeater, so it gets surfaced and logged rather than dropped (#528). + _surfaceUnmatchedResponse(repeaterKey, prefix, responsePayload); + } + + void _surfaceUnmatchedResponse( + String repeaterKey, + String? prefix, + String responsePayload, + ) { + final expired = prefix != null ? _expiredCommands.remove(prefix) : null; + final sinceTimeout = expired == null + ? null + : DateTime.now().difference(expired.expiredAt); + + if (expired != null) { + appLogger.warn( + 'Late reply to "${expired.command}" from $repeaterKey arrived ' + '${sinceTimeout!.inMilliseconds}ms after its window closed: ' + '$responsePayload', + tag: 'RepeaterCommand', + ); + } else { + appLogger.warn( + 'Reply from $repeaterKey matched no pending or recently expired ' + 'command (prefix: ${prefix ?? 'none'}): $responsePayload', + tag: 'RepeaterCommand', + ); + } + + onUnmatchedResponse?.call( + UnmatchedRepeaterResponse( + repeaterKeyHex: repeaterKey, + response: responsePayload, + command: expired?.command, + sinceTimeout: sinceTimeout, + ), + ); + } + + /// The one command awaiting a reply from [repeaterKey], or `''` when that is + /// ambiguous. + /// + /// An unprefixed reply carries no correlation token, so position is all that + /// is left to match on. Firmware only echoes the prefix when the command is + /// longer than four characters including it (`simple_repeater/MyMesh.cpp` + /// `strlen(command) > 4 && command[2] == '|'`), so a very short command can + /// legitimately answer without one and the fallback has to stay. + /// + /// It is only sound with exactly one candidate though. With two or more, + /// "first" is map-iteration order, and choosing one would hand a caller + /// another command's output. Ambiguity is surfaced instead of guessed. + String _solePendingFor(String repeaterKey) { + String? only; + for (final id in _pendingCommands.keys) { + if (!id.startsWith(repeaterKey)) continue; + if (only != null) return ''; + only = id; } + return only ?? ''; + } + + Completer _registerPending(String commandId, String prefix) { + final completer = Completer(); + _pendingCommands[commandId] = completer; + _commandPrefixes[commandId] = prefix; + _pendingByPrefix[prefix] = commandId; + return completer; + } + + /// Puts a command in flight without performing the send, so a test can set up + /// two concurrent commands to one repeater. Deliberately routes through the + /// same [_registerPending] the real send path uses, so the two cannot drift. + @visibleForTesting + Future registerPendingForTest(String repeaterKeyHex, String prefix) => + _registerPending('${repeaterKeyHex}_$prefix', prefix).future; + + /// Records a timed-out command so a reply arriving later can still be + /// attributed to it. Exposed because a test cannot drive a real + /// send-then-time-out cycle without a connected transport. + @visibleForTesting + void recordExpiredCommandForTest(String prefix, String command) { + _expiredCommands[prefix] = _ExpiredCommand( + command: command, + expiredAt: DateTime.now(), + ); + } + + void _pruneExpiredCommands() { + if (_expiredCommands.isEmpty) return; + final cutoff = DateTime.now().subtract(lateReplyRetention); + _expiredCommands.removeWhere( + (_, entry) => entry.expiredAt.isBefore(cutoff), + ); } void _cleanup(String commandId) { @@ -157,6 +348,8 @@ class RepeaterCommandService { _pendingCommands.clear(); _commandPrefixes.clear(); _pendingByPrefix.clear(); + _expiredCommands.clear(); + onUnmatchedResponse = null; } String _nextPrefixToken() { diff --git a/lib/services/stock_config_export_service.dart b/lib/services/stock_config_export_service.dart new file mode 100644 index 00000000..a968accc --- /dev/null +++ b/lib/services/stock_config_export_service.dart @@ -0,0 +1,260 @@ +/// Builds a stock-compatible config export from the connected device (#573, +/// epic #568). +/// +/// The wire format lives in `models/stock_config.dart`; this service is only +/// concerned with reading live state and mapping it across. Section selection +/// mirrors stock's Export Config screen, where every section is individually +/// checkable and the file simply omits what was not selected. +library; + +import 'dart:typed_data'; + +import '../connector/meshcore_connector.dart'; +import '../models/channel.dart'; +import '../models/contact.dart'; +import '../models/stock_config.dart'; + +/// One checkbox on the export screen. [identity] covers the public and private +/// key together, matching stock's single "Private Identity Key" control. +enum StockConfigSection { + name, + identity, + radioSettings, + positionSettings, + otherSettings, + autoAddSettings, + channels, + contacts, +} + +/// Why a requested section did not make it into the file. +enum StockConfigOmission { + /// The device is not connected, or did not answer in time. + noReply, + + /// The radio's firmware was built without the feature. Retrying is pointless. + unsupported, + + /// The device refused the request. + rejected, + + /// The device has not reported this value, so there is nothing to write. + unavailable, +} + +/// The outcome of an export attempt. +/// +/// [omitted] is the important half: a section the user ticked that could not be +/// gathered must be reported, never dropped quietly. The export screen shows +/// these before writing the file. +class StockConfigExportResult { + const StockConfigExportResult({ + required this.config, + required this.included, + required this.omitted, + }); + + final StockConfig config; + final Set included; + final Map omitted; + + bool get isComplete => omitted.isEmpty; +} + +class StockConfigExportService { + StockConfigExportService(this._connector); + + final MeshCoreConnector _connector; + + /// Gathers [sections] from the connected device. + /// + /// Reading the identity is the only step that talks to the radio; everything + /// else is already in connector state from the SELF_INFO handshake and the + /// contact and channel syncs. + Future build({ + required Set sections, + }) async { + final included = {}; + final omitted = {}; + + void include(StockConfigSection section) => included.add(section); + void omit(StockConfigSection section, StockConfigOmission why) => + omitted[section] = why; + + String? name; + if (sections.contains(StockConfigSection.name)) { + name = _connector.selfName; + if (name == null) { + omit(StockConfigSection.name, StockConfigOmission.unavailable); + } else { + include(StockConfigSection.name); + } + } + + Uint8List? publicKey; + Uint8List? privateKey; + if (sections.contains(StockConfigSection.identity)) { + final result = await _connector.exportPrivateKey(); + switch (result.outcome) { + case IdentityTransfer.ok: + // The keys travel as a pair, so a missing public key means we write + // neither rather than half an identity. + final self = _connector.selfPublicKey; + if (self == null) { + omit(StockConfigSection.identity, StockConfigOmission.unavailable); + } else { + publicKey = self; + privateKey = result.identity; + include(StockConfigSection.identity); + } + case IdentityTransfer.unsupported: + omit(StockConfigSection.identity, StockConfigOmission.unsupported); + case IdentityTransfer.rejected: + omit(StockConfigSection.identity, StockConfigOmission.rejected); + case IdentityTransfer.noReply: + omit(StockConfigSection.identity, StockConfigOmission.noReply); + } + } + + StockRadioSettings? radio; + if (sections.contains(StockConfigSection.radioSettings)) { + radio = _buildRadioSettings(); + if (radio == null) { + omit(StockConfigSection.radioSettings, StockConfigOmission.unavailable); + } else { + include(StockConfigSection.radioSettings); + } + } + + StockPositionSettings? position; + if (sections.contains(StockConfigSection.positionSettings)) { + position = StockPositionSettings( + latitude: _connector.selfLatitude ?? 0, + longitude: _connector.selfLongitude ?? 0, + ); + include(StockConfigSection.positionSettings); + } + + StockOtherSettings? other; + if (sections.contains(StockConfigSection.otherSettings)) { + other = StockOtherSettings( + // The raw device byte, not the connector's inverted convenience flag. + manualAddContacts: _connector.manualAddContactsRaw, + advertLocationPolicy: _connector.advertLocationPolicy, + ); + include(StockConfigSection.otherSettings); + } + + StockAutoAddSettings? autoAdd; + if (sections.contains(StockConfigSection.autoAddSettings)) { + autoAdd = StockAutoAddSettings( + autoAddChat: _connector.autoAddUsers ?? false, + autoAddRepeater: _connector.autoAddRepeaters ?? false, + autoAddRoomServer: _connector.autoAddRoomServers ?? false, + autoAddSensor: _connector.autoAddSensors ?? false, + overwriteOldest: _connector.autoAddOverwriteOldest ?? false, + autoAddMaxHops: _connector.autoAddMaxHops, + ); + include(StockConfigSection.autoAddSettings); + } + + List? channels; + if (sections.contains(StockConfigSection.channels)) { + channels = [ + for (final channel in _connector.channels) + if (!channel.isEmpty) toStockChannel(channel), + ]; + include(StockConfigSection.channels); + } + + List? contacts; + if (sections.contains(StockConfigSection.contacts)) { + contacts = [ + for (final contact in _connector.contacts) toStockContact(contact), + ]; + include(StockConfigSection.contacts); + } + + return StockConfigExportResult( + config: StockConfig( + name: name, + publicKey: publicKey, + privateKey: privateKey, + radioSettings: radio, + positionSettings: position, + otherSettings: other, + autoAddSettings: autoAdd, + channels: channels, + contacts: contacts, + ), + included: included, + omitted: omitted, + ); + } + + /// Null until the device has reported its radio parameters. Partial radio + /// state is never written: stock's reader takes the five values together. + StockRadioSettings? _buildRadioSettings() { + // `currentFreqHz` is misnamed: the value is kHz, which is what stock's + // `frequency` field also carries, so it passes through unconverted. + // `currentBwHz` really is Hz, matching stock's `bandwidth`. The units + // differ between the two fields in both our state and the file. + final frequencyKhz = _connector.currentFreqHz; + final bandwidthHz = _connector.currentBwHz; + final sf = _connector.currentSf; + final cr = _connector.currentCr; + final txPower = _connector.currentTxPower; + if (frequencyKhz == null || + bandwidthHz == null || + sf == null || + cr == null || + txPower == null) { + return null; + } + return StockRadioSettings( + frequencyKhz: frequencyKhz, + bandwidthHz: bandwidthHz, + spreadingFactor: sf, + codingRate: cr, + txPower: txPower, + ); + } +} + +/// Maps one of our channels onto the stock record. The channel's index is not +/// written: stock derives it from array position. +StockChannel toStockChannel(Channel channel) => + StockChannel(name: channel.name, secret: channel.psk); + +/// Maps one of our contacts onto the stock record. +StockContact toStockContact(Contact contact) { + return StockContact( + type: contact.type, + name: contact.name, + publicKey: contact.publicKey, + flags: contact.flags, + latitude: contact.latitude ?? 0, + longitude: contact.longitude ?? 0, + lastAdvert: _epochSeconds(contact.lastSeen), + lastModified: _epochSeconds(contact.lastModified ?? contact.lastSeen), + outPath: _toStockOutPath(contact), + ); +} + +/// Our path is a hash count plus a per-hop width (#309); stock writes one +/// comma-separated hash per hop, so the width survives as each element's +/// length. A flood route (`pathLength` of -1) and an empty path both mean +/// "no route", which stock spells as a null field. +StockOutPath? _toStockOutPath(Contact contact) { + if (contact.pathLength <= 0 || contact.path.isEmpty) return null; + final width = contact.pathHashWidth; + if (!kStockPathHashWidths.contains(width)) return null; + final usable = contact.pathLength * width; + if (usable > contact.path.length) return null; + return StockOutPath( + hashWidth: width, + bytes: Uint8List.sublistView(contact.path, 0, usable), + ); +} + +int _epochSeconds(DateTime time) => time.millisecondsSinceEpoch ~/ 1000; diff --git a/lib/services/stock_config_import_service.dart b/lib/services/stock_config_import_service.dart new file mode 100644 index 00000000..39f574ed --- /dev/null +++ b/lib/services/stock_config_import_service.dart @@ -0,0 +1,396 @@ +/// Applies a stock-compatible config file to the connected device (#575, +/// epic #568). +/// +/// Merge semantics deliberately match the stock app, which states them on its +/// own Import Config screen: +/// +/// * **Contacts**: "New contacts will be added. Existing contacts will be +/// updated." An upsert keyed on public key. Nothing is ever deleted. +/// * **Channels**: "New channels will be added. Existing channels will not +/// change." Purely additive, so a rotated PSK for a channel the user already +/// has does not apply. +/// * **Identity**: "Importing this private key will overwrite your current +/// identity." Destructive, and the caller must have confirmed with the user. +/// +/// We match that behavior but not stock's silence about it: anything skipped +/// comes back in [StockConfigImportResult] so the UI can name it. A channel +/// that quietly failed to import is exactly the kind of silent no-op SAFELANE +/// section 6 forbids. +library; + +import 'dart:typed_data'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../models/channel.dart'; +import '../models/stock_config.dart'; +import 'stock_config_export_service.dart' show StockConfigSection; + +/// Why a section or a single channel was not applied. +enum StockConfigImportIssue { + /// The file did not contain this section. + absentFromFile, + + /// The device is not connected, or did not answer. + noReply, + + /// The radio's firmware was built without the feature. + unsupported, + + /// The device refused the request. + rejected, + + /// The device already has this channel, and stock's rule is that existing + /// channels are never overwritten. + alreadyPresent, + + /// Every channel slot on the device is occupied. + noFreeSlot, + + /// We have no supported way to write this value to the device. + notWritable, +} + +/// A channel present in the file that did not land on the device. +class SkippedChannel { + const SkippedChannel(this.name, this.reason); + + final String name; + final StockConfigImportIssue reason; +} + +class StockConfigImportResult { + const StockConfigImportResult({ + required this.applied, + required this.failed, + required this.skippedChannels, + required this.contactsWritten, + required this.channelsAdded, + }); + + /// Sections whose commands were **sent** to the device without error. + /// + /// This is not device confirmation. Apart from the identity import, which + /// waits for a real OK or ERR, the firmware's generic OK for these commands + /// is not currently awaited, so a frame lost or refused after it left our + /// side would still land here. Wiring per-command confirmation is tracked + /// separately; until then this set means "sent", and the UI says so rather + /// than claiming more than we know. + final Set applied; + + final Map failed; + + /// Channels in the file that were not written, each with a reason. Shown to + /// the user; never discarded. + final List skippedChannels; + + /// Contacts whose write command was sent. See [applied] for why this is a + /// send count and not a confirmed count. + final int contactsWritten; + + /// Channels whose write command was sent. Same caveat as [contactsWritten]. + final int channelsAdded; + + bool get isComplete => failed.isEmpty && skippedChannels.isEmpty; +} + +class StockConfigImportService { + StockConfigImportService(this._connector); + + final MeshCoreConnector _connector; + + /// Applies the selected [sections] of [config] to the device. + /// + /// [StockConfigSection.identity] is destructive and is only applied when the + /// caller includes it; confirming that with the user is the UI's job. + Future apply({ + required StockConfig config, + required Set sections, + }) async { + final applied = {}; + final failed = {}; + final skippedChannels = []; + var contactsWritten = 0; + var channelsAdded = 0; + + if (!_connector.isConnected) { + return StockConfigImportResult( + applied: const {}, + failed: {for (final s in sections) s: StockConfigImportIssue.noReply}, + skippedChannels: const [], + contactsWritten: 0, + channelsAdded: 0, + ); + } + + if (sections.contains(StockConfigSection.name)) { + final name = config.name; + if (name == null) { + failed[StockConfigSection.name] = StockConfigImportIssue.absentFromFile; + } else { + await _connector.setNodeName(name); + applied.add(StockConfigSection.name); + } + } + + if (sections.contains(StockConfigSection.identity)) { + final identity = config.privateKey; + if (identity == null) { + failed[StockConfigSection.identity] = + StockConfigImportIssue.absentFromFile; + } else { + // Destructive: replaces the node's identity outright. + switch (await _connector.importPrivateKey(identity)) { + case IdentityTransfer.ok: + applied.add(StockConfigSection.identity); + case IdentityTransfer.unsupported: + failed[StockConfigSection.identity] = + StockConfigImportIssue.unsupported; + case IdentityTransfer.rejected: + failed[StockConfigSection.identity] = + StockConfigImportIssue.rejected; + case IdentityTransfer.noReply: + failed[StockConfigSection.identity] = + StockConfigImportIssue.noReply; + } + } + } + + if (sections.contains(StockConfigSection.radioSettings)) { + final radio = config.radioSettings; + if (radio == null) { + failed[StockConfigSection.radioSettings] = + StockConfigImportIssue.absentFromFile; + } else { + // The device takes frequency in the same kHz unit the file uses, so + // this is a straight pass-through. See the note in the export service. + await _connector.sendFrame( + buildSetRadioParamsFrame( + radio.frequencyKhz, + radio.bandwidthHz, + radio.spreadingFactor, + radio.codingRate, + ), + ); + applied.add(StockConfigSection.radioSettings); + } + } + + if (sections.contains(StockConfigSection.positionSettings)) { + final position = config.positionSettings; + if (position == null) { + failed[StockConfigSection.positionSettings] = + StockConfigImportIssue.absentFromFile; + } else { + await _connector.setNodeLocation( + lat: position.latitude, + lon: position.longitude, + ); + applied.add(StockConfigSection.positionSettings); + } + } + + if (sections.contains(StockConfigSection.otherSettings)) { + final other = config.otherSettings; + if (other == null) { + failed[StockConfigSection.otherSettings] = + StockConfigImportIssue.absentFromFile; + } else { + // buildSetOtherParamsFrame deliberately pins the auto-add-contacts + // byte to disabled, so `manual_add_contacts` from the file cannot be + // written without changing app-wide behavior. Only the advert location + // policy is applied, and the section is reported as partially written + // rather than claimed as done. + await _connector.sendFrame( + buildSetOtherParamsFrame( + (_connector.telemetryModeEnv << 4) | + (_connector.telemetryModeLoc << 2) | + _connector.telemetryModeBase, + other.advertLocationPolicy, + _connector.multiAcks, + ), + ); + failed[StockConfigSection.otherSettings] = + StockConfigImportIssue.notWritable; + } + } + + if (sections.contains(StockConfigSection.autoAddSettings)) { + final autoAdd = config.autoAddSettings; + if (autoAdd == null) { + failed[StockConfigSection.autoAddSettings] = + StockConfigImportIssue.absentFromFile; + } else { + await _connector.sendFrame( + buildSetAutoAddConfigFrame( + autoAddChat: autoAdd.autoAddChat, + autoAddRepeater: autoAdd.autoAddRepeater, + autoAddRoomServer: autoAdd.autoAddRoomServer, + autoAddSensor: autoAdd.autoAddSensor, + overwriteOldest: autoAdd.overwriteOldest, + maxHops: autoAdd.autoAddMaxHops, + ), + ); + applied.add(StockConfigSection.autoAddSettings); + } + } + + if (sections.contains(StockConfigSection.channels)) { + final channels = config.channels; + if (channels == null) { + failed[StockConfigSection.channels] = + StockConfigImportIssue.absentFromFile; + } else { + channelsAdded = await _applyChannels(channels, skippedChannels); + applied.add(StockConfigSection.channels); + } + } + + if (sections.contains(StockConfigSection.contacts)) { + final contacts = config.contacts; + if (contacts == null) { + failed[StockConfigSection.contacts] = + StockConfigImportIssue.absentFromFile; + } else { + contactsWritten = await _applyContacts(contacts); + applied.add(StockConfigSection.contacts); + } + } + + return StockConfigImportResult( + applied: applied, + failed: failed, + skippedChannels: skippedChannels, + contactsWritten: contactsWritten, + channelsAdded: channelsAdded, + ); + } + + Future _applyChannels( + List incoming, + List skipped, + ) async { + final plan = planChannelImport( + existing: _connector.channels, + incoming: incoming, + maxChannels: _connector.maxChannels, + ); + for (final assignment in plan.assignments) { + await _connector.setChannel( + assignment.slot, + assignment.channel.name, + assignment.channel.secret, + ); + } + skipped.addAll(plan.skipped); + return plan.assignments.length; + } + + /// Upserts every contact. The firmware's add-or-update command keys on the + /// public key, so an existing contact is updated in place and a new one is + /// created. Nothing is removed, in either direction. + Future _applyContacts(List contacts) async { + var written = 0; + for (final contact in contacts) { + final path = contact.outPath; + // Position is always passed through, including (0, 0). Suppressing zero + // would be pointless here: the frame builder emits the position block + // whenever lastModified is present, which it always is below, so a + // suppressed position writes 0/0 anyway. Passing it straight through + // means the file's value is what lands, with no special case to + // misread. + await _connector.sendFrame( + buildUpdateContactPathFrame( + contact.publicKey, + path?.bytes ?? _emptyPath, + // No path in the file means flood, which the frame encodes as -1. + path == null || path.hopCount == 0 ? -1 : path.hopCount, + hashWidth: path == null || path.hashWidth == 0 ? 1 : path.hashWidth, + type: contact.type, + flags: contact.flags, + name: contact.name, + lat: contact.latitude, + lon: contact.longitude, + lastModified: DateTime.fromMillisecondsSinceEpoch( + contact.lastModified * 1000, + ), + ), + ); + written++; + } + return written; + } +} + +/// A zero-length path, which the frame builder pads out to the fixed-size +/// path field. +final Uint8List _emptyPath = Uint8List(0); + +/// One incoming channel and the device slot it will occupy. +class ChannelAssignment { + const ChannelAssignment(this.slot, this.channel); + + final int slot; + final StockChannel channel; +} + +/// The decision of which incoming channels get written, and where. +class ChannelImportPlan { + const ChannelImportPlan(this.assignments, this.skipped); + + final List assignments; + final List skipped; +} + +/// Decides which of [incoming] to write, honoring stock's additive rule. +/// +/// A channel counts as already present when either its PSK or its name matches +/// one already on the device. Stock says only that existing channels do not +/// change, without defining what makes a channel "existing"; matching on both +/// is the non-destructive reading, and pinning down what stock actually does is +/// one of the T1 gate's questions. +/// +/// New channels go into the lowest free slot. Stock's file has no index field, +/// so incoming order is the only ordering information there is, and slots +/// already occupied are left alone. +ChannelImportPlan planChannelImport({ + required List existing, + required List incoming, + required int maxChannels, +}) { + final live = existing.where((c) => !c.isEmpty).toList(); + final takenSlots = live.map((c) => c.index).toSet(); + final psks = live.map((c) => c.pskHex).toSet(); + final names = live.map((c) => c.name).toSet(); + + final assignments = []; + final skipped = []; + + for (final channel in incoming) { + final pskHex = pubKeyToHex(channel.secret); + if (psks.contains(pskHex) || names.contains(channel.name)) { + skipped.add( + SkippedChannel(channel.name, StockConfigImportIssue.alreadyPresent), + ); + continue; + } + int? slot; + for (var i = 0; i < maxChannels; i++) { + if (!takenSlots.contains(i)) { + slot = i; + break; + } + } + if (slot == null) { + skipped.add( + SkippedChannel(channel.name, StockConfigImportIssue.noFreeSlot), + ); + continue; + } + assignments.add(ChannelAssignment(slot, channel)); + takenSlots.add(slot); + psks.add(pskHex); + names.add(channel.name); + } + return ChannelImportPlan(assignments, skipped); +} diff --git a/lib/services/tcp_transport_service_native.dart b/lib/services/tcp_transport_service_native.dart index a6db99b5..a6911f1d 100644 --- a/lib/services/tcp_transport_service_native.dart +++ b/lib/services/tcp_transport_service_native.dart @@ -167,6 +167,10 @@ class TcpTransportService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + _debugLogService?.error('TCP ${skipped.describe()}', tag: 'TCP'); + } } void _handleSocketError(Object error, [StackTrace? stackTrace]) { diff --git a/lib/services/usb_serial_frame_codec.dart b/lib/services/usb_serial_frame_codec.dart index 0b7b39a7..4a936ec6 100644 --- a/lib/services/usb_serial_frame_codec.dart +++ b/lib/services/usb_serial_frame_codec.dart @@ -37,13 +37,58 @@ class UsbSerialDecodedPacket { bool get isRxFrame => frameStart == usbSerialRxFrameStart; } +/// Bytes the decoder could not frame and discarded (#711). Lost bytes mean +/// lost frames, so callers log this as an error rather than drop it quietly. +class UsbSerialSkipReport { + const UsbSerialSkipReport({required this.count, required this.sample}); + + final int count; + + /// The first discarded bytes, for the log. + final List sample; + + String describe() { + final hex = sample + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(' '); + return 'discarded $count byte(s) that could not be framed ' + '(first: $hex${count > sample.length ? ' ...' : ''})'; + } +} + class UsbSerialFrameDecoder { + static const int _skipSampleLength = 16; + final List _rxBuffer = []; int _startIndex = 0; + int _skipped = 0; + final List _skipSample = []; void reset() { _rxBuffer.clear(); _startIndex = 0; + _skipped = 0; + _skipSample.clear(); + } + + /// Returns what was discarded since the last call, or null if nothing was. + UsbSerialSkipReport? takeSkipReport() { + if (_skipped == 0) return null; + final report = UsbSerialSkipReport( + count: _skipped, + sample: List.unmodifiable(_skipSample), + ); + _skipped = 0; + _skipSample.clear(); + return report; + } + + void _skipByte() { + _skipped++; + if (_skipSample.length < _skipSampleLength) { + _skipSample.add(_rxBuffer[_startIndex]); + } + _startIndex++; } List ingest(Uint8List bytes) { @@ -63,7 +108,7 @@ class UsbSerialFrameDecoder { if (_rxBuffer[_startIndex] != usbSerialRxFrameStart && _rxBuffer[_startIndex] != usbSerialTxFrameStart) { - _startIndex++; + _skipByte(); _compactBufferIfNeeded(); continue; } @@ -77,7 +122,7 @@ class UsbSerialFrameDecoder { final payloadLength = _rxBuffer[_startIndex + 1] | (_rxBuffer[_startIndex + 2] << 8); if (payloadLength > usbSerialMaxPayloadLength) { - _startIndex++; + _skipByte(); _compactBufferIfNeeded(); continue; } diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 44059199..fcb01aa0 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -421,10 +421,16 @@ class UsbSerialService { unawaited(disconnect().whenComplete(_closeFrameController)); } + // One readList() returns at most 8 KB, so a single read per callback left + // the rest of a burst waiting in the native ring (#702, #711). Drain it, + // bounded to the ring's 256 KB so a stuck read can never spin forever. + static const int _maxReadsPerCallback = 32; + void _handleSerialData(FlSerialEventArgs event) { try { - final bytes = event.serial.readList(); - if (bytes.isNotEmpty) { + for (var i = 0; i < _maxReadsPerCallback; i++) { + final bytes = event.serial.readList(); + if (bytes.isEmpty) break; _ingestRawBytes(Uint8List.fromList(bytes)); } } catch (error, stack) { @@ -465,6 +471,12 @@ class UsbSerialService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + final message = 'USB serial ${skipped.describe()}'; + debugPrint(message); + _debugLogService?.error(message, tag: 'USB Serial'); + } } void _addFrame(Uint8List payload) { diff --git a/lib/services/usb_serial_service_web.dart b/lib/services/usb_serial_service_web.dart index 5261308d..f476f228 100644 --- a/lib/services/usb_serial_service_web.dart +++ b/lib/services/usb_serial_service_web.dart @@ -546,6 +546,12 @@ class UsbSerialService { } _addFrame(packet.payload); } + final skipped = _frameDecoder.takeSkipReport(); + if (skipped != null) { + final message = 'USB serial ${skipped.describe()}'; + debugPrint(message); + _debugLogService?.error(message, tag: 'USB Serial'); + } } void _addFrame(Uint8List payload) { diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index d907752b..9a647864 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -1,5 +1,6 @@ import 'dart:convert'; -import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; import '../models/contact.dart'; import '../utils/app_logger.dart'; @@ -15,6 +16,13 @@ class ContactStore { String get keyFor => '$_keyPrefix$publicKeyHex'; + // Set when the stored list for that key could not be decoded. A save there + // is refused until a load succeeds, so a partial in-memory list can never + // replace contacts the app merely failed to read (#660, #673). + String? _unreadableKey; + + bool get lastLoadFailed => _unreadableKey == keyFor; + Future> loadContacts() async { if (publicKeyHex.isEmpty) { appLogger.warn('Public key hex is not set. Cannot load contacts.'); @@ -47,10 +55,31 @@ class ContactStore { try { final jsonList = jsonDecode(jsonString) as List; - return jsonList + final contacts = jsonList .map((entry) => _fromJson(entry as Map)) .toList(); - } catch (_) { + if (_unreadableKey == keyFor) _unreadableKey = null; + return contacts; + } catch (e) { + // SAFELANE 6: a decode failure is not "no contacts". Keep the raw value + // somewhere a later save cannot touch, then refuse saves to this key. + final key = keyFor; + final aside = + '$key.unreadable-${DateTime.now().toUtc().millisecondsSinceEpoch}'; + _unreadableKey = key; + final message = + 'Could not read saved contacts for $key: $e. Raw data kept under ' + '$aside; saving contacts for this radio is disabled until they load.'; + debugPrint(message); + appLogger.error(message, tag: 'Storage'); + try { + await blobs.write(aside, jsonString); + } catch (writeError) { + appLogger.error( + 'Could not keep unreadable contacts aside under $aside: $writeError', + tag: 'Storage', + ); + } return []; } } @@ -60,6 +89,14 @@ class ContactStore { appLogger.warn('Public key hex is not set. Cannot save contacts.'); return; } + if (lastLoadFailed) { + final message = + 'Refusing to save ${contacts.length} contact(s) over $keyFor: the ' + 'stored list could not be read, so a save could replace it.'; + debugPrint(message); + appLogger.error(message, tag: 'Storage'); + return; + } final jsonList = contacts.map(_toJson).toList(); await BlobStore.instance.write(keyFor, jsonEncode(jsonList)); } diff --git a/lib/utils/log_export.dart b/lib/utils/log_export.dart index 271da1ff..2532cf4e 100644 --- a/lib/utils/log_export.dart +++ b/lib/utils/log_export.dart @@ -43,6 +43,11 @@ class LogExport { : context.l10n.debugLog_saveLog; } + /// Short verb for a compound button label like "Download & save". Mobile + /// shares via the OS sheet; desktop and web save a file (web via a browser + /// download), so "save" fits both. (#580) + static String get actionVerb => (!kIsWeb && _isMobile) ? 'share' : 'save'; + /// Export the combined on-disk app+BLE log (the App/BLE log screens). On web /// there is no on-disk file, so [webContent] supplies the text to download. static Future shareLogs( diff --git a/lib/utils/stock_config_file.dart b/lib/utils/stock_config_file.dart new file mode 100644 index 00000000..b21d8878 --- /dev/null +++ b/lib/utils/stock_config_file.dart @@ -0,0 +1,70 @@ +/// Naming and writing of stock-compatible config files (#574, epic #568). +library; + +import 'dart:io' show File; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'log_export.dart'; +import 'log_web_download.dart'; + +/// Characters Windows forbids in a file name, plus the path separators. +final _illegalFileNameChars = RegExp(r'[<>:"/\\|?*\x00-\x1F]'); + +/// Builds the file name stock uses: `_meshcore_config_`. +/// +/// Real device names contain emoji and, in at least one observed case, a +/// trailing space, so the name is sanitized for the filesystem here. The name +/// written *inside* the file is never touched: it must round-trip exactly. +String stockConfigFileName(String? deviceName, DateTime at) { + final safeName = _sanitizeForFileName(deviceName ?? ''); + final stamp = [ + at.year.toString().padLeft(4, '0'), + at.month.toString().padLeft(2, '0'), + at.day.toString().padLeft(2, '0'), + ].join('-'); + final time = [ + at.hour.toString().padLeft(2, '0'), + at.minute.toString().padLeft(2, '0'), + at.second.toString().padLeft(2, '0'), + ].join(); + final prefix = safeName.isEmpty ? '' : '${safeName}_'; + return '${prefix}meshcore_config_$stamp-$time.json'; +} + +String _sanitizeForFileName(String name) { + final cleaned = name.replaceAll(_illegalFileNameChars, ''); + // Windows also rejects names ending in a space or a dot. + return cleaned.replaceAll(RegExp(r'[ .]+$'), '').trim(); +} + +/// Writes [json] out as [fileName], using each platform's normal mechanism: +/// the share sheet on mobile, a Save As dialog on desktop, a browser download +/// on web. Reuses [LogExport], which already owns that per-platform logic, so +/// there is only one place where export behavior can drift. +Future saveStockConfigFile( + BuildContext context, { + required String json, + required String fileName, + String? subject, +}) async { + if (kIsWeb) { + downloadTextFile(fileName, json); + return; + } + // A temp file is the handoff format LogExport works in. It holds the node's + // private key when the identity section was included, so it is written under + // the app's own temp directory and never anywhere shared. + final dir = await getTemporaryDirectory(); + final file = File('${dir.path}/$fileName'); + await file.writeAsString(json, flush: true); + if (!context.mounted) return; + await LogExport.shareFile( + context, + file, + subject: subject, + fileName: fileName, + ); +} diff --git a/lib/widgets/add_contact_by_key_dialog.dart b/lib/widgets/add_contact_by_key_dialog.dart new file mode 100644 index 00000000..7ec374fb --- /dev/null +++ b/lib/widgets/add_contact_by_key_dialog.dart @@ -0,0 +1,261 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../l10n/l10n.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../models/contact.dart'; +import '../screens/contact_qr_scanner_screen.dart'; + +/// Adds a contact from an identity alone: a public key, a name and a type. +/// +/// This is the manual half of the identity exchange (#628). It exists because +/// a public key is never present in channel traffic, so for anyone who has not +/// recently adverted there is otherwise no way to reach them at all (#620). +/// +/// The field also accepts a whole `meshcore://contact/add` link, since that is +/// what someone is most likely to paste, and a QR is only that same link +/// rendered visually. +/// [initialKeyText] seeds the key field, so a scan taken from somewhere else +/// can open this already filled in rather than making the user paste. (#629) +Future showAddContactByKeyDialog( + BuildContext context, { + String? initialKeyText, +}) { + return showDialog( + context: context, + builder: (_) => _AddContactByKeyDialog(initialKeyText: initialKeyText), + ); +} + +class _AddContactByKeyDialog extends StatefulWidget { + const _AddContactByKeyDialog({this.initialKeyText}); + + final String? initialKeyText; + + @override + State<_AddContactByKeyDialog> createState() => _AddContactByKeyDialogState(); +} + +class _AddContactByKeyDialogState extends State<_AddContactByKeyDialog> { + final _keyController = TextEditingController(); + final _nameController = TextEditingController(); + int _type = advTypeChat; + String? _keyError; + bool _submitting = false; + + @override + void initState() { + super.initState(); + final seed = widget.initialKeyText; + if (seed != null && seed.isNotEmpty) { + _keyController.text = seed; + // Route the seed through the same handler as a paste, so a full link + // populates name and type instead of sitting there as raw text. + _onKeyChanged(seed); + } + } + + @override + void dispose() { + _keyController.dispose(); + _nameController.dispose(); + super.dispose(); + } + + /// Strips whitespace so a key copied across a line break still works. + String get _cleanedKey => + _keyController.text.replaceAll(RegExp(r'\s+'), '').toLowerCase(); + + bool get _keyLooksValid => Contact.isValidShareUri( + Contact.buildShareUri(publicKeyHex: _cleanedKey, name: 'x', type: _type), + ); + + /// If a full contact link OR a channel contact card was pasted, absorb every + /// field from it rather than making the user retype a name they already have. + /// + /// Both formats are accepted because both are real and a user will meet both: + /// the `meshcore://` link comes from a QR or a DM, and the compact + /// `` card is what appears in channel traffic, including the + /// cards this app itself posts. Accepting only the link would mean rejecting + /// our own output. + void _onKeyChanged(String raw) { + final pasted = Contact.fromShareUri(raw) ?? Contact.fromChannelShare(raw); + if (pasted != null) { + setState(() { + _keyController.value = TextEditingValue( + text: pasted.publicKeyHex, + selection: TextSelection.collapsed( + offset: pasted.publicKeyHex.length, + ), + ); + if (pasted.name != 'Unknown') _nameController.text = pasted.name; + _type = pasted.type; + _keyError = null; + }); + return; + } + if (_keyError != null) setState(() => _keyError = null); + } + + Future _scan() async { + final scanned = await Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const ContactQrScannerScreen()), + ); + if (!mounted || scanned == null) return; + // Route the scan through the same handler as a paste. A QR is only the + // link rendered visually, so it must not get its own code path. + _keyController.text = scanned; + _onKeyChanged(scanned); + } + + Future _submit() async { + final l10n = context.l10n; + if (!_keyLooksValid) { + setState(() => _keyError = l10n.contacts_publicKeyInvalid); + return; + } + + final name = _nameController.text.trim(); + // Round-trip through the share URI so a manually typed contact and a + // scanned QR produce byte-identical state. One code path, no drift. + final stub = Contact.fromShareUri( + Contact.buildShareUri(publicKeyHex: _cleanedKey, name: name, type: _type), + ); + if (stub == null) { + setState(() => _keyError = l10n.contacts_publicKeyInvalid); + return; + } + + setState(() => _submitting = true); + final connector = Provider.of(context, listen: false); + final added = await connector.addContactByKey(stub); + if (!mounted) return; + + Navigator.of(context).pop(); + showDismissibleSnackBar( + context, + content: Text( + added + ? l10n.contacts_addByKeyAdded(stub.name) + : l10n.contacts_addByKeyFailed, + ), + ); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + + return AlertDialog( + title: Text(l10n.contacts_addByKey), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.contacts_addByKeyDescription, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 16), + TextField( + controller: _keyController, + autofocus: true, + maxLines: 2, + minLines: 1, + decoration: InputDecoration( + labelText: l10n.contacts_publicKeyLabel, + helperText: l10n.contacts_publicKeyHelper, + helperMaxLines: 2, + errorText: _keyError, + errorMaxLines: 2, + border: const OutlineInputBorder(), + suffixIcon: contactQrScanAvailable + ? IconButton( + icon: const Icon(Icons.qr_code_scanner), + tooltip: l10n.contacts_scanContactQr, + onPressed: _submitting ? null : _scan, + ) + : null, + ), + onChanged: _onKeyChanged, + ), + const SizedBox(height: 16), + TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.contacts_nameLabel, + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: 16), + DropdownButtonFormField( + initialValue: _type, + decoration: InputDecoration( + labelText: l10n.contacts_typeLabel, + border: const OutlineInputBorder(), + ), + items: [ + DropdownMenuItem( + value: advTypeChat, + child: Text(l10n.contact_typeChat), + ), + DropdownMenuItem( + value: advTypeRepeater, + child: Text(l10n.contact_typeRepeater), + ), + DropdownMenuItem( + value: advTypeRoom, + child: Text(l10n.contact_typeRoom), + ), + DropdownMenuItem( + value: advTypeSensor, + child: Text(l10n.contact_typeSensor), + ), + ], + onChanged: (v) => setState(() => _type = v ?? advTypeChat), + ), + const SizedBox(height: 16), + // Honest about what a key-only add actually gives you. Deliberately + // informational, not a warning: nothing is wrong with this contact + // (#630). + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.info_outline, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + l10n.contacts_addByKeyUnverifiedNote, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: _submitting ? null : () => Navigator.of(context).pop(), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: _submitting ? null : _submit, + child: Text(l10n.common_add), + ), + ], + ); + } +} diff --git a/lib/widgets/composer_budget_notice.dart b/lib/widgets/composer_budget_notice.dart new file mode 100644 index 00000000..84121a0d --- /dev/null +++ b/lib/widgets/composer_budget_notice.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../l10n/l10n.dart'; + +/// Explains a composer whose byte budget is too small to carry a message. +/// +/// #592 was reported twice as "the keyboard doesn't respond". It was not an +/// input bug: the byte budget had collapsed to 0, so the length limiter +/// rejected every keystroke while the field still focused and blinked. Nothing +/// on screen said why. +/// +/// This is a persistent inline notice rather than a toast on purpose. The +/// condition is a *state* that lasts as long as the link does, not an event, so +/// a transient snackbar would scroll away and leave the same dead field behind. +/// SAFELANE 6 requires a user-facing error to persist; sitting directly above +/// the composer it also lands where the confusion is (#684). +/// +/// Renders nothing when the budget is healthy, so both composers can include it +/// unconditionally. +class ComposerBudgetNotice extends StatelessWidget { + /// The composer's computed limit, from `maxChannelMessageBytes` or + /// `maxContactMessageBytes`. + final int maxBytes; + + /// Transport in use, so the cause can be named plainly instead of described + /// as generic failure. + final MeshCoreTransportType transport; + + /// Whether a radio is actually connected. + /// + /// Required, and not cosmetic. While disconnected, `_activeTransport` still + /// reads `bluetooth` (its default) and there is no device, so the frame + /// budget falls to the same 20-byte floor an unreported MTU produces. Without + /// this gate the notice would appear on every disconnect and blame the link + /// for a small packet size when there is no link at all. + final bool isConnected; + + const ComposerBudgetNotice({ + super.key, + required this.maxBytes, + required this.transport, + required this.isConnected, + }); + + @override + Widget build(BuildContext context) { + if (!isConnected) return const SizedBox.shrink(); + if (isComposerBudgetUsable(maxBytes)) return const SizedBox.shrink(); + + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + + // A budget of 0 blocks every keystroke; 1-15 accepts input but cannot carry + // a sentence. Those are different severities and must not look the same. + // Zero is a failure: nothing can be sent. Non-zero is a fact about a + // working link, so it is stated rather than alarmed about - a permanent red + // banner over a link that genuinely only fits a few characters is noise, + // and noise is what teaches people to ignore the banner that matters. + final blocked = maxBytes <= 0; + + final title = blocked + ? l10n.composerBudgetBlockedTitle + : l10n.composerBudgetLimitedTitle(maxBytes); + + final cause = transport == MeshCoreTransportType.bluetooth + ? l10n.composerBudgetBluetoothCause + : l10n.composerBudgetGenericCause; + + final background = blocked + ? scheme.errorContainer + : scheme.secondaryContainer; + final foreground = blocked + ? scheme.onErrorContainer + : scheme.onSecondaryContainer; + + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + color: background, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // No semanticLabel on purpose: Icon wraps its glyph in + // ExcludeSemantics and only announces a label when given one, so an + // unlabelled icon is correctly decorative here. The two Text children + // below already carry the whole message to a screen reader, and + // labelling the icon too would just repeat it. + Icon( + blocked ? Icons.error_outline : Icons.info_outline, + size: 18, + color: foreground, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontWeight: FontWeight.w600, + color: foreground, + ), + ), + const SizedBox(height: 2), + Text(cause, style: TextStyle(fontSize: 12, color: foreground)), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/contact_card_chip.dart b/lib/widgets/contact_card_chip.dart new file mode 100644 index 00000000..19d41e30 --- /dev/null +++ b/lib/widgets/contact_card_chip.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import 'add_contact_by_key_dialog.dart'; + +/// Renders a received contact share card as a tappable Add Contact affordance +/// instead of the raw `` text. (#610) +/// +/// This is the receive half of the exchange. The send half (#611) already +/// emits this format, and the stock app already renders it as a native Add +/// Contact button, so until now sharing worked outbound only: a stock user +/// could add an Offband user from a card, but not the reverse. +/// +/// Tapping opens the add dialog seeded with the card, so the user sees the key, +/// name and type before anything is written to the radio. It does NOT add +/// silently: a contact is an identity, and adding one should be a deliberate +/// act with the details visible. +class ContactCardChip extends StatelessWidget { + const ContactCardChip({super.key, required this.card, required this.style}); + + /// The raw matched card text, ``. + final String card; + + final TextStyle style; + + @override + Widget build(BuildContext context) { + final parsed = Contact.fromChannelShare(card); + final scheme = Theme.of(context).colorScheme; + final l10n = context.l10n; + + // The regex matched the shape but the parser rejected the contents, e.g. a + // type outside the documented range. Show the original text rather than a + // chip that would lie about being addable. + if (parsed == null) return Text(card, style: style); + + // Mirrors what stock does: it warned the owner when the contact was + // already held rather than silently re-adding. + // + // O(1) against the connector's maintained key set. Scanning `contacts` + // here would run per rendered chip on every notification, which is + // hundreds of comparisons in a message list on a device with a large + // contact book. (Gemini review, #610) + final known = context.select( + (c) => c.isKnownContact(parsed.publicKeyHex), + ); + + final label = known + ? l10n.contacts_cardAlreadyAdded(parsed.name) + : l10n.contacts_cardAddContact(parsed.name); + + // A WidgetSpan gives its child unbounded width, so Flexible needs a real + // ceiling to ellipsize against. Without this the chip grows to whatever + // name the sender chose, which overflowed the message layout. + // + // Scaled off the viewport rather than a fixed pixel count, so a large + // accessibility font on a wide screen is not ellipsized while space + // remains, and a narrow phone still gets a sane bound. (Gemini recheck) + final maxChipWidth = MediaQuery.sizeOf(context).width * 0.7; + final chip = ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxChipWidth), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: known + ? scheme.onSurface.withValues(alpha: 0.08) + : scheme.primaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + known ? Icons.how_to_reg : Icons.person_add_alt_1, + size: 15, + color: known + ? scheme.onSurfaceVariant + : scheme.onPrimaryContainer, + ), + const SizedBox(width: 5), + // Bounded and ellipsized. The name comes off a public radio channel + // and is attacker-controlled, so an unbounded label lets anyone + // overflow the message layout by posting a card with a long name. + // Reproduced before this: a 405 pixel RenderFlex overflow. + // (Gemini review prompted the adversarial case, #610) + Flexible( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style.copyWith( + fontWeight: FontWeight.w500, + color: known + ? scheme.onSurfaceVariant + : scheme.onPrimaryContainer, + ), + ), + ), + ], + ), + ), + ); + + if (known) { + return Tooltip( + message: l10n.contacts_cardAlreadyAddedTooltip, + child: chip, + ); + } + + return InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () => showAddContactByKeyDialog(context, initialKeyText: card), + child: chip, + ); + } +} diff --git a/lib/widgets/contact_sync_shortfall_banner.dart b/lib/widgets/contact_sync_shortfall_banner.dart new file mode 100644 index 00000000..5b3a0110 --- /dev/null +++ b/lib/widgets/contact_sync_shortfall_banner.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; + +/// Shown above the whole app when a full contact sync delivered fewer contacts +/// than the radio reported (#668), after the forced resync (#703) has tried +/// and is still short. The banner stays until dismissed, and a modal asks +/// whether to keep the saved contacts (the default) or accept the radio's +/// shorter list. +/// +/// SAFELANE §6: the short sync that silently replaced 350 saved contacts with +/// 106 (#660) must now be loud. Sits in `MaterialApp.builder`, above the +/// Navigator, so the modal is drawn here rather than pushed as a route. +class ContactSyncShortfallBanner extends StatelessWidget { + final ContactSyncShortfall? shortfall; + final bool decisionPending; + final int undeliveredCount; + final VoidCallback onDismiss; + final VoidCallback onKeep; + final VoidCallback onUseRadio; + final Widget child; + + const ContactSyncShortfallBanner({ + super.key, + required this.shortfall, + required this.decisionPending, + required this.undeliveredCount, + required this.onDismiss, + required this.onKeep, + required this.onUseRadio, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final current = shortfall; + if (current == null && !decisionPending) return child; + + final content = current == null + ? child + : Column( + children: [ + _banner(context, current), + Expanded(child: child), + ], + ); + if (!decisionPending) return content; + + return Stack( + children: [ + content, + const ModalBarrier(dismissible: false, color: Colors.black54), + Center( + child: _decision( + context, + current?.received ?? 0, + current?.confirmedGone ?? 0, + ), + ), + ], + ); + } + + static String _withGone(String text, int gone, BuildContext context) => + gone > 0 ? '$text ${context.l10n.contactSyncConfirmedGone(gone)}' : text; + + Widget _banner(BuildContext context, ContactSyncShortfall current) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final declared = current.declared; + final body = _withGone( + declared == null + ? l10n.contactSyncShortfallBodyNoTotal(current.received) + : l10n.contactSyncShortfallBody(declared, current.received), + current.confirmedGone, + context, + ); + return Material( + color: scheme.errorContainer, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 10, 4, 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.sync_problem, color: scheme.onErrorContainer), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.contactSyncShortfallTitle, + style: TextStyle( + fontWeight: FontWeight.bold, + color: scheme.onErrorContainer, + ), + ), + const SizedBox(height: 2), + Text( + body, + style: TextStyle(color: scheme.onErrorContainer), + ), + ], + ), + ), + // No tooltip: this sits above the Navigator, where there is no + // Overlay, and a Tooltip without one blanks the window (#713). + IconButton( + icon: Icon( + Icons.close, + color: scheme.onErrorContainer, + semanticLabel: l10n.common_close, + ), + onPressed: onDismiss, + ), + ], + ), + ), + ), + ); + } + + Widget _decision(BuildContext context, int received, int gone) { + final l10n = context.l10n; + return AlertDialog( + title: Text(l10n.contactSyncDecisionTitle), + content: Text( + _withGone( + l10n.contactSyncDecisionBody(received, undeliveredCount), + gone, + context, + ), + ), + actions: [ + TextButton( + onPressed: onUseRadio, + child: Text(l10n.contactSyncUseRadio), + ), + FilledButton( + autofocus: true, + onPressed: onKeep, + child: Text(l10n.contactSyncKeep), + ), + ], + ); + } +} diff --git a/lib/widgets/contact_verification_badge.dart b/lib/widgets/contact_verification_badge.dart new file mode 100644 index 00000000..20d9091c --- /dev/null +++ b/lib/widgets/contact_verification_badge.dart @@ -0,0 +1,109 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import '../models/message.dart'; + +/// How far a contact identity has actually been confirmed. (#630) +enum ContactVerification { + /// Added from a bare key. Nothing has confirmed it on air. + keyOnly, + + /// A message with this contact went through. That is cryptographic proof + /// the holder of the matching private key is live and reachable, because + /// direct messages are encrypted with an ECDH secret derived from this + /// contact key, and the ACK is computed over the decrypted plaintext + /// (firmware `BaseChatMesh.cpp:442,451`). It does NOT prove the person is + /// who the name claims: names are display, keys are identity. + keyConfirmed, + + /// A signed advert has been received. Strongest state: the node itself + /// asserted its name, type and position, and the raw advert is stored, so + /// the contact can also be re-shared. + advertVerified, +} + +/// Resolves the verification state for [contact]. +/// +/// This runs from a widget `build` inside a contact `ListView`, so it does as +/// little as possible: +/// +/// 1. An advert-verified contact returns immediately on a single integer +/// comparison. That is most contacts, and no message list is touched. +/// 2. Only a key-only contact scans, and it scans **newest first**, because a +/// delivered message is overwhelmingly likely to be recent. +/// +/// A `lastMessageAt == epoch` shortcut was considered and **rejected**: +/// `_setContactLastMessageAt` maintains that field only for `advTypeChat`, so +/// a key-added repeater that had been messaged would have reported the wrong +/// badge. A cheap wrong answer is worse than a slightly slower right one. +/// +/// Remaining worst case is a key-only contact carrying many messages of which +/// none ever delivered. If that shows up in practice the fix is a cached flag +/// set once on first delivery, not a bounded scan, which could misreport. +ContactVerification resolveContactVerification( + Contact contact, + MeshCoreConnector connector, +) { + if (contact.isAdvertVerified) return ContactVerification.advertVerified; + final messages = connector.getMessages(contact); + for (var i = messages.length - 1; i >= 0; i--) { + if (messages[i].status == MessageStatus.delivered) { + return ContactVerification.keyConfirmed; + } + } + return ContactVerification.keyOnly; +} + +/// A small, deliberately calm indicator of how far a contact is confirmed. +/// +/// Owner steer (#630): a green check for fully verified and a different icon +/// otherwise. Explicitly NOT amber and NOT a hazard glyph, because nothing is +/// wrong with a key-added contact. The scale reads as "how much we know", +/// never as "how risky". +class ContactVerificationBadge extends StatelessWidget { + const ContactVerificationBadge({ + super.key, + required this.contact, + this.size = 15, + }); + + final Contact contact; + final double size; + + @override + Widget build(BuildContext context) { + final state = resolveContactVerification( + contact, + context.read(), + ); + final scheme = Theme.of(context).colorScheme; + final l10n = context.l10n; + + final (IconData icon, Color color, String tooltip) = switch (state) { + ContactVerification.advertVerified => ( + Icons.verified, + // The one deliberately positive colour in the set. + Colors.green, + l10n.contacts_verifiedByAdvert, + ), + ContactVerification.keyConfirmed => ( + Icons.check_circle_outline, + scheme.onSurfaceVariant, + l10n.contacts_verifiedByMessage, + ), + ContactVerification.keyOnly => ( + Icons.key_outlined, + scheme.onSurfaceVariant, + l10n.contacts_verifiedKeyOnly, + ), + }; + + return Tooltip( + message: tooltip, + child: Icon(icon, size: size, color: color), + ); + } +} diff --git a/lib/widgets/my_contact_qr_dialog.dart b/lib/widgets/my_contact_qr_dialog.dart new file mode 100644 index 00000000..289e8a9f --- /dev/null +++ b/lib/widgets/my_contact_qr_dialog.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; +import 'qr_code_display.dart'; + +/// Shows this device's own identity as a scannable QR plus a copyable link. +/// (#629) +/// +/// This is the fast, definitive way to hand someone your identity: it carries +/// the public key itself, so it cannot fail on a name mismatch and it does not +/// ask them to wait for an advert. It also costs the mesh no airtime, which +/// asking for a couple of flood adverts does. +/// +/// Rendering works on every platform, which matters on desktop: put this on +/// screen and the other person scans it with their phone. +Future showMyContactQrDialog(BuildContext context) { + final connector = Provider.of(context, listen: false); + final keyHex = connector.selfPublicKeyHex; + + // Without a connection we do not know our own key, so there is nothing + // truthful to render. + if (keyHex.length != pubKeySize * 2) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.contacts_qrNeedsConnection), + ); + return Future.value(); + } + + final uri = Contact.buildShareUri( + publicKeyHex: keyHex, + name: connector.selfName ?? '', + // This device is a companion. + type: advTypeChat, + ); + + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.contacts_myContactQr), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + QrCodeDisplay( + data: uri, + instructions: dialogContext.l10n.contacts_myContactQrInstructions, + ), + const SizedBox(height: 8), + SelectableText( + uri, + style: Theme.of(dialogContext).textTheme.bodySmall?.copyWith( + fontFamily: 'monospace', + color: Theme.of(dialogContext).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + actions: [ + TextButton.icon( + onPressed: () async { + await Clipboard.setData(ClipboardData(text: uri)); + if (!dialogContext.mounted) return; + showDismissibleSnackBar( + dialogContext, + content: Text(dialogContext.l10n.contacts_contactLinkCopied), + ); + }, + icon: const Icon(Icons.copy), + label: Text(dialogContext.l10n.common_copy), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: Text(dialogContext.l10n.common_close), + ), + ], + ), + ); +} diff --git a/lib/widgets/qr_code_display.dart b/lib/widgets/qr_code_display.dart index 584eabee..dca94c28 100644 --- a/lib/widgets/qr_code_display.dart +++ b/lib/widgets/qr_code_display.dart @@ -96,9 +96,18 @@ class QrCodeDisplay extends StatelessWidget { ), ], ), - child: embeddedImage != null - ? _buildQrWithEmbeddedImage(fgColor, bgColor) - : _buildSimpleQr(fgColor, bgColor), + // Bound the QR to a fixed square. QrImageView builds through a + // LayoutBuilder, which cannot answer intrinsic dimension queries, + // so an intrinsic-measuring parent (AlertDialog measures its + // content's max intrinsic height) throws without this. A tight + // SizedBox answers the intrinsic itself and never asks the child. + // (#629, first real use of this widget.) + child: SizedBox.square( + dimension: size, + child: embeddedImage != null + ? _buildQrWithEmbeddedImage(fgColor, bgColor) + : _buildSimpleQr(fgColor, bgColor), + ), ), if (instructions != null) ...[ diff --git a/lib/widgets/radio_preset_picker.dart b/lib/widgets/radio_preset_picker.dart new file mode 100644 index 00000000..642f1e92 --- /dev/null +++ b/lib/widgets/radio_preset_picker.dart @@ -0,0 +1,175 @@ +import 'package:flutter/material.dart'; + +import '../l10n/l10n.dart'; +import '../models/radio_preset.dart'; +import '../services/radio_preset_service.dart'; + +/// The regional preset picker (#729): presets grouped by region under +/// non-selectable headers, each labelled with its source, plus a status line +/// saying where the list came from (and any refresh failure) with a refresh +/// button. Used by the companion Radio Settings form and the remote-node +/// settings screen. +class RadioPresetPicker extends StatelessWidget { + const RadioPresetPicker({ + super.key, + required this.service, + required this.presets, + required this.selectedId, + required this.onSelected, + }); + + final RadioPresetService service; + + /// The presets to offer, already filtered and in display order (grouped + /// by region). + final List presets; + final String? selectedId; + final ValueChanged onSelected; + + static const _regionHeaderPrefix = 'region:'; + + RadioPreset? _byId(String? id) => + id == null ? null : presets.where((p) => p.id == id).firstOrNull; + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final selected = _byId(selectedId)?.id; + final titlesById = {for (final p in presets) p.id: p.title}; + final items = >[]; + String? region; + for (final preset in presets) { + if (preset.region != region) { + region = preset.region; + items.add( + DropdownMenuItem( + value: '$_regionHeaderPrefix$region', + enabled: false, + child: Text( + region, + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + ); + } + items.add( + DropdownMenuItem( + value: preset.id, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12), + child: Row( + children: [ + Expanded( + child: Text(preset.title, overflow: TextOverflow.ellipsis), + ), + const SizedBox(width: 8), + Text( + switch (preset.source) { + RadioPresetSource.meshcore => + l10n.settings_presetSourceMeshCore, + RadioPresetSource.offband => + l10n.settings_presetSourceOffband, + }, + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DropdownButtonFormField( + key: ValueKey(selected), + initialValue: selected, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.settings_presets, + border: const OutlineInputBorder(), + ), + selectedItemBuilder: (context) => [ + for (final item in items) + Align( + alignment: AlignmentDirectional.centerStart, + child: Text( + titlesById[item.value] ?? '', + overflow: TextOverflow.ellipsis, + ), + ), + ], + items: items, + // Disabled while a refresh runs, so a pick can't vanish when the + // refreshed list lands. + onChanged: service.refreshing + ? null + : (id) { + final preset = _byId(id); + if (preset != null) onSelected(preset); + }, + ), + _PresetStatus(service: service), + ], + ); + } +} + +/// Where the list came from, and any refresh failure, kept on screen until +/// the next successful refresh. +class _PresetStatus extends StatelessWidget { + const _PresetStatus({required this.service}); + + final RadioPresetService service; + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final String text; + Color? color; + if (service.refreshing) { + text = l10n.settings_presetsUpdating; + } else if (service.refreshError != null) { + text = l10n.settings_presetsUpdateFailed; + color = theme.colorScheme.error; + } else if (service.lastRefreshed != null) { + text = l10n.settings_presetsUpdatedAt( + MaterialLocalizations.of( + context, + ).formatMediumDate(service.lastRefreshed!.toLocal()), + ); + } else { + text = l10n.settings_presetsBundled; + } + return Row( + children: [ + Expanded( + child: Text( + text, + style: theme.textTheme.bodySmall?.copyWith( + color: color ?? theme.colorScheme.onSurfaceVariant, + ), + ), + ), + IconButton( + tooltip: l10n.settings_presetsRefresh, + onPressed: service.refreshing ? null : service.refresh, + icon: service.refreshing + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + ), + ], + ); + } +} diff --git a/lib/widgets/top_toast.dart b/lib/widgets/top_toast.dart new file mode 100644 index 00000000..b0217098 --- /dev/null +++ b/lib/widgets/top_toast.dart @@ -0,0 +1,222 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../utils/app_logger.dart'; + +/// A transient, tap-to-dismiss notification anchored to the TOP of the screen. +/// +/// The app previously used bottom-anchored [SnackBar]s, which sat on top of the +/// chat composer (#638). A [SnackBar] is positioned by its [Scaffold] and can +/// only be pushed upward with a near-full-height bottom margin, which delays +/// its reveal animation and turns the whole screen into a hit-test target, so +/// this renders through the [Overlay] instead. +class TopToast { + TopToast._(); + + static const Duration _animationDuration = Duration(milliseconds: 220); + static const Duration defaultDuration = Duration(seconds: 4); + static const double _maxWidth = 560; + + /// Removes the toast currently on screen. Non-null only while one is visible. + static VoidCallback? _dismissCurrent; + + /// Shows [content] at the top of the screen. + /// + /// When [persist] is true the toast stays until the user dismisses it, for + /// messages that must be read rather than glimpsed (SAFELANE 6). + static void show( + BuildContext context, { + required Widget content, + Color? backgroundColor, + Duration duration = defaultDuration, + bool persist = false, + }) { + final overlay = Overlay.maybeOf(context, rootOverlay: true); + if (overlay == null) { + // SAFELANE 6: a message we cannot display must not disappear silently. + appLogger.warn( + 'No Overlay in this context; notification was not shown', + tag: 'TopToast', + ); + return; + } + + // A newer message replaces the visible one outright: two entries would + // otherwise stack on top of each other at the same position. + _dismissCurrent?.call(); + + late final OverlayEntry entry; + var removed = false; + void remove() { + if (removed) return; + removed = true; + entry.remove(); + if (_dismissCurrent == remove) { + _dismissCurrent = null; + } + } + + entry = OverlayEntry( + builder: (_) => _TopToastHost( + backgroundColor: backgroundColor, + duration: duration, + persist: persist, + animationDuration: _animationDuration, + maxWidth: _maxWidth, + onDismissed: remove, + child: content, + ), + ); + _dismissCurrent = remove; + overlay.insert(entry); + } +} + +class _TopToastHost extends StatefulWidget { + const _TopToastHost({ + required this.child, + required this.duration, + required this.persist, + required this.animationDuration, + required this.maxWidth, + required this.onDismissed, + this.backgroundColor, + }); + + final Widget child; + final Duration duration; + final bool persist; + final Duration animationDuration; + final double maxWidth; + final VoidCallback onDismissed; + final Color? backgroundColor; + + @override + State<_TopToastHost> createState() => _TopToastHostState(); +} + +class _TopToastHostState extends State<_TopToastHost> + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: widget.animationDuration, + ); + Timer? _timer; + bool _dismissing = false; + + @override + void initState() { + super.initState(); + _controller.forward(); + if (!widget.persist) { + _timer = Timer(widget.duration, _dismiss); + } + } + + Future _dismiss() async { + if (_dismissing || !mounted) return; + _dismissing = true; + _timer?.cancel(); + try { + await _controller.reverse(); + } on TickerCanceled { + // Replaced by a newer toast mid-animation; that path already removed us. + return; + } + if (!mounted) return; + widget.onDismissed(); + } + + @override + void dispose() { + _timer?.cancel(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final background = + widget.backgroundColor ?? + theme.snackBarTheme.backgroundColor ?? + theme.colorScheme.inverseSurface; + final textStyle = + theme.snackBarTheme.contentTextStyle ?? + theme.textTheme.titleMedium!.copyWith( + color: theme.colorScheme.onInverseSurface, + ); + + return Positioned( + top: 0, + left: 0, + right: 0, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), + child: Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: widget.maxWidth), + child: SlideTransition( + position: + Tween( + begin: const Offset(0, -0.4), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _controller, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ), + ), + child: FadeTransition( + opacity: _controller, + // Parity with SnackBar, which wraps its content the same way + // (snack_bar.dart): without liveRegion a screen reader never + // announces the message at all. + child: Semantics( + container: true, + liveRegion: true, + onDismiss: _dismiss, + child: Material( + color: background, + elevation: 6, + borderRadius: BorderRadius.circular(8), + clipBehavior: Clip.antiAlias, + // One recognizer for both gestures: a nested InkWell would + // also splash on the tap-up that ends a dismissing swipe. + child: GestureDetector( + onTap: _dismiss, + onVerticalDragEnd: (details) { + if ((details.primaryVelocity ?? 0) < 0) { + _dismiss(); + } + }, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + child: DefaultTextStyle( + style: textStyle, + child: IconTheme( + data: IconThemeData(color: textStyle.color), + child: widget.child, + ), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/translated_message_content.dart b/lib/widgets/translated_message_content.dart index 96b89177..d61f6cf0 100644 --- a/lib/widgets/translated_message_content.dart +++ b/lib/widgets/translated_message_content.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '../helpers/link_handler.dart'; +import 'contact_card_chip.dart'; class TranslatedMessageContent extends StatelessWidget { final String displayText; @@ -25,6 +26,15 @@ class TranslatedMessageContent extends StatelessWidget { // A leading `@[Name] ` reply prefix. static final RegExp _replyPrefix = RegExp(r'^@\[([^\]]+)\]\s+'); + /// A contact share card, `<64-hex key:type:name>`, rendered as a tappable + /// Add Contact chip rather than the raw text it used to show. (#610) + /// + /// This is the format real clients put on the air, confirmed because the + /// stock app renders it as a native Add Contact button. The name is the final + /// field and may contain colons and spaces, so it is matched greedily to the + /// closing bracket; brackets themselves are stripped by the emitter. + static final RegExp _contactCard = RegExp(r'<[0-9a-fA-F]{64}:\d+:[^>]*>'); + /// The name of a leading `@[Name]` reply mention, or null. Lets callers show /// a reply chip above content that isn't rendered as text (e.g. a reply-gif, /// #232). @@ -50,27 +60,44 @@ class TranslatedMessageContent extends StatelessWidget { } Widget _buildText(BuildContext context, String text, TextStyle textStyle) { - if (!_mention.hasMatch(text)) { + final hasMention = _mention.hasMatch(text); + final hasCard = _contactCard.hasMatch(text); + if (!hasMention && !hasCard) { return LinkHandler.buildLinkifyText( context: context, text: text, style: textStyle, ); } - // Mentions can't be interleaved with the Linkify widget, so a message that - // contains a mention renders as rich text with chip spans (links inside a - // mention message are not tappable, same as the prior leading-mention - // path). Messages without a mention keep full link support above. + // Neither chip can be interleaved with the Linkify widget, so a message + // containing one renders as rich text with chip spans (links inside such a + // message are not tappable, same as the prior leading-mention path). + // Messages with neither keep full link support above. + // + // Both patterns are collected and sorted by position, so a message + // carrying a mention AND a contact card renders both in the right order. + // They cannot overlap: a mention is `@[...]`, a card is `<...>`. + // Each match carries which pattern produced it. Inferring the kind from + // the text, e.g. `text[m.start] == '<'`, would silently mis-route the day + // a third bracketed pattern is added. (Gemini review, #610) + final matches = <(Match, bool isCard)>[ + ..._mention.allMatches(text).map((m) => (m, false)), + ..._contactCard.allMatches(text).map((m) => (m, true)), + ]..sort((a, b) => a.$1.start.compareTo(b.$1.start)); + final spans = []; var last = 0; - for (final m in _mention.allMatches(text)) { + for (final (m, isCard) in matches) { + if (m.start < last) continue; if (m.start > last) { spans.add(TextSpan(text: text.substring(last, m.start))); } spans.add( WidgetSpan( alignment: PlaceholderAlignment.middle, - child: mentionChip(context, m.group(1)!, textStyle), + child: isCard + ? ContactCardChip(card: m.group(0)!, style: textStyle) + : mentionChip(context, m.group(1)!, textStyle), ), ); last = m.end; diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index f6f23bfe..6cf6d508 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,10 +6,22 @@ #include "generated_plugin_registrant.h" +#include +#include #include +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin"); + screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); + g_autoptr(FlPluginRegistrar) window_manager_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "WindowManagerPlugin"); + window_manager_plugin_register_with_registrar(window_manager_registrar); } diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 93e46829..b86d669d 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,7 +3,10 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + screen_retriever_linux url_launcher_linux + window_manager ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index d2ea57e9..6a868e65 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,24 +5,32 @@ import FlutterMacOS import Foundation +import file_selector_macos import flutter_blue_plus_darwin import flutter_local_notifications import mobile_scanner import package_info_plus +import path_provider_foundation +import screen_retriever_macos import share_plus import shared_preferences_foundation import sqflite_darwin import url_launcher_macos import wakelock_plus +import window_manager func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin")) SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) WakelockPlusMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockPlusMacosPlugin")) + WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin")) } diff --git a/packages/flserial/.clang-format b/packages/flserial/.clang-format new file mode 100644 index 00000000..64ee9a17 --- /dev/null +++ b/packages/flserial/.clang-format @@ -0,0 +1,3 @@ +# Disable clang-format for this vendored submodule so that local patches +# are not stomped by editor auto-formatting. +DisableFormat: true diff --git a/packages/flserial/.gitignore b/packages/flserial/.gitignore new file mode 100644 index 00000000..ac5aa989 --- /dev/null +++ b/packages/flserial/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/packages/flserial/.metadata b/packages/flserial/.metadata new file mode 100644 index 00000000..3c2a016b --- /dev/null +++ b/packages/flserial/.metadata @@ -0,0 +1,42 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668" + channel: "stable" + +project_type: plugin_ffi + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: android + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: ios + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: linux + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: macos + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: windows + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/flserial/CHANGELOG.md b/packages/flserial/CHANGELOG.md new file mode 100644 index 00000000..e31a4adb --- /dev/null +++ b/packages/flserial/CHANGELOG.md @@ -0,0 +1,49 @@ +## 0.3.5 +* Add support 16KB Page Size + +## 0.3.4 +* Changelog fix + +## 0.3.3 +* Replace fifo library + +## 0.3.2 +* MacOS support +* Memory allocation fix + +## 0.3.1 +* Update libs + +## 0.3.0 +* Import project to new plugin ffi template +* Few Api changes + +## 0.2.0 +* New event model +* Cleaning up unnecessary libs +* Performance improvements +* Api changes, main functions: + +Stream based events, before: +``` +serial.onSerialData.subscribe( +``` +to: +``` +serial.onSerialData.stream.listen( +``` + +Write serial port, before: +``` +serial.write(data.length, data); +``` +to: +``` +serial.write(data); +``` + +## 0.1.2 +* Android compilation + +## 0.1.1 +* Initial beta version diff --git a/packages/flserial/LICENSE b/packages/flserial/LICENSE new file mode 100644 index 00000000..aad987ed --- /dev/null +++ b/packages/flserial/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Grzegorz Leśniak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/flserial/README.md b/packages/flserial/README.md new file mode 100644 index 00000000..cae9c4f3 --- /dev/null +++ b/packages/flserial/README.md @@ -0,0 +1,63 @@ +# flserial +Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices. + +Based on great serial library: https://github.com/wjwwood/serial + +Supported platforms: +- Linux +- Windows +- Android +- MacOS + +Example of usage: + +``` + FlSerial serial = FlSerial(); + serial.init(); + serial.openPort("COM3", 9600); + serial.onSerialData.stream.listen( + (args) { + if (args.len > 0) { + print(args.serial.readList()); + } + }, + ); + + serial.setByteSize8(); + serial.setBitParityNone(); + serial.setStopBits1(); + serial.setFlowControlNone(); + + String msg = "Hello World!"; + var list = msg.codeUnits; + serial.write(Uint8List.fromList(list)); + + serial.closePort(); + serial.free(); + + +``` + + + +MIT License + +Copyright (c) 2024 Grzegorz Leśniak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/flserial/analysis_options.yaml b/packages/flserial/analysis_options.yaml new file mode 100644 index 00000000..a5744c1c --- /dev/null +++ b/packages/flserial/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/flserial/android/.gitignore b/packages/flserial/android/.gitignore new file mode 100644 index 00000000..161bdcda --- /dev/null +++ b/packages/flserial/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/packages/flserial/android/build.gradle b/packages/flserial/android/build.gradle new file mode 100644 index 00000000..c2859ef5 --- /dev/null +++ b/packages/flserial/android/build.gradle @@ -0,0 +1,66 @@ +// The Android Gradle Plugin builds the native code with the Android NDK. + +group = "pl.glpro.flserial" +version = "1.0" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + // The Android Gradle Plugin knows how to build native code with the NDK. + classpath("com.android.tools.build:gradle:8.13.0") + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" + +android { + if (project.android.hasProperty("namespace")) { + namespace = "pl.glpro.flserial" + } + + // Bumping the plugin compileSdk version requires all clients of this plugin + // to bump the version in their app. + compileSdk = 36 + + // Use the NDK version + // declared in /android/app/build.gradle file of the Flutter project. + // Replace it with a version number if this plugin requires a specific NDK version. + // (e.g. ndkVersion "23.1.7779620") + // ndkVersion = android.ndkVersion + ndkVersion = "29.0.14206865" + + // Invoke the shared CMake build with the Android Gradle Plugin. + externalNativeBuild { + cmake { + path = "../src/CMakeLists.txt" + + // The default CMake version for the Android Gradle Plugin is 3.10.2. + // https://developer.android.com/studio/projects/install-ndk#vanilla_cmake + // + // The Flutter tooling requires that developers have CMake 3.10 or later + // installed. You should not increase this version, as doing so will cause + // the plugin to fail to compile for some customers of the plugin. + // version "3.10.2" + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdk = 21 + } +} diff --git a/packages/flserial/android/settings.gradle b/packages/flserial/android/settings.gradle new file mode 100644 index 00000000..ea223529 --- /dev/null +++ b/packages/flserial/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'flserial' diff --git a/packages/flserial/android/src/main/AndroidManifest.xml b/packages/flserial/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..a51915ba --- /dev/null +++ b/packages/flserial/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/packages/flserial/ffigen.yaml b/packages/flserial/ffigen.yaml new file mode 100644 index 00000000..31e28c07 --- /dev/null +++ b/packages/flserial/ffigen.yaml @@ -0,0 +1,19 @@ +# Run with `dart run ffigen --config ffigen.yaml`. +name: FlserialBindings +description: | + Bindings for `src/flserial.h`. + + Regenerate bindings with `dart run ffigen --config ffigen.yaml`. +output: 'lib/flserial_bindings_generated.dart' +headers: + entry-points: + - 'src/flserial.h' + include-directives: + - 'src/flserial.h' +preamble: | + // ignore_for_file: always_specify_types + // ignore_for_file: camel_case_types + // ignore_for_file: non_constant_identifier_names +comments: + style: any + length: full diff --git a/packages/flserial/ios/Classes/flserial.c b/packages/flserial/ios/Classes/flserial.c new file mode 100644 index 00000000..56c5e102 --- /dev/null +++ b/packages/flserial/ios/Classes/flserial.c @@ -0,0 +1,3 @@ +// Relative import to be able to reuse the C sources. +// See the comment in ../flserial.podspec for more information. +#include "../../src/flserial.cp" diff --git a/packages/flserial/ios/flserial.podspec b/packages/flserial/ios/flserial.podspec new file mode 100644 index 00000000..006f0d04 --- /dev/null +++ b/packages/flserial/ios/flserial.podspec @@ -0,0 +1,28 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flserial.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flserial' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.platform = :ios, '12.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' +end diff --git a/packages/flserial/lib/flserial.dart b/packages/flserial/lib/flserial.dart new file mode 100644 index 00000000..6b6668cd --- /dev/null +++ b/packages/flserial/lib/flserial.dart @@ -0,0 +1,450 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; +import 'package:flserial/flserial_exception.dart'; + +import 'flserial_bindings_generated.dart'; + +const String _libName = 'flserial'; +const int _serialIOBuffLen = 1024 * 8; + +/// The dynamic library in which the symbols for [FlserialBindings] can be found. +final DynamicLibrary dylib = () { + if (Platform.isMacOS || Platform.isIOS) { + return DynamicLibrary.open('$_libName.framework/$_libName'); + } + if (Platform.isAndroid || Platform.isLinux) { + return DynamicLibrary.open('lib$_libName.so'); + } + if (Platform.isWindows) { + return DynamicLibrary.open('$_libName.dll'); + } + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); +}(); + +/// The bindings to the native functions in [_dylib]. +final FlserialBindings bindings = FlserialBindings(dylib); + +/// Native pointer to string conversion +String nativeInt8ToString(Pointer pointer, {bool allowMalformed = true}) { + var ptrName = pointer.cast(); + final ptrNameCodeUnits = pointer.cast(); + var list = ptrNameCodeUnits.asTypedList(ptrName.length); + return utf8.decode(list, allowMalformed: allowMalformed); +} + +/// String conversion to native pointer, memory should be free outside function +Pointer stringToNativeInt8(String str, {Allocator allocator = calloc}) { + final units = utf8.encode(str); + final result = allocator(units.length + 1); + final nativeString = result.asTypedList(units.length + 1); + nativeString.setAll(0, units); + nativeString[units.length] = 0; + + return result.cast(); +} + +/// List conversion to native pointer, memory should be free outside function +Pointer int8ListToPointerInt8(Uint8List units, Pointer pointer, + {Allocator allocator = calloc}) { + final nativeString = pointer.asTypedList(units.length + 1); //blobBytes + nativeString.setAll(0, units); + nativeString[units.length] = 0; + return pointer.cast(); +} + +Pointer listToPointerDouble(List sample) { + final Pointer pointer = + calloc.allocate(sample.length, alignment: 8); + final nativeSamples = pointer.asTypedList(sample.length); + nativeSamples.setAll(0, sample); + return pointer.cast(); +} + +/// Native pointer conversion to list +Int8List nativeInt8ToInt8List(Pointer pointer) { + var ptrName = pointer.cast(); + final ptrNameCodeUnits = pointer.cast(); + var list = ptrNameCodeUnits.asTypedList(ptrName.length); + return list; +} + +/// Open serial port status +enum FlOpenStatus { + open, + closed, + error, +} + +/// Class for incoming data handling +class FlSerialEventArgs { + FlSerialEventArgs(this.serial, this.len, this.cts, this.dsr); + final FlSerial serial; + final int len; + final bool cts, dsr; +} + +/// Main serial wrapper class over ffi +class FlSerial { + int flh = -1; + bool prevCTS = false; + bool prevDSR = false; + var onSerialData = StreamController(); + Pointer serialReadBuff = Pointer.fromAddress(0); + Pointer serialWriteBuff = Pointer.fromAddress(0); + + /// Init should be called at program start, after FlSerial creation + /// Function is used to make array of internal port structs for 16 parallel processing ports + int init() { + return bindings.fl_init(16); + } + + /// Setting callback to native code. Used for incoming data signal + void setCallback(int flh, {required DartflcallbackFunction callback}) { + final nativeCallable = + NativeCallable.listener(callback); + bindings.fl_set_callback(flh, nativeCallable.nativeFunction); + } + + /// Listing serial ports. Platform depend + static List listPorts() { + List list = List.empty(growable: true); + + Allocator allocator = calloc; + var result = allocator(1024); + + for (int i = 0; i < 255; i++) { + int len = bindings.fl_ports(i, 1024, result); + if (len > 0) { + String resultStr = result.cast().toDartString(length: len); + list.add(resultStr); + } else { + break; + } + } + + allocator.free(result); + return list; + } + + /// Internal function for serial port handler checking + int _checkFLH(int handler) { + if (handler >= 0 && handler < MAX_PORT_COUNT) { + return FlError.FL_ERROR_OK; + } + throw FlSerialException(FlError.FL_ERROR_HANDLER, msg: "$handler"); + } + + /// Function for openning serial port + FlOpenStatus openPort(String portname, int baudrate) { + prevCTS = false; + prevDSR = false; + Pointer ptr = stringToNativeInt8(portname); + flh = bindings.fl_open(flh, ptr, baudrate); + calloc.free(ptr); + int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + int flerror = FlError.FL_ERROR_UNKNOW; + if (error > 0) { + /// error mapping + String msg = "Port open error: $portname"; + switch (error) { + case 1: + case 3: + flerror = FlError.FL_ERROR_PORT_NOT_EXIST; + msg += " port not exist"; + break; + case 2: + flerror = FlError.FL_ERROR_PORT_ALLREADY_OPEN; + msg += " port allready open"; + break; + } + + bindings.fl_close(flh); + flh = -1; + throw FlSerialException(flerror, msg: msg); + } + + onSerialData = StreamController(); + + Allocator allocator = calloc; + serialReadBuff = allocator(_serialIOBuffLen); + serialWriteBuff = allocator(_serialIOBuffLen); + + setCallback( + flh, + callback: (cflh, len) async { + if (len > 0) { + onSerialData.add(FlSerialEventArgs(this, len, prevCTS, prevDSR)); + } + }, + ); + + return isOpen(); + } + + /// Function check is serial port opened + FlOpenStatus isOpen() { + if (flh < 0) { + return FlOpenStatus.closed; + } + + int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + if (error > 0) { + return FlOpenStatus.error; + } + int nres = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_IS_PORT_OPEN, -1); + if (nres == 0) { + return FlOpenStatus.closed; + } + return FlOpenStatus.open; + } + + /// Get last error message. Return empty string if no error + String getLastError() { + _checkFLH(flh); + + int res = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + String strres = ""; + + switch (res) { + case FlError.FL_ERROR_OK: + strres = "0: None"; + break; + case FlError.FL_ERROR_PORT_ALLREADY_OPEN: + strres = "$res: Port allready open"; + break; + case FlError.FL_ERROR_PORT_NOT_EXIST: + strres = "$res: Port not exist"; + break; + default: + strres = "-1: Unknow error"; + break; + } + return strres; + } + +/* + Future _readLineStatus() async { + + _checkFLH(flh); + + bool currCTS = getCTS(); + bool currDSR = getDSR(); + if(currCTS != prevCTS || prevDSR != currDSR) + { + prevCTS = currCTS; + prevDSR = currDSR; + + onSerialData.broadcast(FlSerialEventArgs( + readBuff.length, Uint8List(0), currCTS, currDSR)); + } + return 0; + }*/ + + /// Internal function to read serial data from lower layer with desired len. If no data is present, empty list is returned + Uint8List _readList(int len) { + _checkFLH(flh); + + if (len > _serialIOBuffLen) { + len = _serialIOBuffLen; + } + + int intres = bindings.fl_read(flh, len, serialReadBuff); + + if (intres <= 0) { + return Uint8List(0); + } + + final ptrNameCodeUnits = serialReadBuff.cast(); + var list = ptrNameCodeUnits.asTypedList(intres); + + return list; + } + + /// Read full read bufer from serial port + Uint8List readList() { + _checkFLH(flh); + + return readListLen(1024 * 8); + } + + /// Read desired len from serial port buffer + Uint8List readListLen(int len) { + _checkFLH(flh); + + return _readList(len); + } + + /// Read single byte + int read() { + _checkFLH(flh); + + Uint8List data = _readList(1); + + if (data.isNotEmpty) { + return data.first; + } + return -1; + } + + /// Write list data to serial port + int write(Uint8List data) { + _checkFLH(flh); + + Pointer ptr = int8ListToPointerInt8(data, serialWriteBuff); + int res = bindings.fl_write(flh, data.length, ptr); + + return res; + } + + /// Close serial port and free resources + int closePort() { + _checkFLH(flh); + bindings.fl_close(flh); + onSerialData.close(); + Allocator allocator = calloc; + if (serialReadBuff.value != 0) { + allocator.free(serialReadBuff); + } + if (serialWriteBuff.value != 0) { + allocator.free(serialWriteBuff); + } + flh = -1; + return flh; + } + + /// Uniwersal function to control serial port + int ctrl(int cmd, int value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, cmd, value); + } + + /// Function set RTS line in serial port + int setRTS(bool value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_RTS, value ? 1 : 0); + } + + /// Function set CTS line in serial port + bool getCTS() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_CTS, 0) > 0 ? true : false; + } + + /// Get status of DTR line + int setDTR(bool value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_DTR, value ? 1 : 0); + } + + /// Get status of DSR line + bool getDSR() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_DSR, 0) > 0 ? true : false; + } + + /// Set byte size to 5 bits + int setByteSize5() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_5, 0); + } + + /// Set byte size to 6 bits + int setByteSize6() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_6, 0); + } + + /// Set byte size to 7 bits + int setByteSize7() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_7, 0); + } + + /// Set byte size to 8 bits + int setByteSize8() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_8, 0); + } + + /// Set bit parity to none + int setBitParityNone() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_NONE, 0); + } + + /// Set bit parity to odd + int setBitParityOdd() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_ODD, 0); + } + + // Set bit parity to even + int setBitParityEven() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_EVEN, 0); + } + + // Set bit parity to mark + int setBitParityMark() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_MARK, 0); + } + + // Set bit parity to space + int setBitParitySpace() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_SPACE, 0); + } + + /// Set stop bits to one + int setStopBits1() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE, 0); + } + + /// Set stop bits to one and half + int setStopBits1_5() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, 0); + } + + /// Set stop bits to two + int setStopBits2() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_TWO, 0); + } + + /// Disable flow control + int setFlowControlNone() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_NONE, 0); + } + + /// Set hardware flow control + int setFlowControlHardware() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_HARDWARE, 0); + } + + /// Set xon/xoff flow control (software) + int setFlowControlSoftware() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_SOFTWARE, 0); + } + + /// Waiting for status line change + int setWaitStatusChange() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_STATUS_CHANGE, 0); + } + + /// Free resources. Serial port should not be used after calling this function + int free() { + return bindings.fl_free(); + } +} diff --git a/packages/flserial/lib/flserial_bindings_generated.dart b/packages/flserial/lib/flserial_bindings_generated.dart new file mode 100644 index 00000000..a8c22a9d --- /dev/null +++ b/packages/flserial/lib/flserial_bindings_generated.dart @@ -0,0 +1,216 @@ +// ignore_for_file: always_specify_types +// ignore_for_file: camel_case_types +// ignore_for_file: non_constant_identifier_names + +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +// ignore_for_file: type=lint +import 'dart:ffi' as ffi; + +/// Bindings for `src/flserial.h`. +/// +/// Regenerate bindings with `dart run ffigen --config ffigen.yaml`. +/// +class FlserialBindings { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + FlserialBindings(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + FlserialBindings.fromLookup( + ffi.Pointer Function(String symbolName) + lookup) + : _lookup = lookup; + + int fl_init( + int portCount, + ) { + return _fl_init( + portCount, + ); + } + + late final _fl_initPtr = + _lookup>('fl_init'); + late final _fl_init = _fl_initPtr.asFunction(); + + int fl_set_callback( + int flh, + flcallback cb, + ) { + return _fl_set_callback( + flh, + cb, + ); + } + + late final _fl_set_callbackPtr = + _lookup>( + 'fl_set_callback'); + late final _fl_set_callback = + _fl_set_callbackPtr.asFunction(); + + int fl_ports( + int index, + int buffsize, + ffi.Pointer buff, + ) { + return _fl_ports( + index, + buffsize, + buff, + ); + } + + late final _fl_portsPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_ports'); + late final _fl_ports = + _fl_portsPtr.asFunction)>(); + + int fl_open( + int flh, + ffi.Pointer portname, + int baudrate, + ) { + return _fl_open( + flh, + portname, + baudrate, + ); + } + + late final _fl_openPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Pointer, ffi.Int)>>('fl_open'); + late final _fl_open = + _fl_openPtr.asFunction, int)>(); + + int fl_read( + int flh, + int len, + ffi.Pointer buff, + ) { + return _fl_read( + flh, + len, + buff, + ); + } + + late final _fl_readPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_read'); + late final _fl_read = + _fl_readPtr.asFunction)>(); + + int fl_write( + int flh, + int len, + ffi.Pointer data, + ) { + return _fl_write( + flh, + len, + data, + ); + } + + late final _fl_writePtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_write'); + late final _fl_write = + _fl_writePtr.asFunction)>(); + + int fl_close( + int flh, + ) { + return _fl_close( + flh, + ); + } + + late final _fl_closePtr = + _lookup>('fl_close'); + late final _fl_close = _fl_closePtr.asFunction(); + + int fl_ctrl( + int flh, + int param, + int value, + ) { + return _fl_ctrl( + flh, + param, + value, + ); + } + + late final _fl_ctrlPtr = _lookup< + ffi.NativeFunction>( + 'fl_ctrl'); + late final _fl_ctrl = _fl_ctrlPtr.asFunction(); + + int fl_free() { + return _fl_free(); + } + + late final _fl_freePtr = + _lookup>('fl_free'); + late final _fl_free = _fl_freePtr.asFunction(); +} + +abstract class FlCtrl { + static const int FL_CTRL_LAST_ERROR = 0; + static const int FL_CTRL_IS_PORT_OPEN = 1; + static const int FL_CTRL_BREAK = 2; + static const int FL_CTRL_SET_RTS = 3; + static const int FL_CTRL_GET_CTS = 4; + static const int FL_CTRL_SET_DTR = 5; + static const int FL_CTRL_GET_DSR = 6; + static const int FL_CTRL_SET_BYTESIZE_5 = 7; + static const int FL_CTRL_SET_BYTESIZE_6 = 8; + static const int FL_CTRL_SET_BYTESIZE_7 = 9; + static const int FL_CTRL_SET_BYTESIZE_8 = 10; + static const int FL_CTRL_SET_PARITY_NONE = 11; + static const int FL_CTRL_SET_PARITY_ODD = 12; + static const int FL_CTRL_SET_PARITY_EVEN = 13; + static const int FL_CTRL_SET_PARITY_MARK = 14; + static const int FL_CTRL_SET_PARITY_SPACE = 15; + static const int FL_CTRL_SET_STOPBITS_ONE = 16; + static const int FL_CTRL_SET_STOPBITS_TWO = 17; + static const int FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE = 18; + static const int FL_CTRL_SET_FLOWCONTROL_NONE = 19; + static const int FL_CTRL_SET_FLOWCONTROL_HARDWARE = 20; + static const int FL_CTRL_SET_FLOWCONTROL_SOFTWARE = 21; + static const int FL_CTRL_GET_STATUS_CHANGE = 22; + static const int FL_CTRL_LAST = 23; +} + +abstract class FlError { + static const int FL_ERROR_OK = 0; + static const int FL_ERROR_UNKNOW = 1; + static const int FL_ERROR_PORT_ALLREADY_OPEN = 2; + static const int FL_ERROR_PORT_NOT_EXIST = 3; + static const int FL_ERROR_IO = 4; + static const int FL_ERROR_HANDLER = 5; + static const int FL_ERROR_LAST = 6; +} + +typedef flcallback = ffi.Pointer>; +typedef flcallbackFunction = ffi.Void Function( + ffi.UnsignedInt, ffi.UnsignedInt); +typedef DartflcallbackFunction = void Function(int, int); + +const int MAX_PORT_NAME_LEN = 512; + +const int MAX_PORT_COUNT = 128; diff --git a/packages/flserial/lib/flserial_exception.dart b/packages/flserial/lib/flserial_exception.dart new file mode 100644 index 00000000..a05cbcce --- /dev/null +++ b/packages/flserial/lib/flserial_exception.dart @@ -0,0 +1,6 @@ +/// Exception class for serial port +class FlSerialException implements Exception { + FlSerialException(this.error, {required this.msg}); + final int error; + final String msg; +} diff --git a/packages/flserial/lib/main.dart b/packages/flserial/lib/main.dart new file mode 100644 index 00000000..23f84bc5 --- /dev/null +++ b/packages/flserial/lib/main.dart @@ -0,0 +1,2 @@ +export 'flserial_exception.dart'; +export 'flserial.dart'; diff --git a/packages/flserial/linux/CMakeLists.txt b/packages/flserial/linux/CMakeLists.txt new file mode 100644 index 00000000..1120a7f9 --- /dev/null +++ b/packages/flserial/linux/CMakeLists.txt @@ -0,0 +1,22 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "flserial") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(flserial_bundled_libraries + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + $ + PARENT_SCOPE +) diff --git a/packages/flserial/macos/Classes/flserial.cpp b/packages/flserial/macos/Classes/flserial.cpp new file mode 100644 index 00000000..cb4a955a --- /dev/null +++ b/packages/flserial/macos/Classes/flserial.cpp @@ -0,0 +1,419 @@ +#include "flserial.h" +#include "native_libs/include/serial/serial.h" +#include "native_libs/include/tinycthread.h" +#include "native_libs/include/ringbuffer.h" +#include +#include +#include +#include + +// Offband (#702/#710): the 8 KB ring overwrote the oldest bytes whenever the +// radio sent faster than Dart drained it, so a 52 KB contact sync arrived +// mostly lost. The ring is now 256 KB (a power of two, as the ring's mask +// needs), the thread never reads more than the ring has room for, and Dart is +// told about data during a burst rather than only when the port goes idle. +#define FL_SERIAL_BUFF_LEN (256 * 1024) +#define FL_SERIAL_READ_CHUNK (8 * 1024) +#define FL_NOTIFY_BYTES (4 * 1024) +#define FL_NOTIFY_INTERVAL std::chrono::milliseconds(10) + +typedef struct _flserial_ +{ + char portname[MAX_PORT_NAME_LEN + 1]; + int baudrate; + serial::Serial *serialport; + enum FlError lasterror; + char lasterrormsg[512]; + thrd_t cthread; + int breakThread; + ring_buffer_t cinfifo; + ring_buffer_t coutfifo; + char inbuff[FL_SERIAL_BUFF_LEN]; + char outbuff[FL_SERIAL_BUFF_LEN]; + mtx_t inFifo_mutex; + mtx_t outFifo_mutex; + flcallback callback; +} FlSerial; + +int SerialThread(void *aArg) +{ + FlSerial *serial = (FlSerial *)aArg; + ring_buffer_size_t res = 0; + uint8_t buff[FL_SERIAL_READ_CHUNK]; + ring_buffer_size_t len = sizeof(buff); + ring_buffer_size_t total = 0; + auto lastNotify = std::chrono::steady_clock::now(); + + while (!serial->breakThread) + { + try + { + // Read only what the ring can hold. When it is full, leave the + // bytes in the OS driver: USB flow control holds the sender, and + // nothing is overwritten. + mtx_lock(&serial->inFifo_mutex); + ring_buffer_size_t room = RING_BUFFER_MASK((&serial->cinfifo)) - + ring_buffer_num_items(&serial->cinfifo); + mtx_unlock(&serial->inFifo_mutex); + + res = 0; + if (room > 0) + { + res = (int)serial->serialport->read( + (uint8_t *)buff, (size_t)(std::min)(len, room)); + } + if (res > 0) + { + mtx_lock(&serial->inFifo_mutex); + ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res); + mtx_unlock(&serial->inFifo_mutex); + total += res; + } + + bool idle = !serial->serialport->available(); + auto now = std::chrono::steady_clock::now(); + if (total > 0 && + (idle || room == 0 || total >= FL_NOTIFY_BYTES || + now - lastNotify >= FL_NOTIFY_INTERVAL)) + { + serial->callback(0, (unsigned int)total); + total = 0; + lastNotify = now; + } + + if (room == 0) + { + // Give Dart time to drain before trying again. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + else if (res > 0 && !idle) + { + continue; + } + + mtx_lock(&serial->outFifo_mutex); + res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len); + mtx_unlock(&serial->outFifo_mutex); + if (res > 0) { + res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res); + } + + + } + catch (const serial::IOException &ioe) + { + serial->lasterror = FL_ERROR_IO; + strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1); + } + } + + return 0; +} + +FlSerial *flserial_tab[MAX_PORT_COUNT]; +int flserial_count; +int current_port; + +/// Internal helper: close a single slot and null it out. +/// Safe to call with a NULL entry — returns immediately. +/// Sets breakThread=1 then calls thrd_join() so the SerialThread is +/// guaranteed to have exited before this function returns. This is the +/// critical ordering that prevents the Dart NativeCallable from being +/// invoked after the isolate has freed it ("Callback invoked after it has +/// been deleted"). +static void _fl_close_slot(int slot) +{ + FlSerial *port = flserial_tab[slot]; + if (port == NULL) + return; + + port->breakThread = 1; + + try + { + if (port->cthread != 0) + thrd_join(port->cthread, NULL); + + port->serialport->close(); + + mtx_destroy(&port->inFifo_mutex); + mtx_destroy(&port->outFifo_mutex); + } + catch (const std::exception &) + { + } + + delete port->serialport; + port->serialport = NULL; + delete port; + flserial_tab[slot] = NULL; +} + +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb) +{ + FlSerial *port = flserial_tab[flh]; + port->callback = cb; + return 0; +} + +FFI_PLUGIN_EXPORT int fl_init(int portCount) +{ + if (portCount > MAX_PORT_COUNT) + return 1; + + flserial_count = portCount; + current_port = -1; + + return 0; +} + +FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) +{ + int porth = flh; + + if (porth < 0) + porth = ++current_port; + + // If a previous FlSerial (and its SerialThread) is alive in this slot, + // join and free it before overwriting. On Dart hot restart the isolate + // dies without calling fl_close(), leaving the old thread running with a + // dangling NativeCallable pointer. Joining here prevents the crash. + _fl_close_slot(porth); + + FlSerial *port = new FlSerial(); + port->breakThread = 0; + // Before anything can fail or start the reader thread: the thread locks + // inFifo_mutex on its first pass, and _fl_close_slot destroys both even + // when open() threw. + mtx_init(&port->inFifo_mutex, mtx_plain); + mtx_init(&port->outFifo_mutex, mtx_plain); + + flserial_tab[porth] = port; + + strncpy(port->portname, portname, MAX_PORT_NAME_LEN); + + port->baudrate = baudrate; + port->lasterror = FL_ERROR_OK; + + port->serialport = new serial::Serial(); +#if !defined(__linux__) && !defined(__APPLE__) + port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); +#endif // #if defined(__linux__) + port->serialport->setPort(portname); + port->serialport->setBaudrate(baudrate); + + try + { + port->serialport->open(); + + ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN ); + ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN ); + + port->serialport->setBytesize(serial::bytesize_t::eightbits); + port->serialport->setParity(serial::parity_t::parity_none); + port->serialport->setStopbits(serial::stopbits_one); + thrd_create(&port->cthread, SerialThread, (void *)port); + } + catch (const serial::IOException &ioe) + { + strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1); + + switch (ioe.getErrorNumber()) + { + case 1: + port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST; + break; + case 2: + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + break; + default: + port->lasterror = FlError::FL_ERROR_UNKNOW; + break; + } + } + catch (const std::exception) + { + port->lasterror = FlError::FL_ERROR_UNKNOW; + } + + return porth; +} + +FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff) +{ + auto list = serial::list_ports(); + if (serial::list_ports().size() <= index) + { + return 0; + } + else + { + serial::PortInfo info = list[index]; + return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str()); + } +} + +FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff) +{ + FlSerial *port = flserial_tab[flh]; + ring_buffer_size_t res = 0; + + char *buf = NULL; + ring_buffer_size_t size = 0; + ring_buffer_size_t read = 0; + + mtx_lock(&port->inFifo_mutex); + read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len); + mtx_unlock(&port->inFifo_mutex); + + return (int)read; +} + +FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data) +{ + FlSerial *port = flserial_tab[flh]; + int res = 0; + try + { + mtx_lock(&port->outFifo_mutex); + ring_buffer_queue_arr(&port->coutfifo, data, len); + mtx_unlock(&port->outFifo_mutex); + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + + return res; +} + +FFI_PLUGIN_EXPORT int fl_close(int flh) +{ + _fl_close_slot(flh); + return 0; +} + +FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value) +{ + + int result = -1; + FlSerial *port = flserial_tab[flh]; + + try + { + switch (param) + { + case FL_CTRL_IS_PORT_OPEN: + result = port->serialport->isOpen() ? 1 : 0; + break; + case FL_CTRL_LAST_ERROR: + result = port->lasterror; + break; + case FL_CTRL_BREAK: + port->serialport->setBreak(); + result = FL_ERROR_OK; + break; + case FL_CTRL_SET_RTS: + port->serialport->setRTS(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_CTS: + result = port->serialport->getCTS() ? 1 : 0; + break; + case FL_CTRL_SET_DTR: + port->serialport->setDTR(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_DSR: + result = port->serialport->getDSR() ? 1 : 0; + break; + + case FL_CTRL_SET_BYTESIZE_5: + port->serialport->setBytesize(serial::bytesize_t::fivebits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_6: + port->serialport->setBytesize(serial::bytesize_t::sixbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_7: + port->serialport->setBytesize(serial::bytesize_t::sevenbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_8: + port->serialport->setBytesize(serial::bytesize_t::eightbits); + result = 1; + break; + case FL_CTRL_SET_PARITY_NONE: + port->serialport->setParity(serial::parity_t::parity_none); + result = 1; + break; + case FL_CTRL_SET_PARITY_ODD: + port->serialport->setParity(serial::parity_t::parity_odd); + result = 1; + break; + case FL_CTRL_SET_PARITY_EVEN: + port->serialport->setParity(serial::parity_t::parity_even); + result = 1; + break; + case FL_CTRL_SET_PARITY_MARK: + port->serialport->setParity(serial::parity_t::parity_mark); + result = 1; + break; + case FL_CTRL_SET_PARITY_SPACE: + port->serialport->setParity(serial::parity_t::parity_space); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_TWO: + port->serialport->setStopbits(serial::stopbits_t::stopbits_two); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_NONE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_HARDWARE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware); + result = 1; + break; + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software); + result = 1; + case FL_CTRL_SET_FLOWCONTROL_SOFTWARE: + break; + case FL_CTRL_GET_STATUS_CHANGE: + port->serialport->waitForChange(); + result = 1; + break; + + default: + result = -1; + break; + } + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + return result; +} + +FFI_PLUGIN_EXPORT int fl_free(void) +{ + // Join every live SerialThread before the Dart isolate tears down on hot + // restart. Without this, threads holding freed NativeCallable pointers + // crash with "Callback invoked after it has been deleted". + for (int i = 0; i < MAX_PORT_COUNT; i++) + _fl_close_slot(i); + + flserial_count = 0; + current_port = -1; + return 0; +} diff --git a/packages/flserial/macos/Classes/flserial.h b/packages/flserial/macos/Classes/flserial.h new file mode 100644 index 00000000..edd8b7ef --- /dev/null +++ b/packages/flserial/macos/Classes/flserial.h @@ -0,0 +1,79 @@ +#include +#include +#include + +#if _WIN32 +#include +#else +#include +#include +#endif + +#if _WIN32 +#define FFI_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FFI_PLUGIN_EXPORT +#endif + + +#define MAX_PORT_FIFO_LEN 128*1024 +#define MAX_PORT_NAME_LEN 512 +#define MAX_PORT_COUNT 16 + +typedef enum FlCtrl { + FL_CTRL_LAST_ERROR, + FL_CTRL_IS_PORT_OPEN, + FL_CTRL_BREAK, + FL_CTRL_SET_RTS, + FL_CTRL_GET_CTS, + FL_CTRL_SET_DTR, + FL_CTRL_GET_DSR, + FL_CTRL_SET_BYTESIZE_5, + FL_CTRL_SET_BYTESIZE_6, + FL_CTRL_SET_BYTESIZE_7, + FL_CTRL_SET_BYTESIZE_8, + FL_CTRL_SET_PARITY_NONE, + FL_CTRL_SET_PARITY_ODD, + FL_CTRL_SET_PARITY_EVEN, + FL_CTRL_SET_PARITY_MARK, + FL_CTRL_SET_PARITY_SPACE, + FL_CTRL_SET_STOPBITS_ONE, + FL_CTRL_SET_STOPBITS_TWO, + FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, + FL_CTRL_SET_FLOWCONTROL_NONE, + FL_CTRL_SET_FLOWCONTROL_HARDWARE, + FL_CTRL_SET_FLOWCONTROL_SOFTWARE, + FL_CTRL_GET_STATUS_CHANGE, + FL_CTRL_LAST, +} FlCtrl; + +typedef enum FlError { + FL_ERROR_OK, + FL_ERROR_UNKNOW, + FL_ERROR_PORT_ALLREADY_OPEN, + FL_ERROR_PORT_NOT_EXIST, + FL_ERROR_IO, + FL_ERROR_HANDLER, + FL_ERROR_LAST, +} FlError; + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*flcallback)(unsigned int, unsigned int); + +FFI_PLUGIN_EXPORT int fl_init (int portCount); +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb); +FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff); +FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate); +FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff); +FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data); +FFI_PLUGIN_EXPORT int fl_close (int flh); +FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value); +FFI_PLUGIN_EXPORT int fl_free (void); + + +#ifdef __cplusplus +} +#endif diff --git a/packages/flserial/macos/Classes/native_libs/include/cglob.h b/packages/flserial/macos/Classes/native_libs/include/cglob.h new file mode 100644 index 00000000..8da8abd9 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/cglob.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)glob.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD$ + */ + +#ifndef _GLOB_H_ +#define _GLOB_H_ + +#include +#include + +#ifndef _SIZE_T_DECLARED +typedef size_t __size_t; +#define _SIZE_T_DECLARED +#endif + +struct stat; +typedef struct { + size_t gl_pathc; /* Count of total paths so far. */ + size_t gl_matchc; /* Count of paths matching pattern. */ + size_t gl_offs; /* Reserved at beginning of gl_pathv. */ + int gl_flags; /* Copy of flags parameter to glob. */ + char **gl_pathv; /* List of paths matching pattern. */ + /* Copy of errfunc parameter to glob. */ + int (*gl_errfunc)(const char *, int); + + /* + * Alternate filesystem access methods for glob; replacement + * versions of closedir(3), readdir(3), opendir(3), stat(2) + * and lstat(2). + */ + void (*gl_closedir)(void *); + struct dirent *(*gl_readdir)(void *); + void *(*gl_opendir)(const char *); + int (*gl_lstat)(const char *, struct stat *); + int (*gl_stat)(const char *, struct stat *); +} cglob_t; + + +/* Believed to have been introduced in 1003.2-1992 */ +#define GLOB_APPEND 0x0001 /* Append to output from previous call. */ +#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */ +#define GLOB_ERR 0x0004 /* Return on error. */ +#define GLOB_MARK 0x0008 /* Append / to matching directories. */ +#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */ +#define GLOB_NOSORT 0x0020 /* Don't sort. */ +#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */ + +/* Error values returned by glob(3) */ +#define GLOB_NOSPACE (-1) /* Malloc call failed. */ +#define GLOB_ABORTED (-2) /* Unignored error. */ +#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */ +#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */ + + + +#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */ +#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */ +#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */ +#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */ +#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */ +#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */ +#define GLOB_LIMIT 0x1000 /* limit number of returned paths */ + +/* source compatibility, these are the old names */ +#define GLOB_MAXPATH GLOB_LIMIT +#define GLOB_ABEND GLOB_ABORTED + +__BEGIN_DECLS +int cglob(const char *, int, int (*)(const char *, int), cglob_t *); +void cglobfree(cglob_t *); +__END_DECLS + +#endif /* !_GLOB_H_ */ diff --git a/packages/flserial/macos/Classes/native_libs/include/ringbuffer.h b/packages/flserial/macos/Classes/native_libs/include/ringbuffer.h new file mode 100644 index 00000000..36da6eb1 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/ringbuffer.h @@ -0,0 +1,144 @@ +#include +#include +#include +/** + * @file + * Prototypes and structures for the ring buffer module. + */ + +#ifndef RINGBUFFER_H +#define RINGBUFFER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RING_BUFFER_ASSERT(x) assert(x) + +/** + * Checks if the buffer_size is a power of two. + * Due to the design only RING_BUFFER_SIZE-1 items + * can be contained in the buffer. + * buffer_size must be a power of two. +*/ +#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0) + +/** + * The type which is used to hold the size + * and the indicies of the buffer. + */ +typedef size_t ring_buffer_size_t; + +/** + * Used as a modulo operator + * as a % b = (a & (b − 1)) + * where \c a is a positive index in the buffer and + * \c b is the (power of two) size of the buffer. + */ +#define RING_BUFFER_MASK(rb) (rb->buffer_mask) + +/** + * Simplifies the use of struct ring_buffer_t. + */ +typedef struct ring_buffer_t ring_buffer_t; + +/** + * Structure which holds a ring buffer. + * The buffer contains a buffer array + * as well as metadata for the ring buffer. + */ +struct ring_buffer_t { + /** Buffer memory. */ + char *buffer; + /** Buffer mask. */ + ring_buffer_size_t buffer_mask; + /** Index of tail. */ + ring_buffer_size_t tail_index; + /** Index of head. */ + ring_buffer_size_t head_index; +}; + +/** + * Initializes the ring buffer pointed to by buffer. + * This function can also be used to empty/reset the buffer. + * The resulting buffer can contain buf_size-1 bytes. + * @param buffer The ring buffer to initialize. + * @param buf The buffer allocated for the ringbuffer. + * @param buf_size The size of the allocated ringbuffer. + */ +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size); + +/** + * Adds a byte to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data The byte to place. + */ +void ring_buffer_queue(ring_buffer_t *buffer, char data); + +/** + * Adds an array of bytes to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data A pointer to the array of bytes to place in the queue. + * @param size The size of the array. + */ +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size); + +/** + * Returns the oldest byte in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data); + +/** + * Returns the len oldest bytes in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the array at which the data should be placed. + * @param len The maximum number of bytes to return. + * @return The number of bytes returned. + */ +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len); +/** + * Peeks a ring buffer, i.e. returns an element without removing it. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @param index The index to peek. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index); + + +/** + * Returns whether a ring buffer is empty. + * @param buffer The buffer for which it should be returned whether it is empty. + * @return 1 if empty; 0 otherwise. + */ +inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) { + return (buffer->head_index == buffer->tail_index); +} + +/** + * Returns whether a ring buffer is full. + * @param buffer The buffer for which it should be returned whether it is full. + * @return 1 if full; 0 otherwise. + */ +inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer); +} + +/** + * Returns the number of items in a ring buffer. + * @param buffer The buffer for which the number of items should be returned. + * @return The number of items in the ring buffer. + */ +inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)); +} + +#ifdef __cplusplus +} +#endif + +#endif /* RINGBUFFER_H */ diff --git a/packages/flserial/macos/Classes/native_libs/include/serial/impl/unix.h b/packages/flserial/macos/Classes/native_libs/include/serial/impl/unix.h new file mode 100644 index 00000000..02d85e9d --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/serial/impl/unix.h @@ -0,0 +1,221 @@ +/*! + * \file serial/impl/unix.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a unix based pimpl for the Serial class. This implementation is + * based off termios.h and uses select for multiplexing the IO ports. + * + */ + +#if !defined(_WIN32) + +#ifndef SERIAL_IMPL_UNIX_H +#define SERIAL_IMPL_UNIX_H + +#include "../../../include/serial/serial.h" + +#include + +namespace serial { + +using std::size_t; +using std::string; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class MillisecondTimer { +public: + MillisecondTimer(const uint32_t millis); + int64_t remaining(); + +private: + static timespec timespec_now(); + timespec expiry; +}; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + string port_; // Path to the file descriptor + int fd_; // The current file descriptor + + bool is_open_; + bool xonxoff_; + bool rtscts_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + pthread_mutex_t read_mutex; + // Mutex used to lock the write functions + pthread_mutex_t write_mutex; +}; + +} + +#endif // SERIAL_IMPL_UNIX_H + +#endif // !defined(_WIN32) diff --git a/packages/flserial/macos/Classes/native_libs/include/serial/impl/win.h b/packages/flserial/macos/Classes/native_libs/include/serial/impl/win.h new file mode 100644 index 00000000..2c0c6cde --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/serial/impl/win.h @@ -0,0 +1,207 @@ +/*! + * \file serial/impl/windows.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a windows implementation of the Serial class interface. + * + */ + +#if defined(_WIN32) + +#ifndef SERIAL_IMPL_WINDOWS_H +#define SERIAL_IMPL_WINDOWS_H + +#include "serial/serial.h" + +#include "windows.h" + +namespace serial { + +using std::string; +using std::wstring; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + wstring port_; // Path to the file descriptor + HANDLE fd_; + + bool is_open_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + HANDLE read_mutex; + // Mutex used to lock the write functions + HANDLE write_mutex; +}; + +} + +#endif // SERIAL_IMPL_WINDOWS_H + +#endif // if defined(_WIN32) diff --git a/packages/flserial/macos/Classes/native_libs/include/serial/serial.h b/packages/flserial/macos/Classes/native_libs/include/serial/serial.h new file mode 100644 index 00000000..642febf3 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/serial/serial.h @@ -0,0 +1,780 @@ +/*! + * \file serial/serial.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a cross platform interface for interacting with Serial Ports. + */ + +#ifndef SERIAL_H +#define SERIAL_H + +#include +#include +#include +#include +#include +#include +#include +#include "v8stdint.h" + + + +#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \ +__LINE__, (message), (errorno) ) + +#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \ +__LINE__, (message) ) + +namespace serial { + +/*! + * Enumeration defines the possible bytesizes for the serial port. + */ +typedef enum { + fivebits = 5, + sixbits = 6, + sevenbits = 7, + eightbits = 8 +} bytesize_t; + +/*! + * Enumeration defines the possible parity types for the serial port. + */ +typedef enum { + parity_none = 0, + parity_odd = 1, + parity_even = 2, + parity_mark = 3, + parity_space = 4 +} parity_t; + +/*! + * Enumeration defines the possible stopbit types for the serial port. + */ +typedef enum { + stopbits_one = 1, + stopbits_two = 2, + stopbits_one_point_five +} stopbits_t; + +/*! + * Enumeration defines the possible flowcontrol types for the serial port. + */ +typedef enum { + flowcontrol_none = 0, + flowcontrol_software, + flowcontrol_hardware +} flowcontrol_t; + +/*! + * Structure for setting the timeout of the serial port, times are + * in milliseconds. + * + * In order to disable the interbyte timeout, set it to Timeout::max(). + */ +struct Timeout { +#ifdef max +# undef max +#endif + static uint32_t max() {return std::numeric_limits::max();} + /*! + * Convenience function to generate Timeout structs using a + * single absolute timeout. + * + * \param timeout A long that defines the time in milliseconds until a + * timeout occurs after a call to read or write is made. + * + * \return Timeout struct that represents this simple timeout provided. + */ + static Timeout simpleTimeout(uint32_t timeout) { + return Timeout(10, timeout, 0, timeout, 0); + } + + /*! Number of milliseconds between bytes received to timeout on. */ + uint32_t inter_byte_timeout; + /*! A constant number of milliseconds to wait after calling read. */ + uint32_t read_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling read. + */ + uint32_t read_timeout_multiplier; + /*! A constant number of milliseconds to wait after calling write. */ + uint32_t write_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling write. + */ + uint32_t write_timeout_multiplier; + + explicit Timeout (uint32_t inter_byte_timeout_=0, + uint32_t read_timeout_constant_=0, + uint32_t read_timeout_multiplier_=0, + uint32_t write_timeout_constant_=0, + uint32_t write_timeout_multiplier_=0) + : inter_byte_timeout(inter_byte_timeout_), + read_timeout_constant(read_timeout_constant_), + read_timeout_multiplier(read_timeout_multiplier_), + write_timeout_constant(write_timeout_constant_), + write_timeout_multiplier(write_timeout_multiplier_) + {} +}; + +/*! + * Class that provides a portable serial port interface. + */ +class Serial { +public: + /*! + * Creates a Serial object and opens the port if a port is specified, + * otherwise it remains closed until serial::Serial::open is called. + * + * \param port A std::string containing the address of the serial port, + * which would be something like 'COM1' on Windows and '/dev/ttyS0' + * on Linux. + * + * \param baudrate An unsigned 32-bit integer that represents the baudrate + * + * \param timeout A serial::Timeout struct that defines the timeout + * conditions for the serial port. \see serial::Timeout + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \param flowcontrol Type of flowcontrol used, default is + * flowcontrol_none, possible values are: flowcontrol_none, + * flowcontrol_software, flowcontrol_hardware + * + * \throw serial::PortNotOpenedException + * \throw serial::IOException + * \throw std::invalid_argument + */ + Serial (const std::string &port = "", + uint32_t baudrate = 9600, + Timeout timeout = Timeout(), + bytesize_t bytesize = eightbits, + parity_t parity = parity_none, + stopbits_t stopbits = stopbits_one, + flowcontrol_t flowcontrol = flowcontrol_none); + + /*! Destructor */ + virtual ~Serial (); + + /*! + * Opens the serial port as long as the port is set and the port isn't + * already open. + * + * If the port is provided to the constructor then an explicit call to open + * is not needed. + * + * \see Serial::Serial + * + * \throw std::invalid_argument + * \throw serial::SerialException + * \throw serial::IOException + */ + void + open (); + + /*! Gets the open status of the serial port. + * + * \return Returns true if the port is open, false otherwise. + */ + bool + isOpen () const; + + /*! Closes the serial port. */ + void + close (); + + /*! Return the number of characters in the buffer. */ + size_t + available (); + + /*! Block until there is serial data to read or read_timeout_constant + * number of milliseconds have elapsed. The return value is true when + * the function exits with the port in a readable state, false otherwise + * (due to timeout or select interruption). */ + bool + waitReadable (); + + /*! Block for a period of time corresponding to the transmission time of + * count characters at present serial settings. This may be used in con- + * junction with waitReadable to read larger blocks of data from the + * port. */ + void + waitByteTimes (size_t count); + + /*! Read a given amount of bytes from the serial port into a given buffer. + * + * The read function will return in one of three cases: + * * The number of requested bytes was read. + * * In this case the number of bytes requested will match the size_t + * returned by read. + * * A timeout occurred, in this case the number of bytes read will not + * match the amount requested, but no exception will be thrown. One of + * two possible timeouts occurred: + * * The inter byte timeout expired, this means that number of + * milliseconds elapsed between receiving bytes from the serial port + * exceeded the inter byte timeout. + * * The total timeout expired, which is calculated by multiplying the + * read timeout multiplier by the number of requested bytes and then + * added to the read timeout constant. If that total number of + * milliseconds elapses after the initial call to read a timeout will + * occur. + * * An exception occurred, in this case an actual exception will be thrown. + * + * \param buffer An uint8_t array of at least the requested size. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (uint8_t *buffer, size_t size); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::vector of uint8_t. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::vector &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::string. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::string &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port and return a string + * containing the data. + * + * \param size A size_t defining how many bytes to be read. + * + * \return A std::string containing the data read from the port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + read (size_t size = 1); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param buffer A std::string reference used to store the data. + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A size_t representing the number of bytes read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A std::string containing the line. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + readline (size_t size = 65536, std::string eol = "\n"); + + /*! Reads in multiple lines until the serial port times out. + * + * This requires a timeout > 0 before it can be run. It will read until a + * timeout occurs and return a list of strings. + * + * \param size A maximum length of combined lines, defaults to 65536 (2^16) + * + * \param eol A string to match against for the EOL. + * + * \return A vector containing the lines. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::vector + readlines (size_t size = 65536, std::string eol = "\n"); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \param size A size_t that indicates how many bytes should be written from + * the given data buffer. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const uint8_t *data, size_t size); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::vector &data); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::string &data); + + /*! Sets the serial port identifier. + * + * \param port A const std::string reference containing the address of the + * serial port, which would be something like 'COM1' on Windows and + * '/dev/ttyS0' on Linux. + * + * \throw std::invalid_argument + */ + void + setPort (const std::string &port); + + /*! Gets the serial port identifier. + * + * \see Serial::setPort + * + * \throw std::invalid_argument + */ + std::string + getPort () const; + + /*! Sets the timeout for reads and writes using the Timeout struct. + * + * There are two timeout conditions described here: + * * The inter byte timeout: + * * The inter_byte_timeout component of serial::Timeout defines the + * maximum amount of time, in milliseconds, between receiving bytes on + * the serial port that can pass before a timeout occurs. Setting this + * to zero will prevent inter byte timeouts from occurring. + * * Total time timeout: + * * The constant and multiplier component of this timeout condition, + * for both read and write, are defined in serial::Timeout. This + * timeout occurs if the total time since the read or write call was + * made exceeds the specified time in milliseconds. + * * The limit is defined by multiplying the multiplier component by the + * number of requested bytes and adding that product to the constant + * component. In this way if you want a read call, for example, to + * timeout after exactly one second regardless of the number of bytes + * you asked for then set the read_timeout_constant component of + * serial::Timeout to 1000 and the read_timeout_multiplier to zero. + * This timeout condition can be used in conjunction with the inter + * byte timeout condition with out any problems, timeout will simply + * occur when one of the two timeout conditions is met. This allows + * users to have maximum control over the trade-off between + * responsiveness and efficiency. + * + * Read and write functions will return in one of three cases. When the + * reading or writing is complete, when a timeout occurs, or when an + * exception occurs. + * + * A timeout of 0 enables non-blocking mode. + * + * \param timeout A serial::Timeout struct containing the inter byte + * timeout, and the read and write timeout constants and multipliers. + * + * \see serial::Timeout + */ + void + setTimeout (Timeout &timeout); + + /*! Sets the timeout for reads and writes. */ + void + setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, + uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, + uint32_t write_timeout_multiplier) + { + Timeout timeout(inter_byte_timeout, read_timeout_constant, + read_timeout_multiplier, write_timeout_constant, + write_timeout_multiplier); + return setTimeout(timeout); + } + + /*! Gets the timeout for reads in seconds. + * + * \return A Timeout struct containing the inter_byte_timeout, and read + * and write timeout constants and multipliers. + * + * \see Serial::setTimeout + */ + Timeout + getTimeout () const; + + /*! Sets the baudrate for the serial port. + * + * Possible baudrates depends on the system but some safe baudrates include: + * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, + * 57600, 115200 + * Some other baudrates that are supported by some comports: + * 128000, 153600, 230400, 256000, 460800, 500000, 921600 + * + * \param baudrate An integer that sets the baud rate for the serial port. + * + * \throw std::invalid_argument + */ + void + setBaudrate (uint32_t baudrate); + + /*! Gets the baudrate for the serial port. + * + * \return An integer that sets the baud rate for the serial port. + * + * \see Serial::setBaudrate + * + * \throw std::invalid_argument + */ + uint32_t + getBaudrate () const; + + /*! Sets the bytesize for the serial port. + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \throw std::invalid_argument + */ + void + setBytesize (bytesize_t bytesize); + + /*! Gets the bytesize for the serial port. + * + * \see Serial::setBytesize + * + * \throw std::invalid_argument + */ + bytesize_t + getBytesize () const; + + /*! Sets the parity for the serial port. + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \throw std::invalid_argument + */ + void + setParity (parity_t parity); + + /*! Gets the parity for the serial port. + * + * \see Serial::setParity + * + * \throw std::invalid_argument + */ + parity_t + getParity () const; + + /*! Sets the stopbits for the serial port. + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \throw std::invalid_argument + */ + void + setStopbits (stopbits_t stopbits); + + /*! Gets the stopbits for the serial port. + * + * \see Serial::setStopbits + * + * \throw std::invalid_argument + */ + stopbits_t + getStopbits () const; + + /*! Sets the flow control for the serial port. + * + * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, + * possible values are: flowcontrol_none, flowcontrol_software, + * flowcontrol_hardware + * + * \throw std::invalid_argument + */ + void + setFlowcontrol (flowcontrol_t flowcontrol); + + /*! Gets the flow control for the serial port. + * + * \see Serial::setFlowcontrol + * + * \throw std::invalid_argument + */ + flowcontrol_t + getFlowcontrol () const; + + /*! Flush the input and output buffers */ + void + flush (); + + /*! Flush only the input buffer */ + void + flushInput (); + + /*! Flush only the output buffer */ + void + flushOutput (); + + /*! Sends the RS-232 break signal. See tcsendbreak(3). */ + void + sendBreak (int duration); + + /*! Set the break condition to a given level. Defaults to true. */ + void + setBreak (bool level = true); + + /*! Set the RTS handshaking line to the given level. Defaults to true. */ + void + setRTS (bool level = true); + + /*! Set the DTR handshaking line to the given level. Defaults to true. */ + void + setDTR (bool level = true); + + /*! + * Blocks until CTS, DSR, RI, CD changes or something interrupts it. + * + * Can throw an exception if an error occurs while waiting. + * You can check the status of CTS, DSR, RI, and CD once this returns. + * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a + * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a + * polling method is used which can give +-2ms. + * + * \return Returns true if one of the lines changed, false if something else + * occurred. + * + * \throw SerialException + */ + bool + waitForChange (); + + /*! Returns the current status of the CTS line. */ + bool + getCTS (); + + /*! Returns the current status of the DSR line. */ + bool + getDSR (); + + /*! Returns the current status of the RI line. */ + bool + getRI (); + + /*! Returns the current status of the CD line. */ + bool + getCD (); + +private: + // Disable copy constructors + Serial(const Serial&); + Serial& operator=(const Serial&); + + // Pimpl idiom, d_pointer + class SerialImpl; + SerialImpl *pimpl_; + + // Scoped Lock Classes + class ScopedReadLock; + class ScopedWriteLock; + + // Read common function + size_t + read_ (uint8_t *buffer, size_t size); + // Write common function + size_t + write_ (const uint8_t *data, size_t length); + +}; + +class SerialException : public std::exception +{ + // Disable copy constructors + SerialException& operator=(const SerialException&); + std::string e_what_; +public: + SerialException (const char *description) { + std::stringstream ss; + ss << "SerialException " << description << " failed."; + e_what_ = ss.str(); + } + SerialException (const SerialException& other) : e_what_(other.e_what_) {} + virtual ~SerialException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class IOException : public std::exception +{ + // Disable copy constructors + IOException& operator=(const IOException&); + std::string file_; + int line_; + std::string e_what_; + int errno_; +public: + explicit IOException (std::string file, int line, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; +#if defined(_WIN32) && !defined(__MINGW32__) + char error_str [1024]; + strerror_s(error_str, 1024, errnum); +#else + char * error_str = strerror(errnum); +#endif + ss << "IO Exception (" << errno_ << "): " << error_str; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + explicit IOException (std::string file, int line, const char * description, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; + ss << "IO Exception: " << description; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + virtual ~IOException() throw() {} + IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} + + int getErrorNumber () const { return errno_; } + + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class PortNotOpenedException : public std::exception +{ + // Disable copy constructors + const PortNotOpenedException& operator=(PortNotOpenedException); + std::string e_what_; +public: + PortNotOpenedException (const char * description) { + std::stringstream ss; + ss << "PortNotOpenedException " << description << " failed."; + e_what_ = ss.str(); + } + PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} + virtual ~PortNotOpenedException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +/*! + * Structure that describes a serial device. + */ +struct PortInfo { + + /*! Address of the serial port (this can be passed to the constructor of Serial). */ + std::string port; + + /*! Human readable description of serial device if available. */ + std::string description; + + /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ + std::string hardware_id; + +}; + +/* Lists the serial ports available on the system + * + * Returns a vector of available serial ports, each represented + * by a serial::PortInfo data structure: + * + * \return vector of serial::PortInfo. + */ +std::vector +list_ports(); + +} // namespace serial + +#endif diff --git a/packages/flserial/macos/Classes/native_libs/include/serial/v8stdint.h b/packages/flserial/macos/Classes/native_libs/include/serial/v8stdint.h new file mode 100644 index 00000000..f3be96b1 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/serial/v8stdint.h @@ -0,0 +1,57 @@ +// This header is from the v8 google project: +// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h + +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Load definitions of standard types. + +#ifndef V8STDINT_H_ +#define V8STDINT_H_ + +#include +#include + +#if defined(_WIN32) && !defined(__MINGW32__) + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; // NOLINT +typedef unsigned short uint16_t; // NOLINT +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +// intptr_t and friends are defined in crtdefs.h through stdio.h. + +#else + +#include + +#endif + +#endif // V8STDINT_H_ diff --git a/packages/flserial/macos/Classes/native_libs/include/tinycthread.h b/packages/flserial/macos/Classes/native_libs/include/tinycthread.h new file mode 100644 index 00000000..2fc7f628 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/include/tinycthread.h @@ -0,0 +1,479 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef _TINYCTHREAD_H_ +#define _TINYCTHREAD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @file +* @mainpage TinyCThread API Reference +* +* @section intro_sec Introduction +* TinyCThread is a minimal, portable implementation of basic threading +* classes for C. +* +* They closely mimic the functionality and naming of the C11 standard, and +* should be easily replaceable with the corresponding standard variants. +* +* @section port_sec Portability +* The Win32 variant uses the native Win32 API for implementing the thread +* classes, while for other systems, the POSIX threads API (pthread) is used. +* +* @section misc_sec Miscellaneous +* The following special keywords are available: #_Thread_local. +* +* For more detailed information, browse the different sections of this +* documentation. A good place to start is: +* tinycthread.h. +*/ + +/* Which platform are we on? */ +#if !defined(_TTHREAD_PLATFORM_DEFINED_) + #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) + #define _TTHREAD_WIN32_ + #else + #define _TTHREAD_POSIX_ + #endif + #define _TTHREAD_PLATFORM_DEFINED_ +#endif + +/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */ +#if defined(_TTHREAD_POSIX_) + #undef _FEATURES_H + #if !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L) + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L + #endif + #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500) + #undef _XOPEN_SOURCE + #define _XOPEN_SOURCE 500 + #endif + #define _XPG6 +#endif + +/* Generic includes */ +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include +#elif defined(_TTHREAD_WIN32_) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #define __UNDEF_LEAN_AND_MEAN + #endif + #include + #ifdef __UNDEF_LEAN_AND_MEAN + #undef WIN32_LEAN_AND_MEAN + #undef __UNDEF_LEAN_AND_MEAN + #endif +#endif + +/* Compiler-specific information */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define TTHREAD_NORETURN _Noreturn +#elif defined(__GNUC__) + #define TTHREAD_NORETURN __attribute__((__noreturn__)) +#else + #define TTHREAD_NORETURN +#endif + +/* If TIME_UTC is missing, provide it and provide a wrapper for + timespec_get. */ +#ifndef TIME_UTC +#define TIME_UTC 1 +#define _TTHREAD_EMULATE_TIMESPEC_GET_ + +#if defined(_TTHREAD_WIN32_) +struct _tthread_timespec { + time_t tv_sec; + long tv_nsec; +}; +#define timespec _tthread_timespec +#endif + +int _tthread_timespec_get(struct timespec *ts, int base); +#define timespec_get _tthread_timespec_get +#endif + +/** TinyCThread version (major number). */ +#define TINYCTHREAD_VERSION_MAJOR 1 +/** TinyCThread version (minor number). */ +#define TINYCTHREAD_VERSION_MINOR 2 +/** TinyCThread version (full version). */ +#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) + +/** +* @def _Thread_local +* Thread local storage keyword. +* A variable that is declared with the @c _Thread_local keyword makes the +* value of the variable local to each thread (known as thread-local storage, +* or TLS). Example usage: +* @code +* // This variable is local to each thread. +* _Thread_local int variable; +* @endcode +* @note The @c _Thread_local keyword is a macro that maps to the corresponding +* compiler directive (e.g. @c __declspec(thread)). +* @note This directive is currently not supported on Mac OS X (it will give +* a compiler error), since compile-time TLS is not supported in the Mac OS X +* executable format. Also, some older versions of MinGW (before GCC 4.x) do +* not support this directive, nor does the Tiny C Compiler. +* @hideinitializer +*/ + +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) + #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) + #define _Thread_local __thread + #else + #define _Thread_local __declspec(thread) + #endif +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9)) + #define _Thread_local __thread +#endif + +/* Macros */ +#if defined(_TTHREAD_WIN32_) +#define TSS_DTOR_ITERATIONS (4) +#else +#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS +#endif + +/* Function return values */ +#define thrd_error 0 /**< The requested operation failed */ +#define thrd_success 1 /**< The requested operation succeeded */ +#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */ +#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ +#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ + +/* Mutex types */ +#define mtx_plain 0 +#define mtx_timed 1 +#define mtx_recursive 2 + +/* Mutex */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + union { + CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */ + HANDLE mut; /* Mutex handle (used for timed mutex) */ + } mHandle; /* Mutex handle */ + int mAlreadyLocked; /* TRUE if the mutex is already locked */ + int mRecursive; /* TRUE if the mutex is recursive */ + int mTimed; /* TRUE if the mutex is timed */ +} mtx_t; +#else +typedef pthread_mutex_t mtx_t; +#endif + +/** Create a mutex object. +* @param mtx A mutex object. +* @param type Bit-mask that must have one of the following six values: +* @li @c mtx_plain for a simple non-recursive mutex +* @li @c mtx_timed for a non-recursive mutex that supports timeout +* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) +* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_init(mtx_t *mtx, int type); + +/** Release any resources used by the given mutex. +* @param mtx A mutex object. +*/ +void mtx_destroy(mtx_t *mtx); + +/** Lock the given mutex. +* Blocks until the given mutex can be locked. If the mutex is non-recursive, and +* the calling thread already has a lock on the mutex, this call will block +* forever. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_lock(mtx_t *mtx); + +/** Lock the given mutex, or block until a specific point in time. +* Blocks until either the given mutex can be locked, or the specified TIME_UTC +* based time. +* @param mtx A mutex object. +* @param ts A UTC based calendar time +* @return @ref The mtx_timedlock function returns thrd_success on success, or +* thrd_timedout if the time specified was reached without acquiring the +* requested resource, or thrd_error if the request could not be honored. +*/ +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); + +/** Try to lock the given mutex. +* The specified mutex shall support either test and return or timeout. If the +* mutex is already locked, the function returns without blocking. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_busy if the resource +* requested is already in use, or @ref thrd_error if the request could not be +* honored. +*/ +int mtx_trylock(mtx_t *mtx); + +/** Unlock the given mutex. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_unlock(mtx_t *mtx); + +/* Condition variable */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */ + unsigned int mWaitersCount; /* Count of the number of waiters. */ + CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */ +} cnd_t; +#else +typedef pthread_cond_t cnd_t; +#endif + +/** Create a condition variable object. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_init(cnd_t *cond); + +/** Release any resources used by the given condition variable. +* @param cond A condition variable object. +*/ +void cnd_destroy(cnd_t *cond); + +/** Signal a condition variable. +* Unblocks one of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_signal(cnd_t *cond); + +/** Broadcast a condition variable. +* Unblocks all of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_broadcast(cnd_t *cond); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex +* before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_wait(cnd_t *cond, mtx_t *mtx); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast, or until after the specified time. When the calling thread +* becomes unblocked it locks the mutex before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @param xt A point in time at which the request will time out (absolute time). +* @return @ref thrd_success upon success, or @ref thrd_timeout if the time +* specified in the call was reached without acquiring the requested resource, or +* @ref thrd_error if the request could not be honored. +*/ +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts); + +/* Thread */ +#if defined(_TTHREAD_WIN32_) +typedef HANDLE thrd_t; +#else +typedef pthread_t thrd_t; +#endif + +/** Thread start function. +* Any thread that is started with the @ref thrd_create() function must be +* started through a function of this type. +* @param arg The thread argument (the @c arg argument of the corresponding +* @ref thrd_create() call). +* @return The thread return value, which can be obtained by another thread +* by using the @ref thrd_join() function. +*/ +typedef int (*thrd_start_t)(void *arg); + +/** Create a new thread. +* @param thr Identifier of the newly created thread. +* @param func A function pointer to the function that will be executed in +* the new thread. +* @param arg An argument to the thread function. +* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could +* be allocated for the thread requested, or @ref thrd_error if the request +* could not be honored. +* @note A thread’s identifier may be reused for a different thread once the +* original thread has exited and either been detached or joined to another +* thread. +*/ +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); + +/** Identify the calling thread. +* @return The identifier of the calling thread. +*/ +thrd_t thrd_current(void); + +/** Dispose of any resources allocated to the thread when that thread exits. + * @return thrd_success, or thrd_error on error +*/ +int thrd_detach(thrd_t thr); + +/** Compare two thread identifiers. +* The function determines if two thread identifiers refer to the same thread. +* @return Zero if the two thread identifiers refer to different threads. +* Otherwise a nonzero value is returned. +*/ +int thrd_equal(thrd_t thr0, thrd_t thr1); + +/** Terminate execution of the calling thread. +* @param res Result code of the calling thread. +*/ +TTHREAD_NORETURN void thrd_exit(int res); + +/** Wait for a thread to terminate. +* The function joins the given thread with the current thread by blocking +* until the other thread has terminated. +* @param thr The thread to join with. +* @param res If this pointer is not NULL, the function will store the result +* code of the given thread in the integer pointed to by @c res. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int thrd_join(thrd_t thr, int *res); + +/** Put the calling thread to sleep. +* Suspend execution of the calling thread. +* @param duration Interval to sleep for +* @param remaining If non-NULL, this parameter will hold the remaining +* time until time_point upon return. This will +* typically be zero, but if the thread was woken up +* by a signal that is not ignored before duration was +* reached @c remaining will hold a positive time. +* @return 0 (zero) on successful sleep, -1 if an interrupt occurred, +* or a negative value if the operation fails. +*/ +int thrd_sleep(const struct timespec *duration, struct timespec *remaining); + +/** Yield execution to another thread. +* Permit other threads to run, even if the current thread would ordinarily +* continue to run. +*/ +void thrd_yield(void); + +/* Thread local storage */ +#if defined(_TTHREAD_WIN32_) +typedef DWORD tss_t; +#else +typedef pthread_key_t tss_t; +#endif + +/** Destructor function for a thread-specific storage. +* @param val The value of the destructed thread-specific storage. +*/ +typedef void (*tss_dtor_t)(void *val); + +/** Create a thread-specific storage. +* @param key The unique key identifier that will be set if the function is +* successful. +* @param dtor Destructor function. This can be NULL. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +* @note On Windows, the @c dtor will definitely be called when +* appropriate for threads created with @ref thrd_create. It will be +* called for other threads in most cases, the possible exception being +* for DLLs loaded with LoadLibraryEx. In order to be certain, you +* should use @ref thrd_create whenever possible. +*/ +int tss_create(tss_t *key, tss_dtor_t dtor); + +/** Delete a thread-specific storage. +* The function releases any resources used by the given thread-specific +* storage. +* @param key The key that shall be deleted. +*/ +void tss_delete(tss_t key); + +/** Get the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @return The value for the current thread held in the given thread-specific +* storage. +*/ +void *tss_get(tss_t key); + +/** Set the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @param val The value of the thread-specific storage to set for the current +* thread. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int tss_set(tss_t key, void *val); + +#if defined(_TTHREAD_WIN32_) + typedef struct { + LONG volatile status; + CRITICAL_SECTION lock; + } once_flag; + #define ONCE_FLAG_INIT {0,} +#else + #define once_flag pthread_once_t + #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT +#endif + +/** Invoke a callback exactly once + * @param flag Flag used to ensure the callback is invoked exactly + * once. + * @param func Callback to invoke. + */ +#if defined(_TTHREAD_WIN32_) + void call_once(once_flag *flag, void (*func)(void)); +#else + #define call_once(flag,func) pthread_once(flag,func) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TINYTHREAD_H_ */ diff --git a/packages/flserial/macos/Classes/native_libs/src/LICENSE_glob b/packages/flserial/macos/Classes/native_libs/src/LICENSE_glob new file mode 100644 index 00000000..32eeff77 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/LICENSE_glob @@ -0,0 +1,34 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ diff --git a/packages/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer b/packages/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer new file mode 100644 index 00000000..4e5491e4 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Kalør + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/flserial/macos/Classes/native_libs/src/LICENSE_serial b/packages/flserial/macos/Classes/native_libs/src/LICENSE_serial new file mode 100644 index 00000000..bd087f8d --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/LICENSE_serial @@ -0,0 +1,7 @@ +Copyright (c) 2012 William Woodall, John Harrison + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread b/packages/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread new file mode 100644 index 00000000..d24cfe88 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread @@ -0,0 +1,25 @@ + +License +------- + +Copyright (c) 2012 Marcus Geelnard + 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. diff --git a/packages/flserial/macos/Classes/native_libs/src/cglob.c b/packages/flserial/macos/Classes/native_libs/src/cglob.c new file mode 100644 index 00000000..7903dbc4 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/cglob.c @@ -0,0 +1,908 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +/* + * glob(3) -- a superset of the one defined in POSIX 1003.2. + * + * The [!...] convention to negate a range is supported (SysV, Posix, ksh). + * + * Optional extra services, controlled by flags not defined by POSIX: + * + * GLOB_QUOTE: + * Escaping convention: \ inhibits any special meaning the following + * character might have (except \ at end of string is retained). + * GLOB_MAGCHAR: + * Set in gl_flags if pattern contained a globbing character. + * GLOB_NOMAGIC: + * Same as GLOB_NOCHECK, but it will only append pattern if it did + * not contain any magic characters. [Used in csh style globbing] + * GLOB_ALTDIRFUNC: + * Use alternately specified directory access functions. + * GLOB_TILDE: + * expand ~user/foo to the /home/dir/of/user/foo + * GLOB_BRACE: + * expand {1,2}{a,b} to 1a 1b 2a 2b + * gl_matchc: + * Number of matches in the current invocation of glob. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing - even if + * GLOB_NOCHECK is specified. + * 2. Illegal byte sequences in filenames are handled by treating them as + * single-byte characters with a value of the first byte of the sequence + * cast to wchar_t. + * 3. State-dependent encodings are not currently supported. + */ + +#include +#include + +#include +#include +#include +#include "cglob.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define DOLLAR '$' +#define DOT '.' +#define EOS '\0' +#define LBRACKET '[' +#define NOT '!' +#define QUESTION '?' +#define QUOTE '\\' +#define RANGE '-' +#define RBRACKET ']' +#define SEP '/' +#define STAR '*' +#define TILDE '~' +#define UNDERSCORE '_' +#define LBRACE '{' +#define RBRACE '}' +#define SLASH '/' +#define COMMA ',' + +#ifndef DEBUG + +#define M_QUOTE 0x8000000000ULL +#define M_PROTECT 0x4000000000ULL +#define M_MASK 0xffffffffffULL +#define M_CHAR 0x00ffffffffULL + +typedef uint_fast64_t Char; + +#else + +#define M_QUOTE 0x80 +#define M_PROTECT 0x40 +#define M_MASK 0xff +#define M_CHAR 0x7f + +typedef char Char; + +#endif + + +#define CHAR(c) ((Char)((c)&M_CHAR)) +#define META(c) ((Char)((c)|M_QUOTE)) +#define M_ALL META('*') +#define M_END META(']') +#define M_NOT META('!') +#define M_ONE META('?') +#define M_RNG META('-') +#define M_SET META('[') +#define ismeta(c) (((c)&M_QUOTE) != 0) + + +static int compare(const void *, const void *); +static int g_Ctoc(const Char *, char *, size_t); +static int g_lstat(Char *, struct stat *, cglob_t *); +static DIR *g_opendir(Char *, cglob_t *); +static const Char *g_strchr(const Char *, wchar_t); +#ifdef notdef +static Char *g_strcat(Char *, const Char *); +#endif +static int g_stat(Char *, struct stat *, cglob_t *); +static int glob0(const Char *, cglob_t *, size_t *); +static int glob1(Char *, cglob_t *, size_t *); +static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int globextend(const Char *, cglob_t *, size_t *); +static const Char * + globtilde(const Char *, Char *, size_t, cglob_t *); +static int globexp1(const Char *, cglob_t *, size_t *); +static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *); +static int match(Char *, Char *, Char *); +#ifdef DEBUG +static void qprintf(const char *, Char *); +#endif + +int +cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob) +{ + const char *patnext; + size_t limit; + Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + patnext = pattern; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathc = 0; + pglob->gl_pathv = NULL; + if (!(flags & GLOB_DOOFFS)) + pglob->gl_offs = 0; + } + + if (flags & GLOB_LIMIT) { + limit = pglob->gl_matchc; + if (limit == 0) + limit = ARG_MAX; + } else + limit = 0; + + pglob->gl_flags = flags & ~GLOB_MAGCHAR; + pglob->gl_errfunc = errfunc; + pglob->gl_matchc = 0; + + bufnext = patbuf; + bufend = bufnext + MAXPATHLEN - 1; + if (flags & GLOB_NOESCAPE) { + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc; + patnext += clen; + } + } else { + /* Protect the quoted characters. */ + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + if (*patnext == QUOTE) { + if (*++patnext == EOS) { + *bufnext++ = QUOTE | M_PROTECT; + continue; + } + prot = M_PROTECT; + } else + prot = 0; + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc | prot; + patnext += clen; + } + } + *bufnext = EOS; + + if (flags & GLOB_BRACE) + return globexp1(patbuf, pglob, &limit); + else + return glob0(patbuf, pglob, &limit); +} + +/* + * Expand recursively a glob {} pattern. When there is no more expansion + * invoke the standard globbing routine to glob the rest of the magic + * characters + */ +static int +globexp1(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char* ptr = pattern; + int rv; + + /* Protect a single {}, for find(1), like csh */ + if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) + return glob0(pattern, pglob, limit); + + while ((ptr = g_strchr(ptr, LBRACE)) != NULL) + if (!globexp2(ptr, pattern, pglob, &rv, limit)) + return rv; + + return glob0(pattern, pglob, limit); +} + + +/* + * Recursive brace globbing helper. Tries to expand a single brace. + * If it succeeds then it invokes globexp1 with the new pattern. + * If it fails then it tries to glob the rest of the pattern and returns. + */ +static int +globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit) +{ + int i; + Char *lm, *ls; + const Char *pe, *pm, *pm1, *pl; + Char patbuf[MAXPATHLEN]; + + /* copy part up to the brace */ + for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++) + continue; + *lm = EOS; + ls = lm; + + /* Find the balanced brace */ + for (i = 0, pe = ++ptr; *pe; pe++) + if (*pe == LBRACKET) { + /* Ignore everything between [] */ + for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++) + continue; + if (*pe == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pe = pm; + } + } + else if (*pe == LBRACE) + i++; + else if (*pe == RBRACE) { + if (i == 0) + break; + i--; + } + + /* Non matching braces; just glob the pattern */ + if (i != 0 || *pe == EOS) { + *rv = glob0(patbuf, pglob, limit); + return 0; + } + + for (i = 0, pl = pm = ptr; pm <= pe; pm++) + switch (*pm) { + case LBRACKET: + /* Ignore everything between [] */ + for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++) + continue; + if (*pm == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pm = pm1; + } + break; + + case LBRACE: + i++; + break; + + case RBRACE: + if (i) { + i--; + break; + } + /* FALLTHROUGH */ + case COMMA: + if (i && *pm == COMMA) + break; + else { + /* Append the current string */ + for (lm = ls; (pl < pm); *lm++ = *pl++) + continue; + /* + * Append the rest of the pattern after the + * closing brace + */ + for (pl = pe + 1; (*lm++ = *pl++) != EOS;) + continue; + + /* Expand the current pattern */ +#ifdef DEBUG + qprintf("globexp2:", patbuf); +#endif + *rv = globexp1(patbuf, pglob, limit); + + /* move after the comma, to the next string */ + pl = pm + 1; + } + break; + + default: + break; + } + *rv = 0; + return 0; +} + + + +/* + * expand tilde from the passwd file. + */ +static const Char * +globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob) +{ + struct passwd *pwd; + char *h; + const Char *p; + Char *b, *eb; + + if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE)) + return pattern; + + /* + * Copy up to the end of the string or / + */ + eb = &patbuf[patbuf_len - 1]; + for (p = pattern + 1, h = (char *) patbuf; + h < (char *)eb && *p && *p != SLASH; *h++ = *p++) + continue; + + *h = EOS; + + if (((char *) patbuf)[0] == EOS) { + /* + * handle a plain ~ or ~/ by expanding $HOME first (iff + * we're not running setuid or setgid) and then trying + * the password file + */ + /*if (issetugid() != 0 || + (h = getenv("HOME")) == NULL) { + if (((h = getlogin()) != NULL && + (pwd = getpwnam(h)) != NULL) || + (pwd = getpwuid(getuid())) != NULL) + h = pwd->pw_dir; + else + return pattern; + }*/ + } + else { + /* + * Expand a ~user + */ + if ((pwd = getpwnam((char*) patbuf)) == NULL) + return pattern; + else + h = pwd->pw_dir; + } + + /* Copy the home directory */ + for (b = patbuf; b < eb && *h; *b++ = *h++) + continue; + + /* Append the rest of the pattern */ + while (b < eb && (*b++ = *p++) != EOS) + continue; + *b = EOS; + + return patbuf; +} + + +/* + * The main glob() routine: compiles the pattern (optionally processing + * quotes), calls glob1() to do the real pattern matching, and finally + * sorts the list (unless unsorted operation is requested). Returns 0 + * if things went well, nonzero if errors occurred. + */ +static int +glob0(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char *qpatnext; + int err; + size_t oldpathc; + Char *bufnext, c, patbuf[MAXPATHLEN]; + + qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); + oldpathc = pglob->gl_pathc; + bufnext = patbuf; + + /* We don't need to check for buffer overflow any more. */ + while ((c = *qpatnext++) != EOS) { + switch (c) { + case LBRACKET: + c = *qpatnext; + if (c == NOT) + ++qpatnext; + if (*qpatnext == EOS || + g_strchr(qpatnext+1, RBRACKET) == NULL) { + *bufnext++ = LBRACKET; + if (c == NOT) + --qpatnext; + break; + } + *bufnext++ = M_SET; + if (c == NOT) + *bufnext++ = M_NOT; + c = *qpatnext++; + do { + *bufnext++ = CHAR(c); + if (*qpatnext == RANGE && + (c = qpatnext[1]) != RBRACKET) { + *bufnext++ = M_RNG; + *bufnext++ = CHAR(c); + qpatnext += 2; + } + } while ((c = *qpatnext++) != RBRACKET); + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_END; + break; + case QUESTION: + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_ONE; + break; + case STAR: + pglob->gl_flags |= GLOB_MAGCHAR; + /* collapse adjacent stars to one, + * to avoid exponential behavior + */ + if (bufnext == patbuf || bufnext[-1] != M_ALL) + *bufnext++ = M_ALL; + break; + default: + *bufnext++ = CHAR(c); + break; + } + } + *bufnext = EOS; +#ifdef DEBUG + qprintf("glob0:", patbuf); +#endif + + if ((err = glob1(patbuf, pglob, limit)) != 0) + return(err); + + /* + * If there was no match we are going to append the pattern + * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified + * and the pattern did not contain any magic characters + * GLOB_NOMAGIC is there just for compatibility with csh. + */ + if (pglob->gl_pathc == oldpathc) { + if (((pglob->gl_flags & GLOB_NOCHECK) || + ((pglob->gl_flags & GLOB_NOMAGIC) && + !(pglob->gl_flags & GLOB_MAGCHAR)))) + return(globextend(pattern, pglob, limit)); + else + return(GLOB_NOMATCH); + } + if (!(pglob->gl_flags & GLOB_NOSORT)) + qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, + pglob->gl_pathc - oldpathc, sizeof(char *), compare); + return(0); +} + +static int +compare(const void *p, const void *q) +{ + return(strcmp(*(char **)p, *(char **)q)); +} + +static int +glob1(Char *pattern, cglob_t *pglob, size_t *limit) +{ + Char pathbuf[MAXPATHLEN]; + + /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ + if (*pattern == EOS) + return(0); + return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, + pattern, pglob, limit)); +} + +/* + * The functions glob2 and glob3 are mutually recursive; there is one level + * of recursion for each segment in the pattern that contains one or more + * meta characters. + */ +static int +glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern, + cglob_t *pglob, size_t *limit) +{ + struct stat sb; + Char *p, *q; + int anymeta; + + /* + * Loop over pattern segments until end of pattern or until + * segment with meta character found. + */ + for (anymeta = 0;;) { + if (*pattern == EOS) { /* End of pattern? */ + *pathend = EOS; + if (g_lstat(pathbuf, &sb, pglob)) + return(0); + + if (((pglob->gl_flags & GLOB_MARK) && + pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) + || (S_ISLNK(sb.st_mode) && + (g_stat(pathbuf, &sb, pglob) == 0) && + S_ISDIR(sb.st_mode)))) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = SEP; + *pathend = EOS; + } + ++pglob->gl_matchc; + return(globextend(pathbuf, pglob, limit)); + } + + /* Find end of next segment, copy tentatively to pathend. */ + q = pathend; + p = pattern; + while (*p != EOS && *p != SEP) { + if (ismeta(*p)) + anymeta = 1; + if (q + 1 > pathend_last) + return (GLOB_ABORTED); + *q++ = *p++; + } + + if (!anymeta) { /* No expansion, do next segment. */ + pathend = q; + pattern = p; + while (*pattern == SEP) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = *pattern++; + } + } else /* Need expansion, recurse. */ + return(glob3(pathbuf, pathend, pathend_last, pattern, p, + pglob, limit)); + } + /* NOTREACHED */ +} + +static int +glob3(Char *pathbuf, Char *pathend, Char *pathend_last, + Char *pattern, Char *restpattern, + cglob_t *pglob, size_t *limit) +{ + struct dirent *dp; + DIR *dirp; + int err; + char buf[MAXPATHLEN]; + + /* + * The readdirfunc declaration can't be prototyped, because it is + * assigned, below, to two functions which are prototyped in glob.h + * and dirent.h as taking pointers to differently typed opaque + * structures. + */ + struct dirent *(*readdirfunc)(); + + if (pathend > pathend_last) + return (GLOB_ABORTED); + *pathend = EOS; + errno = 0; + + if ((dirp = g_opendir(pathbuf, pglob)) == NULL) { + /* TODO: don't call for ENOENT or ENOTDIR? */ + if (pglob->gl_errfunc) { + if (g_Ctoc(pathbuf, buf, sizeof(buf))) + return (GLOB_ABORTED); + if (pglob->gl_errfunc(buf, errno) || + pglob->gl_flags & GLOB_ERR) + return (GLOB_ABORTED); + } + return(0); + } + + err = 0; + + /* Search directory for matching names. */ + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + readdirfunc = pglob->gl_readdir; + else + readdirfunc = readdir; + while ((dp = (*readdirfunc)(dirp))) { + char *sc; + Char *dc; + wchar_t wc; + size_t clen; + mbstate_t mbs; + + /* Initial DOT must be matched literally. */ + if (dp->d_name[0] == DOT && *pattern != DOT) + continue; + memset(&mbs, 0, sizeof(mbs)); + dc = pathend; + sc = dp->d_name; + while (dc < pathend_last) { + clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) { + wc = *sc; + clen = 1; + memset(&mbs, 0, sizeof(mbs)); + } + if ((*dc++ = wc) == EOS) + break; + sc += clen; + } + if (!match(pathend, pattern, restpattern)) { + *pathend = EOS; + continue; + } + err = glob2(pathbuf, --dc, pathend_last, restpattern, + pglob, limit); + if (err) + break; + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + (*pglob->gl_closedir)(dirp); + else + closedir(dirp); + return(err); +} + + +/* + * Extend the gl_pathv member of a glob_t structure to accomodate a new item, + * add the new item, and update gl_pathc. + * + * This assumes the BSD realloc, which only copies the block when its size + * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic + * behavior. + * + * Return 0 if new item added, error code if memory couldn't be allocated. + * + * Invariant of the glob_t structure: + * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and + * gl_pathv points to (gl_offs + gl_pathc + 1) items. + */ +static int +globextend(const Char *path, cglob_t *pglob, size_t *limit) +{ + char **pathv; + size_t i, newsize, len; + char *copy; + const Char *p; + + if (*limit && pglob->gl_pathc > *limit) { + errno = 0; + return (GLOB_NOSPACE); + } + + newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); + pathv = pglob->gl_pathv ? + realloc((char *)pglob->gl_pathv, newsize) : + malloc(newsize); + if (pathv == NULL) { + if (pglob->gl_pathv) { + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } + return(GLOB_NOSPACE); + } + + if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { + /* first time around -- clear initial gl_offs items */ + pathv += pglob->gl_offs; + for (i = pglob->gl_offs + 1; --i > 0; ) + *--pathv = NULL; + } + pglob->gl_pathv = pathv; + + for (p = path; *p++;) + continue; + len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */ + if ((copy = malloc(len)) != NULL) { + if (g_Ctoc(path, copy, len)) { + free(copy); + return (GLOB_NOSPACE); + } + pathv[pglob->gl_offs + pglob->gl_pathc++] = copy; + } + pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; + return(copy == NULL ? GLOB_NOSPACE : 0); +} + +/* + * pattern matching function for filenames. Each occurrence of the * + * pattern causes a recursion level. + */ +static int +match(Char *name, Char *pat, Char *patend) +{ + int ok, negate_range; + Char c, k; + + while (pat < patend) { + c = *pat++; + switch (c & M_MASK) { + case M_ALL: + if (pat == patend) + return(1); + do + if (match(name, pat, patend)) + return(1); + while (*name++ != EOS); + return(0); + case M_ONE: + if (*name++ == EOS) + return(0); + break; + case M_SET: + ok = 0; + if ((k = *name++) == EOS) + return(0); + if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS) + ++pat; + while (((c = *pat++) & M_MASK) != M_END) + if ((*pat & M_MASK) == M_RNG) { + if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1; + pat += 2; + } else if (c == k) + ok = 1; + if (ok == negate_range) + return(0); + break; + default: + if (*name++ != c) + return(0); + break; + } + } + return(*name == EOS); +} + +/* Free allocated data belonging to a glob_t structure. */ +void +cglobfree(cglob_t *pglob) +{ + size_t i; + char **pp; + + if (pglob->gl_pathv != NULL) { + pp = pglob->gl_pathv + pglob->gl_offs; + for (i = pglob->gl_pathc; i--; ++pp) + if (*pp) + free(*pp); + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } +} + +static DIR * +g_opendir(Char *str, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (!*str) + strcpy(buf, "."); + else { + if (g_Ctoc(str, buf, sizeof(buf))) + return (NULL); + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_opendir)(buf)); + + return(opendir(buf)); +} + +static int +g_lstat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_lstat)(buf, sb)); + return(lstat(buf, sb)); +} + +static int +g_stat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_stat)(buf, sb)); + return(stat(buf, sb)); +} + +static const Char * +g_strchr(const Char *str, wchar_t ch) +{ + + do { + if (*str == ch) + return (str); + } while (*str++); + return (NULL); +} + +static int +g_Ctoc(const Char *str, char *buf, size_t len) +{ + mbstate_t mbs; + size_t clen; + + memset(&mbs, 0, sizeof(mbs)); + while (len >= MB_CUR_MAX) { + clen = wcrtomb(buf, *str, &mbs); + if (clen == (size_t)-1) + return (1); + if (*str == L'\0') + return (0); + str++; + buf += clen; + len -= clen; + } + return (1); +} + +#ifdef DEBUG +static void +qprintf(const char *str, Char *s) +{ + Char *p; + + (void)printf("%s:\n", str); + for (p = s; *p; p++) + (void)printf("%c", CHAR(*p)); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", *p & M_PROTECT ? '"' : ' '); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", ismeta(*p) ? '_' : ' '); + (void)printf("\n"); +} +#endif diff --git a/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp new file mode 100644 index 00000000..5799d6ac --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp @@ -0,0 +1,342 @@ +#if defined(__linux__) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef ANDROID +#include "cglob.h" +#else +#include +#define cglob glob +#define cglobfree globfree +#define cglob_t glob_t +#endif +#include +#include +#include + +#include "serial/serial.h" + +using serial::PortInfo; +using std::istringstream; +using std::ifstream; +using std::getline; +using std::vector; +using std::string; +using std::cout; +using std::endl; + +static vector glob(const vector& patterns); +static string basename(const string& path); +static string dirname(const string& path); +static bool path_exists(const string& path); +static string realpath(const string& path); +static string usb_sysfs_friendly_name(const string& sys_usb_path); +static vector get_sysfs_info(const string& device_path); +static string read_line(const string& file); +static string usb_sysfs_hw_string(const string& sysfs_path); +static string format(const char* format, ...); + +vector +glob(const vector& patterns) +{ + vector paths_found; + + if(patterns.size() == 0) + return paths_found; + + cglob_t glob_results; + + int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results); + + vector::const_iterator iter = patterns.begin(); + + while(++iter != patterns.end()) + { + glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results); + } + + for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++) + { + paths_found.push_back(glob_results.gl_pathv[path_index]); + } + + cglobfree(&glob_results); + + return paths_found; +} + +string +basename(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + + return string(path, pos+1, string::npos); +} + +string +dirname(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + else if(pos == 0) + return "/"; + + return string(path, 0, pos); +} + +bool +path_exists(const string& path) +{ + struct stat sb; + + if( stat(path.c_str(), &sb ) == 0 ) + return true; + + return false; +} + +string +realpath(const string& path) +{ + char* real_path = realpath(path.c_str(), NULL); + + string result; + + if(real_path != NULL) + { + result = real_path; + + free(real_path); + } + + return result; +} + +string +usb_sysfs_friendly_name(const string& sys_usb_path) +{ + unsigned int device_number = 0; + + istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number; + + string manufacturer = read_line( sys_usb_path + "/manufacturer" ); + + string product = read_line( sys_usb_path + "/product" ); + + string serial = read_line( sys_usb_path + "/serial" ); + + if( manufacturer.empty() && product.empty() && serial.empty() ) + return ""; + + return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() ); +} + +vector +get_sysfs_info(const string& device_path) +{ + string device_name = basename( device_path ); + + string friendly_name; + + string hardware_id; + + string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() ); + + if( device_name.compare(0,6,"ttyUSB") == 0 ) + { + sys_device_path = dirname( dirname( realpath( sys_device_path ) ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else if( device_name.compare(0,6,"ttyACM") == 0 ) + { + sys_device_path = dirname( realpath( sys_device_path ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else + { + // Try to read ID string of PCI device + + string sys_id_path = sys_device_path + "/id"; + + if( path_exists( sys_id_path ) ) + hardware_id = read_line( sys_id_path ); + } + + if( friendly_name.empty() ) + friendly_name = device_name; + + if( hardware_id.empty() ) + hardware_id = "n/a"; + + vector result; + result.push_back(friendly_name); + result.push_back(hardware_id); + + return result; +} + +string +read_line(const string& file) +{ + ifstream ifs(file.c_str(), ifstream::in); + + string line; + + if(ifs) + { + getline(ifs, line); + } + + return line; +} + +string +format(const char* format, ...) +{ + va_list ap; + + size_t buffer_size_bytes = 256; + + string result; + + char* buffer = (char*)malloc(buffer_size_bytes); + + if( buffer == NULL ) + return result; + + bool done = false; + + unsigned int loop_count = 0; + + while(!done) + { + va_start(ap, format); + + int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap); + + if( return_value < 0 ) + { + done = true; + } + else if( return_value >= buffer_size_bytes ) + { + // Realloc and try again. + + buffer_size_bytes = return_value + 1; + + char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes); + + if( new_buffer_ptr == NULL ) + { + done = true; + } + else + { + buffer = new_buffer_ptr; + } + } + else + { + result = buffer; + done = true; + } + + va_end(ap); + + if( ++loop_count > 5 ) + done = true; + } + + free(buffer); + + return result; +} + +string +usb_sysfs_hw_string(const string& sysfs_path) +{ + string serial_number = read_line( sysfs_path + "/serial" ); + + if( serial_number.length() > 0 ) + { + serial_number = format( "SNR=%s", serial_number.c_str() ); + } + + string vid = read_line( sysfs_path + "/idVendor" ); + + string pid = read_line( sysfs_path + "/idProduct" ); + + return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() ); +} + +vector +serial::list_ports() +{ + vector results; + + vector search_globs; + search_globs.push_back("/dev/ttyACM*"); + search_globs.push_back("/dev/ttyS*"); + search_globs.push_back("/dev/ttyUSB*"); + search_globs.push_back("/dev/tty.*"); + search_globs.push_back("/dev/cu.*"); + search_globs.push_back("/dev/rfcomm*"); + + vector devices_found = glob( search_globs ); + + vector::iterator iter = devices_found.begin(); + + while( iter != devices_found.end() ) + { + string device = *iter++; + + vector sysfs_info = get_sysfs_info( device ); + + string friendly_name = sysfs_info[0]; + + string hardware_id = sysfs_info[1]; + + PortInfo device_entry; + device_entry.port = device; + device_entry.description = friendly_name; + device_entry.hardware_id = hardware_id; + + results.push_back( device_entry ); + + } + + return results; +} + +#endif // defined(__linux__) diff --git a/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp new file mode 100644 index 00000000..8005c62b --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp @@ -0,0 +1,286 @@ +#if defined(__APPLE__) + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../../../include/serial/serial.h" + +using serial::PortInfo; +using std::string; +using std::vector; + +#define HARDWARE_ID_STRING_LENGTH 128 + +string cfstring_to_string( CFStringRef cfstring ); +string get_device_path( io_object_t& serial_port ); +string get_class_name( io_object_t& obj ); +io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port ); +string get_string_property( io_object_t& device, const char* property ); +uint16_t get_int_property( io_object_t& device, const char* property ); +string rtrim(const string& str); + +string +cfstring_to_string( CFStringRef cfstring ) +{ + char cstring[MAXPATHLEN]; + string result; + + if( cfstring ) + { + Boolean success = CFStringGetCString( cfstring, + cstring, + sizeof(cstring), + kCFStringEncodingASCII ); + + if( success ) + result = cstring; + } + + return result; +} + +string +get_device_path( io_object_t& serial_port ) +{ + CFTypeRef callout_path; + string device_path; + + callout_path = IORegistryEntryCreateCFProperty( serial_port, + CFSTR(kIOCalloutDeviceKey), + kCFAllocatorDefault, + 0 ); + + if (callout_path) + { + if( CFGetTypeID(callout_path) == CFStringGetTypeID() ) + device_path = cfstring_to_string( static_cast(callout_path) ); + + CFRelease(callout_path); + } + + return device_path; +} + +string +get_class_name( io_object_t& obj ) +{ + string result; + io_name_t class_name; + kern_return_t kern_result; + + kern_result = IOObjectGetClass( obj, class_name ); + + if( kern_result == KERN_SUCCESS ) + result = class_name; + + return result; +} + +io_registry_entry_t +get_parent_iousb_device( io_object_t& serial_port ) +{ + io_object_t device = serial_port; + io_registry_entry_t parent = 0; + io_registry_entry_t result = 0; + kern_return_t kern_result = KERN_FAILURE; + string name = get_class_name(device); + + // Walk the IO Registry tree looking for this devices parent IOUSBDevice. + while( name != "IOUSBDevice" ) + { + kern_result = IORegistryEntryGetParentEntry( device, + kIOServicePlane, + &parent ); + + if(kern_result != KERN_SUCCESS) + { + result = 0; + break; + } + + device = parent; + + name = get_class_name(device); + } + + if(kern_result == KERN_SUCCESS) + result = device; + + return result; +} + +string +get_string_property( io_object_t& device, const char* property ) +{ + string property_name; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty( + device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if( name_as_cfstring ) + { + if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() ) + property_name = cfstring_to_string( static_cast(name_as_cfstring) ); + + CFRelease(name_as_cfstring); + } + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + } + + return property_name; +} + +uint16_t +get_int_property( io_object_t& device, const char* property ) +{ + uint16_t result = 0; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef number = IORegistryEntryCreateCFProperty( device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + + if( number ) + { + if( CFGetTypeID(number) == CFNumberGetTypeID() ) + { + bool success = CFNumberGetValue( static_cast(number), + kCFNumberSInt16Type, + &result ); + + if( !success ) + result = 0; + } + + CFRelease(number); + } + + } + + return result; +} + +string rtrim(const string& str) +{ + string result = str; + + string whitespace = " \t\f\v\n\r"; + + std::size_t found = result.find_last_not_of(whitespace); + + if (found != std::string::npos) + result.erase(found+1); + else + result.clear(); + + return result; +} + +vector +serial::list_ports(void) +{ + vector devices_found; + CFMutableDictionaryRef classes_to_match; + io_iterator_t serial_port_iterator; + io_object_t serial_port; + mach_port_t master_port; + kern_return_t kern_result; + + kern_result = IOMasterPort(MACH_PORT_NULL, &master_port); + + if(kern_result != KERN_SUCCESS) + return devices_found; + + classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue); + + if (classes_to_match == NULL) + return devices_found; + + CFDictionarySetValue( classes_to_match, + CFSTR(kIOSerialBSDTypeKey), + CFSTR(kIOSerialBSDAllTypes) ); + + kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator); + + if (KERN_SUCCESS != kern_result) + return devices_found; + + while ( (serial_port = IOIteratorNext(serial_port_iterator)) ) + { + string device_path = get_device_path( serial_port ); + io_registry_entry_t parent = get_parent_iousb_device( serial_port ); + IOObjectRelease(serial_port); + + if( device_path.empty() ) + continue; + + PortInfo port_info; + port_info.port = device_path; + port_info.description = "n/a"; + port_info.hardware_id = "n/a"; + + string device_name = rtrim( get_string_property( parent, "USB Product Name" ) ); + string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") ); + string description = rtrim( vendor_name + " " + device_name ); + if( !description.empty() ) + port_info.description = description; + + string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) ); + uint16_t vendor_id = get_int_property( parent, "idVendor" ); + uint16_t product_id = get_int_property( parent, "idProduct" ); + + if( vendor_id && product_id ) + { + char cstring[HARDWARE_ID_STRING_LENGTH]; + + if(serial_number.empty()) + serial_number = "None"; + + int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s", + vendor_id, + product_id, + serial_number.c_str() ); + + if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) ) + port_info.hardware_id = cstring; + } + + devices_found.push_back(port_info); + } + + IOObjectRelease(serial_port_iterator); + return devices_found; +} + +#endif // defined(__APPLE__) diff --git a/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp new file mode 100644 index 00000000..7da40c44 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp @@ -0,0 +1,152 @@ +#if defined(_WIN32) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include "serial/serial.h" +#include +#include +#include +#include +#include +#include + +using serial::PortInfo; +using std::vector; +using std::string; + +static const DWORD port_name_max_length = 256; +static const DWORD friendly_name_max_length = 256; +static const DWORD hardware_id_max_length = 256; + +// Convert a wide Unicode string to an UTF8 string +std::string utf8_encode(const std::wstring &wstr) +{ + int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); + std::string strTo( size_needed, 0 ); + WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); + return strTo; +} + +vector +serial::list_ports() +{ + vector devices_found; + + HDEVINFO device_info_set = SetupDiGetClassDevs( + (const GUID *) &GUID_DEVCLASS_PORTS, + NULL, + NULL, + DIGCF_PRESENT); + + unsigned int device_info_set_index = 0; + SP_DEVINFO_DATA device_info_data; + + device_info_data.cbSize = sizeof(SP_DEVINFO_DATA); + + while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data)) + { + device_info_set_index++; + + // Get port name + + HKEY hkey = SetupDiOpenDevRegKey( + device_info_set, + &device_info_data, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + TCHAR port_name[port_name_max_length]; + DWORD port_name_length = port_name_max_length; + + LONG return_code = RegQueryValueEx( + hkey, + _T("PortName"), + NULL, + NULL, + (LPBYTE)port_name, + &port_name_length); + + RegCloseKey(hkey); + + if(return_code != EXIT_SUCCESS) + continue; + + if(port_name_length > 0 && port_name_length <= port_name_max_length) + port_name[port_name_length-1] = '\0'; + else + port_name[0] = '\0'; + + // Ignore parallel ports + + if(_tcsstr(port_name, _T("LPT")) != NULL) + continue; + + // Get port friendly name + + TCHAR friendly_name[friendly_name_max_length]; + DWORD friendly_name_actual_length = 0; + + BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_FRIENDLYNAME, + NULL, + (PBYTE)friendly_name, + friendly_name_max_length, + &friendly_name_actual_length); + + if(got_friendly_name == TRUE && friendly_name_actual_length > 0) + friendly_name[friendly_name_actual_length-1] = '\0'; + else + friendly_name[0] = '\0'; + + // Get hardware ID + + TCHAR hardware_id[hardware_id_max_length]; + DWORD hardware_id_actual_length = 0; + + BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + NULL, + (PBYTE)hardware_id, + hardware_id_max_length, + &hardware_id_actual_length); + + if(got_hardware_id == TRUE && hardware_id_actual_length > 0) + hardware_id[hardware_id_actual_length-1] = '\0'; + else + hardware_id[0] = '\0'; + + #ifdef UNICODE + std::string portName = utf8_encode(port_name); + std::string friendlyName = utf8_encode(friendly_name); + std::string hardwareId = utf8_encode(hardware_id); + #else + std::string portName = port_name; + std::string friendlyName = friendly_name; + std::string hardwareId = hardware_id; + #endif + + PortInfo port_entry; + port_entry.port = portName; + port_entry.description = friendlyName; + port_entry.hardware_id = hardwareId; + + devices_found.push_back(port_entry); + } + + SetupDiDestroyDeviceInfoList(device_info_set); + + return devices_found; +} + +#endif // #if defined(_WIN32) diff --git a/packages/flserial/macos/Classes/native_libs/src/impl/unix.cpp b/packages/flserial/macos/Classes/native_libs/src/impl/unix.cpp new file mode 100644 index 00000000..689c08cf --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/impl/unix.cpp @@ -0,0 +1,1087 @@ +/* Copyright 2012 William Woodall and John Harrison + * + * Additional Contributors: Christopher Baker @bakercp + */ + +#if !defined(_WIN32) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +# include +#endif + +#include +#include +#include +#ifdef __MACH__ +#include +#include +#include +#endif + +#include "../../include/serial/impl/unix.h" + +#ifndef TIOCINQ +#ifdef FIONREAD +#define TIOCINQ FIONREAD +#else +#define TIOCINQ 0x541B +#endif +#endif + +#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3) +#include +#endif + +using std::string; +using std::stringstream; +using std::invalid_argument; +using serial::MillisecondTimer; +using serial::Serial; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + + +MillisecondTimer::MillisecondTimer (const uint32_t millis) + : expiry(timespec_now()) +{ + int64_t tv_nsec = expiry.tv_nsec + (millis * 1e6); + if (tv_nsec >= 1e9) { + int64_t sec_diff = tv_nsec / static_cast (1e9); + expiry.tv_nsec = tv_nsec % static_cast(1e9); + expiry.tv_sec += sec_diff; + } else { + expiry.tv_nsec = tv_nsec; + } +} + +int64_t +MillisecondTimer::remaining () +{ + timespec now(timespec_now()); + int64_t millis = (expiry.tv_sec - now.tv_sec) * 1e3; + millis += (expiry.tv_nsec - now.tv_nsec) / 1e6; + return millis; +} + +timespec +MillisecondTimer::timespec_now () +{ + timespec time; +# ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + time.tv_sec = mts.tv_sec; + time.tv_nsec = mts.tv_nsec; +# else + clock_gettime(CLOCK_MONOTONIC, &time); +# endif + return time; +} + +timespec +timespec_from_ms (const uint32_t millis) +{ + timespec time; + time.tv_sec = millis / 1e3; + time.tv_nsec = (millis - (time.tv_sec * 1e3)) * 1e6; + return time; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port), fd_ (-1), is_open_ (false), xonxoff_ (false), rtscts_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + pthread_mutex_init(&this->read_mutex, NULL); + pthread_mutex_init(&this->write_mutex, NULL); + if (port_.empty () == false) + open (); +} + +Serial::SerialImpl::~SerialImpl () +{ + close(); + pthread_mutex_destroy(&this->read_mutex); + pthread_mutex_destroy(&this->write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + + int err = errno; + if (fd_ == -1) { + switch (err) { + case EINTR: + // Recurse because this is a recoverable error. + open (); + return; + case ENFILE: + case EMFILE: + THROW (IOException, "Too many file handles open."); + default: + char buff[32]; + sprintf(buff, "%08X", err); + THROW (IOException, buff); + } + } + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == -1) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + struct termios options; // The options for the file descriptor + + if (tcgetattr(fd_, &options) == -1) { + THROW (IOException, "::tcgetattr"); + } + + // set up raw mode / no echo / binary + options.c_cflag |= (tcflag_t) (CLOCAL | CREAD); + options.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | + ISIG | IEXTEN); //|ECHOPRT + + options.c_oflag &= (tcflag_t) ~(OPOST); + options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK); +#ifdef IUCLC + options.c_iflag &= (tcflag_t) ~IUCLC; +#endif +#ifdef PARMRK + options.c_iflag &= (tcflag_t) ~PARMRK; +#endif + + // setup baud rate + bool custom_baud = false; + speed_t baud; + switch (baudrate_) { +#ifdef B0 + case 0: baud = B0; break; +#endif +#ifdef B50 + case 50: baud = B50; break; +#endif +#ifdef B75 + case 75: baud = B75; break; +#endif +#ifdef B110 + case 110: baud = B110; break; +#endif +#ifdef B134 + case 134: baud = B134; break; +#endif +#ifdef B150 + case 150: baud = B150; break; +#endif +#ifdef B200 + case 200: baud = B200; break; +#endif +#ifdef B300 + case 300: baud = B300; break; +#endif +#ifdef B600 + case 600: baud = B600; break; +#endif +#ifdef B1200 + case 1200: baud = B1200; break; +#endif +#ifdef B1800 + case 1800: baud = B1800; break; +#endif +#ifdef B2400 + case 2400: baud = B2400; break; +#endif +#ifdef B4800 + case 4800: baud = B4800; break; +#endif +#ifdef B7200 + case 7200: baud = B7200; break; +#endif +#ifdef B9600 + case 9600: baud = B9600; break; +#endif +#ifdef B14400 + case 14400: baud = B14400; break; +#endif +#ifdef B19200 + case 19200: baud = B19200; break; +#endif +#ifdef B28800 + case 28800: baud = B28800; break; +#endif +#ifdef B57600 + case 57600: baud = B57600; break; +#endif +#ifdef B76800 + case 76800: baud = B76800; break; +#endif +#ifdef B38400 + case 38400: baud = B38400; break; +#endif +#ifdef B115200 + case 115200: baud = B115200; break; +#endif +#ifdef B128000 + case 128000: baud = B128000; break; +#endif +#ifdef B153600 + case 153600: baud = B153600; break; +#endif +#ifdef B230400 + case 230400: baud = B230400; break; +#endif +#ifdef B256000 + case 256000: baud = B256000; break; +#endif +#ifdef B460800 + case 460800: baud = B460800; break; +#endif +#ifdef B500000 + case 500000: baud = B500000; break; +#endif +#ifdef B576000 + case 576000: baud = B576000; break; +#endif +#ifdef B921600 + case 921600: baud = B921600; break; +#endif +#ifdef B1000000 + case 1000000: baud = B1000000; break; +#endif +#ifdef B1152000 + case 1152000: baud = B1152000; break; +#endif +#ifdef B1500000 + case 1500000: baud = B1500000; break; +#endif +#ifdef B2000000 + case 2000000: baud = B2000000; break; +#endif +#ifdef B2500000 + case 2500000: baud = B2500000; break; +#endif +#ifdef B3000000 + case 3000000: baud = B3000000; break; +#endif +#ifdef B3500000 + case 3500000: baud = B3500000; break; +#endif +#ifdef B4000000 + case 4000000: baud = B4000000; break; +#endif + default: + custom_baud = true; + } + if (custom_baud == false) { +#ifdef _BSD_SOURCE + ::cfsetspeed(&options, baud); +#else + ::cfsetispeed(&options, baud); + ::cfsetospeed(&options, baud); +#endif + } + + // setup char len + options.c_cflag &= (tcflag_t) ~CSIZE; + if (bytesize_ == eightbits) + options.c_cflag |= CS8; + else if (bytesize_ == sevenbits) + options.c_cflag |= CS7; + else if (bytesize_ == sixbits) + options.c_cflag |= CS6; + else if (bytesize_ == fivebits) + options.c_cflag |= CS5; + else + throw invalid_argument ("invalid char len"); + // setup stopbits + if (stopbits_ == stopbits_one) + options.c_cflag &= (tcflag_t) ~(CSTOPB); + else if (stopbits_ == stopbits_one_point_five) + // ONE POINT FIVE same as TWO.. there is no POSIX support for 1.5 + options.c_cflag |= (CSTOPB); + else if (stopbits_ == stopbits_two) + options.c_cflag |= (CSTOPB); + else + throw invalid_argument ("invalid stop bit"); + // setup parity + options.c_iflag &= (tcflag_t) ~(INPCK | ISTRIP); + if (parity_ == parity_none) { + options.c_cflag &= (tcflag_t) ~(PARENB | PARODD); + } else if (parity_ == parity_even) { + options.c_cflag &= (tcflag_t) ~(PARODD); + options.c_cflag |= (PARENB); + } else if (parity_ == parity_odd) { + options.c_cflag |= (PARENB | PARODD); + } +#ifdef CMSPAR + else if (parity_ == parity_mark) { + options.c_cflag |= (PARENB | CMSPAR | PARODD); + } + else if (parity_ == parity_space) { + options.c_cflag |= (PARENB | CMSPAR); + options.c_cflag &= (tcflag_t) ~(PARODD); + } +#else + // CMSPAR is not defined on OSX. So do not support mark or space parity. + else if (parity_ == parity_mark || parity_ == parity_space) { + throw invalid_argument ("OS does not support mark or space parity"); + } +#endif // ifdef CMSPAR + else { + throw invalid_argument ("invalid parity"); + } + // setup flow control + if (flowcontrol_ == flowcontrol_none) { + xonxoff_ = false; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_software) { + xonxoff_ = true; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_hardware) { + xonxoff_ = false; + rtscts_ = true; + } + // xonxoff +#ifdef IXANY + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); //|IXANY) + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF | IXANY); +#else + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF); +#endif + // rtscts +#ifdef CRTSCTS + if (rtscts_) + options.c_cflag |= (CRTSCTS); + else + options.c_cflag &= (unsigned long) ~(CRTSCTS); +#elif defined CNEW_RTSCTS + if (rtscts_) + options.c_cflag |= (CNEW_RTSCTS); + else + options.c_cflag &= (unsigned long) ~(CNEW_RTSCTS); +#else +#error "OS Support seems wrong." +#endif + + // http://www.unixwiz.net/techtips/termios-vmin-vtime.html + // this basically sets the read call up to be a polling read, + // but we are using select to ensure there is data available + // to read before each call, so we should never needlessly poll + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + + // activate settings + ::tcsetattr (fd_, TCSANOW, &options); + + // apply custom baud rate, if any + if (custom_baud == true) { + // OS X support +#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4) + // Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates + // other than those specified by POSIX. The driver for the underlying serial hardware + // ultimately determines which baud rates can be used. This ioctl sets both the input + // and output speed. + speed_t new_baud = static_cast (baudrate_); + // PySerial uses IOSSIOSPEED=0x80045402 + if (-1 == ioctl (fd_, IOSSIOSPEED, &new_baud, 1)) { + THROW (IOException, errno); + } + // Linux Support +#elif defined(__linux__) && defined (TIOCSSERIAL) + struct serial_struct ser; + + if (-1 == ioctl (fd_, TIOCGSERIAL, &ser)) { + THROW (IOException, errno); + } + + // set custom divisor + ser.custom_divisor = ser.baud_base / static_cast (baudrate_); + // update flags + ser.flags &= ~ASYNC_SPD_MASK; + ser.flags |= ASYNC_SPD_CUST; + + if (-1 == ioctl (fd_, TIOCSSERIAL, &ser)) { + THROW (IOException, errno); + } +#else + throw invalid_argument ("OS does not currently support custom bauds"); +#endif + } + + // Update byte_time_ based on the new settings. + uint32_t bit_time_ns = 1e9 / baudrate_; + byte_time_ns_ = bit_time_ns * (1 + bytesize_ + parity_ + stopbits_); + + // Compensate for the stopbits_one_point_five enum being equal to int 3, + // and not 1.5. + if (stopbits_ == stopbits_one_point_five) { + byte_time_ns_ += ((1.5 - stopbits_one_point_five) * bit_time_ns); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != -1) { + int ret; + ret = ::close (fd_); + if (ret == 0) { + fd_ = -1; + } else { + THROW (IOException, errno); + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + int count = 0; + if (-1 == ioctl (fd_, TIOCINQ, &count)) { + THROW (IOException, errno); + } else { + return static_cast (count); + } +} + +bool +Serial::SerialImpl::waitReadable (uint32_t timeout) +{ + // Setup a select call to block for serial data or a timeout + fd_set readfds; + FD_ZERO (&readfds); + FD_SET (fd_, &readfds); + timespec timeout_ts (timespec_from_ms (timeout)); + int r = pselect (fd_ + 1, &readfds, NULL, NULL, &timeout_ts, NULL); + + if (r < 0) { + // Select was interrupted + if (errno == EINTR) { + return false; + } + // Otherwise there was some error + THROW (IOException, errno); + } + // Timeout occurred + if (r == 0) { + return false; + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + if (!FD_ISSET (fd_, &readfds)) { + THROW (IOException, "select reports ready to read, but our fd isn't" + " in the list, this shouldn't happen!"); + } + // Data available to read. + return true; +} + +void +Serial::SerialImpl::waitByteTimes (size_t count) +{ + timespec wait_time = { 0, static_cast(byte_time_ns_ * count)}; + pselect (0, NULL, NULL, NULL, &wait_time, NULL); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + // If the port is not open, throw + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + size_t bytes_read = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.read_timeout_constant; + total_timeout_ms += timeout_.read_timeout_multiplier * static_cast (size); + MillisecondTimer total_timeout(total_timeout_ms); + + // Pre-fill buffer with available bytes + { + ssize_t bytes_read_now = ::read (fd_, buf, size); + if (bytes_read_now > 0) { + bytes_read = bytes_read_now; + } + } + + while (bytes_read < size) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + if (timeout_remaining_ms <= 0) { + // Timed out + break; + } + // Timeout for the next select is whichever is less of the remaining + // total read timeout and the inter-byte timeout. + uint32_t timeout = std::min(static_cast (timeout_remaining_ms), + timeout_.inter_byte_timeout); + // Wait for the device to be readable, and then attempt to read. + if (waitReadable(timeout)) { + // If it's a fixed-length multi-byte read, insert a wait here so that + // we can attempt to grab the whole thing in a single IO call. Skip + // this wait if a non-max inter_byte_timeout is specified. + if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) { + size_t bytes_available = available(); + if (bytes_available + bytes_read < size) { + waitByteTimes(size - (bytes_available + bytes_read)); + } + } + // This should be non-blocking returning only what is available now + // Then returning so that select can block again. + ssize_t bytes_read_now = + ::read (fd_, buf + bytes_read, size - bytes_read); + // read should always return some data as select reported it was + // ready to read when we get to this point. + if (bytes_read_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to read immediately + // but reading returns nothing. + throw SerialException ("device reports readiness to read but " + "returned no data (device disconnected?)"); + } + // Update bytes_read + bytes_read += static_cast (bytes_read_now); + // If bytes_read == size then we have read everything we need + if (bytes_read == size) { + break; + } + // If bytes_read < size then we have more to read + if (bytes_read < size) { + continue; + } + // If bytes_read > size then we have over read, which shouldn't happen + if (bytes_read > size) { + throw SerialException ("read over read, too many bytes where " + "read, this shouldn't happen, might be " + "a logical error!"); + } + } + } + return bytes_read; +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + fd_set writefds; + size_t bytes_written = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.write_timeout_constant; + total_timeout_ms += timeout_.write_timeout_multiplier * static_cast (length); + MillisecondTimer total_timeout(total_timeout_ms); + + bool first_iteration = true; + while (bytes_written < length) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + // Only consider the timeout if it's not the first iteration of the loop + // otherwise a timeout of 0 won't be allowed through + if (!first_iteration && (timeout_remaining_ms <= 0)) { + // Timed out + break; + } + first_iteration = false; + + timespec timeout(timespec_from_ms(timeout_remaining_ms)); + + FD_ZERO (&writefds); + FD_SET (fd_, &writefds); + + // Do the select + int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL); + + // Figure out what happened by looking at select's response 'r' + /** Error **/ + if (r < 0) { + // Select was interrupted, try again + if (errno == EINTR) { + continue; + } + // Otherwise there was some error + THROW (IOException, errno); + } + /** Timeout **/ + if (r == 0) { + break; + } + /** Port ready to write **/ + if (r > 0) { + // Make sure our file descriptor is in the ready to write list + if (FD_ISSET (fd_, &writefds)) { + // This will write some + ssize_t bytes_written_now = + ::write (fd_, data + bytes_written, length - bytes_written); + + // even though pselect returned readiness the call might still be + // interrupted. In that case simply retry. + if (bytes_written_now == -1 && errno == EINTR) { + continue; + } + + // write should always return some data as select reported it was + // ready to write when we get to this point. + if (bytes_written_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to write immediately + // but writing returns nothing. + std::stringstream strs; + strs << "device reports readiness to write but " + "returned no data (device disconnected?)"; + strs << " errno=" << errno; + strs << " bytes_written_now= " << bytes_written_now; + strs << " bytes_written=" << bytes_written; + strs << " length=" << length; + throw SerialException(strs.str().c_str()); + } + // Update bytes_written + bytes_written += static_cast (bytes_written_now); + // If bytes_written == size then we have written everything we need to + if (bytes_written == length) { + break; + } + // If bytes_written < size then we have more to write + if (bytes_written < length) { + continue; + } + // If bytes_written > size then we have over written, which shouldn't happen + if (bytes_written > length) { + throw SerialException ("write over wrote, too many bytes where " + "written, this shouldn't happen, might be " + "a logical error!"); + } + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + THROW (IOException, "select reports ready to write, but our fd isn't" + " in the list, this shouldn't happen!"); + } + } + return bytes_written; +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = port; +} + +string +Serial::SerialImpl::getPort () const +{ + return port_; +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) + reconfigurePort (); +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) + reconfigurePort (); +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) + reconfigurePort (); +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) + reconfigurePort (); +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) + reconfigurePort (); +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + tcdrain (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushInput"); + } + tcflush (fd_, TCIFLUSH); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushOutput"); + } + tcflush (fd_, TCOFLUSH); +} + +void +Serial::SerialImpl::sendBreak (int duration) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::sendBreak"); + } + tcsendbreak (fd_, static_cast (duration / 4)); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + + if (level) { + if (-1 == ioctl (fd_, TIOCSBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCCBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + + int command = TIOCM_RTS; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + + int command = TIOCM_DTR; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +bool +Serial::SerialImpl::waitForChange () +{ +#ifndef TIOCMIWAIT + +while (is_open_ == true) { + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + if (0 != (status & TIOCM_CTS) + || 0 != (status & TIOCM_DSR) + || 0 != (status & TIOCM_RI) + || 0 != (status & TIOCM_CD)) + { + return true; + } + } + + usleep(1000); + } + + return false; +#else + int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS); + + if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) { + stringstream ss; + ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): " + << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + return true; +#endif +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCTS failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CTS); + } +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getDSR failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_DSR); + } +} + +bool +Serial::SerialImpl::getRI () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_RI); + } +} + +bool +Serial::SerialImpl::getCD () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCD failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CD); + } +} + +void +Serial::SerialImpl::readLock () +{ + int result = pthread_mutex_lock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::readUnlock () +{ + int result = pthread_mutex_unlock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeLock () +{ + int result = pthread_mutex_lock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeUnlock () +{ + int result = pthread_mutex_unlock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +#endif // !defined(_WIN32) diff --git a/packages/flserial/macos/Classes/native_libs/src/impl/win.cpp b/packages/flserial/macos/Classes/native_libs/src/impl/win.cpp new file mode 100644 index 00000000..cbccf048 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/impl/win.cpp @@ -0,0 +1,651 @@ +#if defined(_WIN32) + +/* Copyright 2012 William Woodall and John Harrison */ + +#include + +#include "serial/impl/win.h" + +using std::string; +using std::wstring; +using std::stringstream; +using std::invalid_argument; +using serial::Serial; +using serial::Timeout; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + +inline wstring +_prefix_port_if_needed(const wstring &input) +{ + static wstring windows_com_port_prefix = L"\\\\.\\"; + if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0) + { + return windows_com_port_prefix + input; + } + return input; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + if (port_.empty () == false) + open (); + read_mutex = CreateMutex(NULL, false, NULL); + write_mutex = CreateMutex(NULL, false, NULL); +} + +Serial::SerialImpl::~SerialImpl () +{ + this->close(); + CloseHandle(read_mutex); + CloseHandle(write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + // See: https://github.com/wjwwood/serial/issues/84 + wstring port_with_prefix = _prefix_port_if_needed(port_); + LPCWSTR lp_port = port_with_prefix.c_str(); + fd_ = CreateFileW(lp_port, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + 0); + + if (fd_ == INVALID_HANDLE_VALUE) { + DWORD create_file_err = GetLastError(); + stringstream ss; + switch (create_file_err) { + case ERROR_FILE_NOT_FOUND: + // Use this->getPort to convert to a std::string + ss << "Specified port, " << this->getPort() << ", does not exist."; + THROWEX (IOException, ss.str().c_str(), 1); + case ERROR_ACCESS_DENIED: + ss << "Specified port, " << this->getPort() << ", allready open."; + THROWEX (IOException, ss.str().c_str(), 2); + default: + ss << "Unknown error opening the serial port: " << create_file_err; + THROW (IOException, ss.str().c_str()); + } + } + + + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == INVALID_HANDLE_VALUE) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + DCB dcbSerialParams = {0}; + + dcbSerialParams.DCBlength=sizeof(dcbSerialParams); + + if (!GetCommState(fd_, &dcbSerialParams)) { + //error getting state + THROW (IOException, "Error getting the serial port state."); + } + + // setup baud rate + switch (baudrate_) { +#ifdef CBR_0 + case 0: dcbSerialParams.BaudRate = CBR_0; break; +#endif +#ifdef CBR_50 + case 50: dcbSerialParams.BaudRate = CBR_50; break; +#endif +#ifdef CBR_75 + case 75: dcbSerialParams.BaudRate = CBR_75; break; +#endif +#ifdef CBR_110 + case 110: dcbSerialParams.BaudRate = CBR_110; break; +#endif +#ifdef CBR_134 + case 134: dcbSerialParams.BaudRate = CBR_134; break; +#endif +#ifdef CBR_150 + case 150: dcbSerialParams.BaudRate = CBR_150; break; +#endif +#ifdef CBR_200 + case 200: dcbSerialParams.BaudRate = CBR_200; break; +#endif +#ifdef CBR_300 + case 300: dcbSerialParams.BaudRate = CBR_300; break; +#endif +#ifdef CBR_600 + case 600: dcbSerialParams.BaudRate = CBR_600; break; +#endif +#ifdef CBR_1200 + case 1200: dcbSerialParams.BaudRate = CBR_1200; break; +#endif +#ifdef CBR_1800 + case 1800: dcbSerialParams.BaudRate = CBR_1800; break; +#endif +#ifdef CBR_2400 + case 2400: dcbSerialParams.BaudRate = CBR_2400; break; +#endif +#ifdef CBR_4800 + case 4800: dcbSerialParams.BaudRate = CBR_4800; break; +#endif +#ifdef CBR_7200 + case 7200: dcbSerialParams.BaudRate = CBR_7200; break; +#endif +#ifdef CBR_9600 + case 9600: dcbSerialParams.BaudRate = CBR_9600; break; +#endif +#ifdef CBR_14400 + case 14400: dcbSerialParams.BaudRate = CBR_14400; break; +#endif +#ifdef CBR_19200 + case 19200: dcbSerialParams.BaudRate = CBR_19200; break; +#endif +#ifdef CBR_28800 + case 28800: dcbSerialParams.BaudRate = CBR_28800; break; +#endif +#ifdef CBR_57600 + case 57600: dcbSerialParams.BaudRate = CBR_57600; break; +#endif +#ifdef CBR_76800 + case 76800: dcbSerialParams.BaudRate = CBR_76800; break; +#endif +#ifdef CBR_38400 + case 38400: dcbSerialParams.BaudRate = CBR_38400; break; +#endif +#ifdef CBR_115200 + case 115200: dcbSerialParams.BaudRate = CBR_115200; break; +#endif +#ifdef CBR_128000 + case 128000: dcbSerialParams.BaudRate = CBR_128000; break; +#endif +#ifdef CBR_153600 + case 153600: dcbSerialParams.BaudRate = CBR_153600; break; +#endif +#ifdef CBR_230400 + case 230400: dcbSerialParams.BaudRate = CBR_230400; break; +#endif +#ifdef CBR_256000 + case 256000: dcbSerialParams.BaudRate = CBR_256000; break; +#endif +#ifdef CBR_460800 + case 460800: dcbSerialParams.BaudRate = CBR_460800; break; +#endif +#ifdef CBR_921600 + case 921600: dcbSerialParams.BaudRate = CBR_921600; break; +#endif + default: + // Try to blindly assign it + dcbSerialParams.BaudRate = baudrate_; + } + + // setup char len + if (bytesize_ == eightbits) + dcbSerialParams.ByteSize = 8; + else if (bytesize_ == sevenbits) + dcbSerialParams.ByteSize = 7; + else if (bytesize_ == sixbits) + dcbSerialParams.ByteSize = 6; + else if (bytesize_ == fivebits) + dcbSerialParams.ByteSize = 5; + else + throw invalid_argument ("invalid char len"); + + // setup stopbits + if (stopbits_ == stopbits_one) + dcbSerialParams.StopBits = ONESTOPBIT; + else if (stopbits_ == stopbits_one_point_five) + dcbSerialParams.StopBits = ONE5STOPBITS; + else if (stopbits_ == stopbits_two) + dcbSerialParams.StopBits = TWOSTOPBITS; + else + throw invalid_argument ("invalid stop bit"); + + // setup parity + if (parity_ == parity_none) { + dcbSerialParams.Parity = NOPARITY; + } else if (parity_ == parity_even) { + dcbSerialParams.Parity = EVENPARITY; + } else if (parity_ == parity_odd) { + dcbSerialParams.Parity = ODDPARITY; + } else if (parity_ == parity_mark) { + dcbSerialParams.Parity = MARKPARITY; + } else if (parity_ == parity_space) { + dcbSerialParams.Parity = SPACEPARITY; + } else { + throw invalid_argument ("invalid parity"); + } + + // setup flowcontrol + if (flowcontrol_ == flowcontrol_none) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + if (flowcontrol_ == flowcontrol_software) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = true; + dcbSerialParams.fInX = true; + } + if (flowcontrol_ == flowcontrol_hardware) { + dcbSerialParams.fOutxCtsFlow = true; + dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + + // activate settings + if (!SetCommState(fd_, &dcbSerialParams)){ + CloseHandle(fd_); + THROW (IOException, "Error setting serial port settings."); + } + + // Setup timeouts + COMMTIMEOUTS timeouts = {0}; + timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout; + timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant; + timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier; + timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant; + timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier; + if (!SetCommTimeouts(fd_, &timeouts)) { + THROW (IOException, "Error setting timeouts."); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != INVALID_HANDLE_VALUE) { + int ret; + ret = CloseHandle(fd_); + if (ret == 0) { + stringstream ss; + ss << "Error while closing serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } else { + fd_ = INVALID_HANDLE_VALUE; + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + COMSTAT cs; + if (!ClearCommError(fd_, NULL, &cs)) { + stringstream ss; + ss << "Error while checking status of the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return static_cast(cs.cbInQue); +} + +bool +Serial::SerialImpl::waitReadable (uint32_t /*timeout*/) +{ + THROW (IOException, "waitReadable is not implemented on Windows."); + return false; +} + +void +Serial::SerialImpl::waitByteTimes (size_t /*count*/) +{ + THROW (IOException, "waitByteTimes is not implemented on Windows."); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + DWORD bytes_read; + if (!ReadFile(fd_, buf, static_cast(size), &bytes_read, NULL)) { + stringstream ss; + ss << "Error while reading from the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_read); +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + DWORD bytes_written; + if (!WriteFile(fd_, data, static_cast(length), &bytes_written, NULL)) { + stringstream ss; + ss << "Error while writing to the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_written); +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = wstring(port.begin(), port.end()); +} + +string +Serial::SerialImpl::getPort () const +{ + return string(port_.begin(), port_.end()); +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; + if (is_open_) { + reconfigurePort (); + } +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) { + reconfigurePort (); + } +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) { + reconfigurePort (); + } +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) { + reconfigurePort (); + } +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) { + reconfigurePort (); + } +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) { + reconfigurePort (); + } +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + FlushFileBuffers (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushInput"); + } + PurgeComm(fd_, PURGE_RXCLEAR); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushOutput"); + } + PurgeComm(fd_, PURGE_TXCLEAR); +} + +void +Serial::SerialImpl::sendBreak (int /*duration*/) +{ + THROW (IOException, "sendBreak is not supported on Windows."); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + if (level) { + EscapeCommFunction (fd_, SETBREAK); + } else { + EscapeCommFunction (fd_, CLRBREAK); + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + if (level) { + EscapeCommFunction (fd_, SETRTS); + } else { + EscapeCommFunction (fd_, CLRRTS); + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + if (level) { + EscapeCommFunction (fd_, SETDTR); + } else { + EscapeCommFunction (fd_, CLRDTR); + } +} + +bool +Serial::SerialImpl::waitForChange () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::waitForChange"); + } + DWORD dwCommEvent; + + if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) { + // Error setting communications mask + return false; + } + + if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) { + // An error occurred waiting for the event. + return false; + } else { + // Event has occurred. + return true; + } +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the CTS line."); + } + + return (MS_CTS_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the DSR line."); + } + + return (MS_DSR_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getRI() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the RI line."); + } + + return (MS_RING_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getCD() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + // Error in GetCommModemStatus; + THROW (IOException, "Error getting the status of the CD line."); + } + + return (MS_RLSD_ON & dwModemStatus) != 0; +} + +void +Serial::SerialImpl::readLock() +{ + if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming read mutex."); + } +} + +void +Serial::SerialImpl::readUnlock() +{ + if (!ReleaseMutex(read_mutex)) { + THROW (IOException, "Error releasing read mutex."); + } +} + +void +Serial::SerialImpl::writeLock() +{ + if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming write mutex."); + } +} + +void +Serial::SerialImpl::writeUnlock() +{ + if (!ReleaseMutex(write_mutex)) { + THROW (IOException, "Error releasing write mutex."); + } +} + +#endif // #if defined(_WIN32) + diff --git a/packages/flserial/macos/Classes/native_libs/src/ringbuffer.c b/packages/flserial/macos/Classes/native_libs/src/ringbuffer.c new file mode 100644 index 00000000..39fbea59 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/ringbuffer.c @@ -0,0 +1,78 @@ +#include "ringbuffer.h" + +/** + * @file + * Implementation of ring buffer functions. + */ + +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) { + RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1); + buffer->buffer = buf; + buffer->buffer_mask = buf_size - 1; + buffer->tail_index = 0; + buffer->head_index = 0; +} + +void ring_buffer_queue(ring_buffer_t *buffer, char data) { + /* Is buffer full? */ + if(ring_buffer_is_full(buffer)) { + /* Is going to overwrite the oldest byte */ + /* Increase tail index */ + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + } + + /* Place data in buffer */ + buffer->buffer[buffer->head_index] = data; + buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer)); +} + +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) { + /* Add bytes; one by one */ + ring_buffer_size_t i; + for(i = 0; i < size; i++) { + ring_buffer_queue(buffer, data[i]); + } +} + +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + *data = buffer->buffer[buffer->tail_index]; + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + return 1; +} + +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + char *data_ptr = data; + ring_buffer_size_t cnt = 0; + while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) { + cnt++; + data_ptr++; + } + return cnt; +} + +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) { + if(index >= ring_buffer_num_items(buffer)) { + /* No items at index */ + return 0; + } + + /* Add index to pointer */ + ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer)); + *data = buffer->buffer[data_index]; + return 1; +} + +extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer); +extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer); +extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer); + diff --git a/packages/flserial/macos/Classes/native_libs/src/serial.cpp b/packages/flserial/macos/Classes/native_libs/src/serial.cpp new file mode 100644 index 00000000..06a15a99 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/serial.cpp @@ -0,0 +1,432 @@ +/* Copyright 2012 William Woodall and John Harrison */ +#include + +#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__) +# include +#endif + +#if defined (__MINGW32__) +# define alloca __builtin_alloca +#endif + +#include "../include/serial/serial.h" + +#ifdef _WIN32 +#include "serial/impl/win.h" +#else +#include "../include/serial/impl/unix.h" +#endif + +using std::invalid_argument; +using std::min; +using std::numeric_limits; +using std::vector; +using std::size_t; +using std::string; + +using serial::Serial; +using serial::SerialException; +using serial::IOException; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; + +class Serial::ScopedReadLock { +public: + ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->readLock(); + } + ~ScopedReadLock() { + this->pimpl_->readUnlock(); + } +private: + // Disable copy constructors + ScopedReadLock(const ScopedReadLock&); + const ScopedReadLock& operator=(ScopedReadLock); + + SerialImpl *pimpl_; +}; + +class Serial::ScopedWriteLock { +public: + ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->writeLock(); + } + ~ScopedWriteLock() { + this->pimpl_->writeUnlock(); + } +private: + // Disable copy constructors + ScopedWriteLock(const ScopedWriteLock&); + const ScopedWriteLock& operator=(ScopedWriteLock); + SerialImpl *pimpl_; +}; + +Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout, + bytesize_t bytesize, parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, + stopbits, flowcontrol)) +{ + pimpl_->setTimeout(timeout); +} + +Serial::~Serial () +{ + delete pimpl_; +} + +void +Serial::open () +{ + pimpl_->open (); +} + +void +Serial::close () +{ + pimpl_->close (); +} + +bool +Serial::isOpen () const +{ + return pimpl_->isOpen (); +} + +size_t +Serial::available () +{ + return pimpl_->available (); +} + +bool +Serial::waitReadable () +{ + serial::Timeout timeout(pimpl_->getTimeout ()); + return pimpl_->waitReadable(timeout.read_timeout_constant); +} + +void +Serial::waitByteTimes (size_t count) +{ + pimpl_->waitByteTimes(count); +} + +size_t +Serial::read_ (uint8_t *buffer, size_t size) +{ + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (uint8_t *buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (std::vector &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + + buffer.insert (buffer.end (), buffer_, buffer_+bytes_read); + delete[] buffer_; + return bytes_read; +} + +size_t +Serial::read (std::string &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + buffer.append (reinterpret_cast(buffer_), bytes_read); + delete[] buffer_; + return bytes_read; +} + +string +Serial::read (size_t size) +{ + std::string buffer; + this->read (buffer, size); + return buffer; +} + +size_t +Serial::readline (string &buffer, size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + while (true) + { + size_t bytes_read = this->read_ (buffer_ + read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + break; // EOL found + } + if (read_so_far == size) { + break; // Reached the maximum read length + } + } + buffer.append(reinterpret_cast (buffer_), read_so_far); + return read_so_far; +} + +string +Serial::readline (size_t size, string eol) +{ + std::string buffer; + this->readline (buffer, size, eol); + return buffer; +} + +vector +Serial::readlines (size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + std::vector lines; + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + size_t start_of_line = 0; + while (read_so_far < size) { + size_t bytes_read = this->read_ (buffer_+read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + if (start_of_line != read_so_far) { + lines.push_back ( + string (reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + // EOL found + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + start_of_line = read_so_far; + } + if (read_so_far == size) { + if (start_of_line != read_so_far) { + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Reached the maximum read length + } + } + return lines; +} + +size_t +Serial::write (const string &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (reinterpret_cast(data.c_str()), + data.length()); +} + +size_t +Serial::write (const std::vector &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (&data[0], data.size()); +} + +size_t +Serial::write (const uint8_t *data, size_t size) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_(data, size); +} + +size_t +Serial::write_ (const uint8_t *data, size_t length) +{ + return pimpl_->write (data, length); +} + +void +Serial::setPort (const string &port) +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + bool was_open = pimpl_->isOpen (); + if (was_open) close(); + pimpl_->setPort (port); + if (was_open) open (); +} + +string +Serial::getPort () const +{ + return pimpl_->getPort (); +} + +void +Serial::setTimeout (serial::Timeout &timeout) +{ + pimpl_->setTimeout (timeout); +} + +serial::Timeout +Serial::getTimeout () const { + return pimpl_->getTimeout (); +} + +void +Serial::setBaudrate (uint32_t baudrate) +{ + pimpl_->setBaudrate (baudrate); +} + +uint32_t +Serial::getBaudrate () const +{ + return uint32_t(pimpl_->getBaudrate ()); +} + +void +Serial::setBytesize (bytesize_t bytesize) +{ + pimpl_->setBytesize (bytesize); +} + +bytesize_t +Serial::getBytesize () const +{ + return pimpl_->getBytesize (); +} + +void +Serial::setParity (parity_t parity) +{ + pimpl_->setParity (parity); +} + +parity_t +Serial::getParity () const +{ + return pimpl_->getParity (); +} + +void +Serial::setStopbits (stopbits_t stopbits) +{ + pimpl_->setStopbits (stopbits); +} + +stopbits_t +Serial::getStopbits () const +{ + return pimpl_->getStopbits (); +} + +void +Serial::setFlowcontrol (flowcontrol_t flowcontrol) +{ + pimpl_->setFlowcontrol (flowcontrol); +} + +flowcontrol_t +Serial::getFlowcontrol () const +{ + return pimpl_->getFlowcontrol (); +} + +void Serial::flush () +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + pimpl_->flush (); +} + +void Serial::flushInput () +{ + ScopedReadLock lock(this->pimpl_); + pimpl_->flushInput (); +} + +void Serial::flushOutput () +{ + ScopedWriteLock lock(this->pimpl_); + pimpl_->flushOutput (); +} + +void Serial::sendBreak (int duration) +{ + pimpl_->sendBreak (duration); +} + +void Serial::setBreak (bool level) +{ + pimpl_->setBreak (level); +} + +void Serial::setRTS (bool level) +{ + pimpl_->setRTS (level); +} + +void Serial::setDTR (bool level) +{ + pimpl_->setDTR (level); +} + +bool Serial::waitForChange() +{ + return pimpl_->waitForChange(); +} + +bool Serial::getCTS () +{ + return pimpl_->getCTS (); +} + +bool Serial::getDSR () +{ + return pimpl_->getDSR (); +} + +bool Serial::getRI () +{ + return pimpl_->getRI (); +} + +bool Serial::getCD () +{ + return pimpl_->getCD (); +} diff --git a/packages/flserial/macos/Classes/native_libs/src/tinycthread.c b/packages/flserial/macos/Classes/native_libs/src/tinycthread.c new file mode 100644 index 00000000..182bbc38 --- /dev/null +++ b/packages/flserial/macos/Classes/native_libs/src/tinycthread.c @@ -0,0 +1,931 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "../include/tinycthread.h" +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include + #include + #include + #include + #include +#elif defined(_TTHREAD_WIN32_) + #include + #include +#endif + +/* Standard, good-to-have defines */ +#ifndef NULL + #define NULL (void*)0 +#endif +#ifndef TRUE + #define TRUE 1 +#endif +#ifndef FALSE + #define FALSE 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +int mtx_init(mtx_t *mtx, int type) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + mtx->mRecursive = type & mtx_recursive; + mtx->mTimed = type & mtx_timed; + if (!mtx->mTimed) + { + InitializeCriticalSection(&(mtx->mHandle.cs)); + } + else + { + mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL); + if (mtx->mHandle.mut == NULL) + { + return thrd_error; + } + } + return thrd_success; +#else + int ret; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + if (type & mtx_recursive) + { + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + } + ret = pthread_mutex_init(mtx, &attr); + pthread_mutexattr_destroy(&attr); + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +void mtx_destroy(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + DeleteCriticalSection(&(mtx->mHandle.cs)); + } + else + { + CloseHandle(mtx->mHandle.mut); + } +#else + pthread_mutex_destroy(mtx); +#endif +} + +int mtx_lock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + EnterCriticalSection(&(mtx->mHandle.cs)); + } + else + { + switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE)) + { + case WAIT_OBJECT_0: + break; + case WAIT_ABANDONED: + default: + return thrd_error; + } + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + return thrd_success; +#else + return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec current_ts; + DWORD timeoutMs; + + if (!mtx->mTimed) + { + return thrd_error; + } + + timespec_get(¤t_ts, TIME_UTC); + + if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) + { + timeoutMs = 0; + } + else + { + timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; + timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; + timeoutMs += 1; + } + + /* TODO: the timeout for WaitForSingleObject doesn't include time + while the computer is asleep. */ + switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + return thrd_timedout; + case WAIT_ABANDONED: + default: + return thrd_error; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + + return thrd_success; +#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) + switch (pthread_mutex_timedlock(mtx, ts)) { + case 0: + return thrd_success; + case ETIMEDOUT: + return thrd_timedout; + default: + return thrd_error; + } +#else + int rc; + struct timespec cur, dur; + + /* Try to acquire the lock and, if we fail, sleep for 5ms. */ + while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { + timespec_get(&cur, TIME_UTC); + + if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) + { + break; + } + + dur.tv_sec = ts->tv_sec - cur.tv_sec; + dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; + if (dur.tv_nsec < 0) + { + dur.tv_sec--; + dur.tv_nsec += 1000000000; + } + + if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) + { + dur.tv_sec = 0; + dur.tv_nsec = 5000000; + } + + nanosleep(&dur, NULL); + } + + switch (rc) { + case 0: + return thrd_success; + case ETIMEDOUT: + case EBUSY: + return thrd_timedout; + default: + return thrd_error; + } +#endif +} + +int mtx_trylock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + int ret; + + if (!mtx->mTimed) + { + ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy; + } + else + { + ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy; + } + + if ((!mtx->mRecursive) && (ret == thrd_success)) + { + if (mtx->mAlreadyLocked) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + ret = thrd_busy; + } + else + { + mtx->mAlreadyLocked = TRUE; + } + } + return ret; +#else + return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; +#endif +} + +int mtx_unlock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + if (!mtx->mTimed) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + } + else + { + if (!ReleaseMutex(mtx->mHandle.mut)) + { + return thrd_error; + } + } + return thrd_success; +#else + return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; +#endif +} + +#if defined(_TTHREAD_WIN32_) +#define _CONDITION_EVENT_ONE 0 +#define _CONDITION_EVENT_ALL 1 +#endif + +int cnd_init(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + cond->mWaitersCount = 0; + + /* Init critical section */ + InitializeCriticalSection(&cond->mWaitersCountLock); + + /* Init events */ + cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) + { + cond->mEvents[_CONDITION_EVENT_ALL] = NULL; + return thrd_error; + } + cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + cond->mEvents[_CONDITION_EVENT_ONE] = NULL; + return thrd_error; + } + + return thrd_success; +#else + return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; +#endif +} + +void cnd_destroy(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + } + if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); + } + DeleteCriticalSection(&cond->mWaitersCountLock); +#else + pthread_cond_destroy(cond); +#endif +} + +int cnd_signal(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_broadcast(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) +{ + DWORD result; + int lastWaiter; + + /* Increment number of waiters */ + EnterCriticalSection(&cond->mWaitersCountLock); + ++ cond->mWaitersCount; + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* Release the mutex while waiting for the condition (will decrease + the number of waiters when done)... */ + mtx_unlock(mtx); + + /* Wait for either event to become signaled due to cnd_signal() or + cnd_broadcast() being called */ + result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); + if (result == WAIT_TIMEOUT) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_timedout; + } + else if (result == WAIT_FAILED) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + + /* Check if we are the last waiter */ + EnterCriticalSection(&cond->mWaitersCountLock); + -- cond->mWaitersCount; + lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && + (cond->mWaitersCount == 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we are the last waiter to be notified to stop waiting, reset the event */ + if (lastWaiter) + { + if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + } + + /* Re-acquire the mutex */ + mtx_lock(mtx); + + return thrd_success; +} +#endif + +int cnd_wait(cnd_t *cond, mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + return _cnd_timedwait_win32(cond, mtx, INFINITE); +#else + return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec now; + if (timespec_get(&now, TIME_UTC) == TIME_UTC) + { + unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; + unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; + DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? + (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; + return _cnd_timedwait_win32(cond, mtx, delta); + } + else + return thrd_error; +#else + int ret; + ret = pthread_cond_timedwait(cond, mtx, ts); + if (ret == ETIMEDOUT) + { + return thrd_timedout; + } + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +struct TinyCThreadTSSData { + void* value; + tss_t key; + struct TinyCThreadTSSData* next; +}; + +static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, }; + +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL; +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL; + +static void _tinycthread_tss_cleanup (void); + +static void _tinycthread_tss_cleanup (void) { + struct TinyCThreadTSSData* data; + int iteration; + unsigned int again = 1; + void* value; + + for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++) + { + again = 0; + for (data = _tinycthread_tss_head ; data != NULL ; data = data->next) + { + if (data->value != NULL) + { + value = data->value; + data->value = NULL; + + if (_tinycthread_tss_dtors[data->key] != NULL) + { + again = 1; + _tinycthread_tss_dtors[data->key](value); + } + } + } + } + + while (_tinycthread_tss_head != NULL) { + data = _tinycthread_tss_head->next; + free (_tinycthread_tss_head); + _tinycthread_tss_head = data; + } + _tinycthread_tss_head = NULL; + _tinycthread_tss_tail = NULL; +} + +static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv) +{ + (void)h; + (void)pv; + + if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)) + { + _tinycthread_tss_cleanup(); + } +} + +#if defined(_MSC_VER) + #ifdef _M_X64 + #pragma const_seg(".CRT$XLB") + #else + #pragma data_seg(".CRT$XLB") + #endif + PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback; + #ifdef _M_X64 + #pragma data_seg() + #else + #pragma const_seg() + #endif +#else + PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback; +#endif + +#endif /* defined(_TTHREAD_WIN32_) */ + +/** Information to pass to the new thread (what to run). */ +typedef struct { + thrd_start_t mFunction; /**< Pointer to the function to be executed. */ + void * mArg; /**< Function argument for the thread function. */ +} _thread_start_info; + +/* Thread wrapper function. */ +#if defined(_TTHREAD_WIN32_) +static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg) +#elif defined(_TTHREAD_POSIX_) +static void * _thrd_wrapper_function(void * aArg) +#endif +{ + thrd_start_t fun; + void *arg; + int res; + + /* Get thread startup information */ + _thread_start_info *ti = (_thread_start_info *) aArg; + fun = ti->mFunction; + arg = ti->mArg; + + /* The thread is responsible for freeing the startup information */ + free((void *)ti); + + /* Call the actual client thread function */ + res = fun(arg); + +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + return (DWORD)res; +#else + return (void*)(intptr_t)res; +#endif +} + +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) +{ + /* Fill out the thread startup information (passed to the thread wrapper, + which will eventually free it) */ + _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); + if (ti == NULL) + { + return thrd_nomem; + } + ti->mFunction = func; + ti->mArg = arg; + + /* Create the thread */ +#if defined(_TTHREAD_WIN32_) + *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL); +#elif defined(_TTHREAD_POSIX_) + if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) + { + *thr = 0; + } +#endif + + /* Did we fail to create the thread? */ + if(!*thr) + { + free(ti); + return thrd_error; + } + + return thrd_success; +} + +thrd_t thrd_current(void) +{ +#if defined(_TTHREAD_WIN32_) + return GetCurrentThread(); +#else + return pthread_self(); +#endif +} + +int thrd_detach(thrd_t thr) +{ +#if defined(_TTHREAD_WIN32_) + /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */ + return CloseHandle(thr) != 0 ? thrd_success : thrd_error; +#else + return pthread_detach(thr) == 0 ? thrd_success : thrd_error; +#endif +} + +int thrd_equal(thrd_t thr0, thrd_t thr1) +{ +#if defined(_TTHREAD_WIN32_) + return GetThreadId(thr0) == GetThreadId(thr1); +#else + return pthread_equal(thr0, thr1); +#endif +} + +void thrd_exit(int res) +{ +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + ExitThread((DWORD)res); +#else + pthread_exit((void*)(intptr_t)res); +#endif +} + +int thrd_join(thrd_t thr, int *res) +{ +#if defined(_TTHREAD_WIN32_) + DWORD dwRes; + + if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) + { + return thrd_error; + } + if (res != NULL) + { + if (GetExitCodeThread(thr, &dwRes) != 0) + { + *res = (int) dwRes; + } + else + { + return thrd_error; + } + } + CloseHandle(thr); +#elif defined(_TTHREAD_POSIX_) + void *pres; + if (pthread_join(thr, &pres) != 0) + { + return thrd_error; + } + if (res != NULL) + { + *res = (int)(intptr_t)pres; + } +#endif + return thrd_success; +} + +int thrd_sleep(const struct timespec *duration, struct timespec *remaining) +{ +#if !defined(_TTHREAD_WIN32_) + int res = nanosleep(duration, remaining); + if (res == 0) { + return 0; + } else if (errno == EINTR) { + return -1; + } else { + return -2; + } +#else + struct timespec start; + DWORD t; + + timespec_get(&start, TIME_UTC); + + t = SleepEx((DWORD)(duration->tv_sec * 1000 + + duration->tv_nsec / 1000000 + + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), + TRUE); + + if (t == 0) { + return 0; + } else { + if (remaining != NULL) { + timespec_get(remaining, TIME_UTC); + remaining->tv_sec -= start.tv_sec; + remaining->tv_nsec -= start.tv_nsec; + if (remaining->tv_nsec < 0) + { + remaining->tv_nsec += 1000000000; + remaining->tv_sec -= 1; + } + } + + return (t == WAIT_IO_COMPLETION) ? -1 : -2; + } +#endif +} + +void thrd_yield(void) +{ +#if defined(_TTHREAD_WIN32_) + Sleep(0); +#else + sched_yield(); +#endif +} + +int tss_create(tss_t *key, tss_dtor_t dtor) +{ +#if defined(_TTHREAD_WIN32_) + *key = TlsAlloc(); + if (*key == TLS_OUT_OF_INDEXES) + { + return thrd_error; + } + _tinycthread_tss_dtors[*key] = dtor; +#else + if (pthread_key_create(key, dtor) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +void tss_delete(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key); + struct TinyCThreadTSSData* prev = NULL; + if (data != NULL) + { + if (data == _tinycthread_tss_head) + { + _tinycthread_tss_head = data->next; + } + else + { + prev = _tinycthread_tss_head; + if (prev != NULL) + { + while (prev->next != data) + { + prev = prev->next; + } + } + } + + if (data == _tinycthread_tss_tail) + { + _tinycthread_tss_tail = prev; + } + + free (data); + } + _tinycthread_tss_dtors[key] = NULL; + TlsFree(key); +#else + pthread_key_delete(key); +#endif +} + +void *tss_get(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + return NULL; + } + return data->value; +#else + return pthread_getspecific(key); +#endif +} + +int tss_set(tss_t key, void *val) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData)); + if (data == NULL) + { + return thrd_error; + } + + data->value = NULL; + data->key = key; + data->next = NULL; + + if (_tinycthread_tss_tail != NULL) + { + _tinycthread_tss_tail->next = data; + } + else + { + _tinycthread_tss_tail = data; + } + + if (_tinycthread_tss_head == NULL) + { + _tinycthread_tss_head = data; + } + + if (!TlsSetValue(key, data)) + { + free (data); + return thrd_error; + } + } + data->value = val; +#else + if (pthread_setspecific(key, val) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_) +int _tthread_timespec_get(struct timespec *ts, int base) +{ +#if defined(_TTHREAD_WIN32_) + struct _timeb tb; +#elif !defined(CLOCK_REALTIME) + struct timeval tv; +#endif + + if (base != TIME_UTC) + { + return 0; + } + +#if defined(_TTHREAD_WIN32_) + _ftime_s(&tb); + ts->tv_sec = (time_t)tb.time; + ts->tv_nsec = 1000000L * (long)tb.millitm; +#elif defined(CLOCK_REALTIME) + base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0; +#else + gettimeofday(&tv, NULL); + ts->tv_sec = (time_t)tv.tv_sec; + ts->tv_nsec = 1000L * (long)tv.tv_usec; +#endif + + return base; +} +#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */ + +#if defined(_TTHREAD_WIN32_) +void call_once(once_flag *flag, void (*func)(void)) +{ + /* The idea here is that we use a spin lock (via the + InterlockedCompareExchange function) to restrict access to the + critical section until we have initialized it, then we use the + critical section to block until the callback has completed + execution. */ + while (flag->status < 3) + { + switch (flag->status) + { + case 0: + if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) { + InitializeCriticalSection(&(flag->lock)); + EnterCriticalSection(&(flag->lock)); + flag->status = 2; + func(); + flag->status = 3; + LeaveCriticalSection(&(flag->lock)); + return; + } + break; + case 1: + break; + case 2: + EnterCriticalSection(&(flag->lock)); + LeaveCriticalSection(&(flag->lock)); + break; + } + } +} +#endif /* defined(_TTHREAD_WIN32_) */ + +#ifdef __cplusplus +} +#endif diff --git a/packages/flserial/macos/flserial.podspec b/packages/flserial/macos/flserial.podspec new file mode 100644 index 00000000..7e0c88ad --- /dev/null +++ b/packages/flserial/macos/flserial.podspec @@ -0,0 +1,27 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flserial.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flserial' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' +end diff --git a/packages/flserial/pubspec.yaml b/packages/flserial/pubspec.yaml new file mode 100644 index 00000000..5b9098c7 --- /dev/null +++ b/packages/flserial/pubspec.yaml @@ -0,0 +1,80 @@ +name: flserial +description: "Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices." +version: 0.3.5 +homepage: https://github.com/grzesl/flserial + +environment: + sdk: ^3.4.0 + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + ffi: ^2.1.3 + test: ^1.25.7 + +dev_dependencies: + ffigen: ^19.1.0 + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) + # which should be registered in the plugin registry. This is required for + # using method channels. + # The Android 'package' specifies package in which the registered class is. + # This is required for using method channels on Android. + # The 'ffiPlugin' specifies that native code should be built and bundled. + # This is required for using `dart:ffi`. + # All these are used by the tooling to maintain consistency when + # adding or updating assets for this project. + # + # Please refer to README.md for a detailed explanation. + plugin: + platforms: + macos: + ffiPlugin: true + android: + ffiPlugin: true + linux: + ffiPlugin: true + windows: + ffiPlugin: true + + # To add assets to your plugin package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/to/asset-from-package + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # To add custom fonts to your plugin package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/to/font-from-package diff --git a/packages/flserial/src/CMakeLists.txt b/packages/flserial/src/CMakeLists.txt new file mode 100644 index 00000000..6a914c05 --- /dev/null +++ b/packages/flserial/src/CMakeLists.txt @@ -0,0 +1,58 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +project(flserial_library VERSION 0.3.5 LANGUAGES C CXX) + +if(MSVC) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif() + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +set(SRC_FILES + "native_libs/src/serial.cpp" + "native_libs/src/tinycthread.c" + "native_libs/src/ringbuffer.c" + "flserial.cpp" + "flserial.def" +) + +if(APPLE) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_osx.cpp) +elseif(ANDROID) + list(APPEND SRC_FILES native_libs/src/cglob.c) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp) +elseif(UNIX) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp) +else() + list(APPEND SRC_FILES native_libs/src/impl/win.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_win.cpp) +endif() + +add_library(flserial SHARED ${SRC_FILES}) + +if(APPLE) +elseif(ANDROID) + target_link_options(flserial PRIVATE "-Wl,-z,max-page-size=16384") +elseif(UNIX) + target_link_libraries(flserial rt pthread) +else() + target_link_libraries(flserial setupapi) +endif() + + + + +include_directories(native_libs/include native_libs/include/serial) + +set_target_properties(flserial PROPERTIES + PUBLIC_HEADER flserial.h + OUTPUT_NAME "flserial" +) + +target_compile_definitions(flserial PUBLIC DART_SHARED_LIB) diff --git a/packages/flserial/src/flserial.cpp b/packages/flserial/src/flserial.cpp new file mode 100644 index 00000000..cb4a955a --- /dev/null +++ b/packages/flserial/src/flserial.cpp @@ -0,0 +1,419 @@ +#include "flserial.h" +#include "native_libs/include/serial/serial.h" +#include "native_libs/include/tinycthread.h" +#include "native_libs/include/ringbuffer.h" +#include +#include +#include +#include + +// Offband (#702/#710): the 8 KB ring overwrote the oldest bytes whenever the +// radio sent faster than Dart drained it, so a 52 KB contact sync arrived +// mostly lost. The ring is now 256 KB (a power of two, as the ring's mask +// needs), the thread never reads more than the ring has room for, and Dart is +// told about data during a burst rather than only when the port goes idle. +#define FL_SERIAL_BUFF_LEN (256 * 1024) +#define FL_SERIAL_READ_CHUNK (8 * 1024) +#define FL_NOTIFY_BYTES (4 * 1024) +#define FL_NOTIFY_INTERVAL std::chrono::milliseconds(10) + +typedef struct _flserial_ +{ + char portname[MAX_PORT_NAME_LEN + 1]; + int baudrate; + serial::Serial *serialport; + enum FlError lasterror; + char lasterrormsg[512]; + thrd_t cthread; + int breakThread; + ring_buffer_t cinfifo; + ring_buffer_t coutfifo; + char inbuff[FL_SERIAL_BUFF_LEN]; + char outbuff[FL_SERIAL_BUFF_LEN]; + mtx_t inFifo_mutex; + mtx_t outFifo_mutex; + flcallback callback; +} FlSerial; + +int SerialThread(void *aArg) +{ + FlSerial *serial = (FlSerial *)aArg; + ring_buffer_size_t res = 0; + uint8_t buff[FL_SERIAL_READ_CHUNK]; + ring_buffer_size_t len = sizeof(buff); + ring_buffer_size_t total = 0; + auto lastNotify = std::chrono::steady_clock::now(); + + while (!serial->breakThread) + { + try + { + // Read only what the ring can hold. When it is full, leave the + // bytes in the OS driver: USB flow control holds the sender, and + // nothing is overwritten. + mtx_lock(&serial->inFifo_mutex); + ring_buffer_size_t room = RING_BUFFER_MASK((&serial->cinfifo)) - + ring_buffer_num_items(&serial->cinfifo); + mtx_unlock(&serial->inFifo_mutex); + + res = 0; + if (room > 0) + { + res = (int)serial->serialport->read( + (uint8_t *)buff, (size_t)(std::min)(len, room)); + } + if (res > 0) + { + mtx_lock(&serial->inFifo_mutex); + ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res); + mtx_unlock(&serial->inFifo_mutex); + total += res; + } + + bool idle = !serial->serialport->available(); + auto now = std::chrono::steady_clock::now(); + if (total > 0 && + (idle || room == 0 || total >= FL_NOTIFY_BYTES || + now - lastNotify >= FL_NOTIFY_INTERVAL)) + { + serial->callback(0, (unsigned int)total); + total = 0; + lastNotify = now; + } + + if (room == 0) + { + // Give Dart time to drain before trying again. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + else if (res > 0 && !idle) + { + continue; + } + + mtx_lock(&serial->outFifo_mutex); + res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len); + mtx_unlock(&serial->outFifo_mutex); + if (res > 0) { + res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res); + } + + + } + catch (const serial::IOException &ioe) + { + serial->lasterror = FL_ERROR_IO; + strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1); + } + } + + return 0; +} + +FlSerial *flserial_tab[MAX_PORT_COUNT]; +int flserial_count; +int current_port; + +/// Internal helper: close a single slot and null it out. +/// Safe to call with a NULL entry — returns immediately. +/// Sets breakThread=1 then calls thrd_join() so the SerialThread is +/// guaranteed to have exited before this function returns. This is the +/// critical ordering that prevents the Dart NativeCallable from being +/// invoked after the isolate has freed it ("Callback invoked after it has +/// been deleted"). +static void _fl_close_slot(int slot) +{ + FlSerial *port = flserial_tab[slot]; + if (port == NULL) + return; + + port->breakThread = 1; + + try + { + if (port->cthread != 0) + thrd_join(port->cthread, NULL); + + port->serialport->close(); + + mtx_destroy(&port->inFifo_mutex); + mtx_destroy(&port->outFifo_mutex); + } + catch (const std::exception &) + { + } + + delete port->serialport; + port->serialport = NULL; + delete port; + flserial_tab[slot] = NULL; +} + +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb) +{ + FlSerial *port = flserial_tab[flh]; + port->callback = cb; + return 0; +} + +FFI_PLUGIN_EXPORT int fl_init(int portCount) +{ + if (portCount > MAX_PORT_COUNT) + return 1; + + flserial_count = portCount; + current_port = -1; + + return 0; +} + +FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) +{ + int porth = flh; + + if (porth < 0) + porth = ++current_port; + + // If a previous FlSerial (and its SerialThread) is alive in this slot, + // join and free it before overwriting. On Dart hot restart the isolate + // dies without calling fl_close(), leaving the old thread running with a + // dangling NativeCallable pointer. Joining here prevents the crash. + _fl_close_slot(porth); + + FlSerial *port = new FlSerial(); + port->breakThread = 0; + // Before anything can fail or start the reader thread: the thread locks + // inFifo_mutex on its first pass, and _fl_close_slot destroys both even + // when open() threw. + mtx_init(&port->inFifo_mutex, mtx_plain); + mtx_init(&port->outFifo_mutex, mtx_plain); + + flserial_tab[porth] = port; + + strncpy(port->portname, portname, MAX_PORT_NAME_LEN); + + port->baudrate = baudrate; + port->lasterror = FL_ERROR_OK; + + port->serialport = new serial::Serial(); +#if !defined(__linux__) && !defined(__APPLE__) + port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); +#endif // #if defined(__linux__) + port->serialport->setPort(portname); + port->serialport->setBaudrate(baudrate); + + try + { + port->serialport->open(); + + ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN ); + ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN ); + + port->serialport->setBytesize(serial::bytesize_t::eightbits); + port->serialport->setParity(serial::parity_t::parity_none); + port->serialport->setStopbits(serial::stopbits_one); + thrd_create(&port->cthread, SerialThread, (void *)port); + } + catch (const serial::IOException &ioe) + { + strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1); + + switch (ioe.getErrorNumber()) + { + case 1: + port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST; + break; + case 2: + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + break; + default: + port->lasterror = FlError::FL_ERROR_UNKNOW; + break; + } + } + catch (const std::exception) + { + port->lasterror = FlError::FL_ERROR_UNKNOW; + } + + return porth; +} + +FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff) +{ + auto list = serial::list_ports(); + if (serial::list_ports().size() <= index) + { + return 0; + } + else + { + serial::PortInfo info = list[index]; + return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str()); + } +} + +FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff) +{ + FlSerial *port = flserial_tab[flh]; + ring_buffer_size_t res = 0; + + char *buf = NULL; + ring_buffer_size_t size = 0; + ring_buffer_size_t read = 0; + + mtx_lock(&port->inFifo_mutex); + read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len); + mtx_unlock(&port->inFifo_mutex); + + return (int)read; +} + +FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data) +{ + FlSerial *port = flserial_tab[flh]; + int res = 0; + try + { + mtx_lock(&port->outFifo_mutex); + ring_buffer_queue_arr(&port->coutfifo, data, len); + mtx_unlock(&port->outFifo_mutex); + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + + return res; +} + +FFI_PLUGIN_EXPORT int fl_close(int flh) +{ + _fl_close_slot(flh); + return 0; +} + +FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value) +{ + + int result = -1; + FlSerial *port = flserial_tab[flh]; + + try + { + switch (param) + { + case FL_CTRL_IS_PORT_OPEN: + result = port->serialport->isOpen() ? 1 : 0; + break; + case FL_CTRL_LAST_ERROR: + result = port->lasterror; + break; + case FL_CTRL_BREAK: + port->serialport->setBreak(); + result = FL_ERROR_OK; + break; + case FL_CTRL_SET_RTS: + port->serialport->setRTS(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_CTS: + result = port->serialport->getCTS() ? 1 : 0; + break; + case FL_CTRL_SET_DTR: + port->serialport->setDTR(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_DSR: + result = port->serialport->getDSR() ? 1 : 0; + break; + + case FL_CTRL_SET_BYTESIZE_5: + port->serialport->setBytesize(serial::bytesize_t::fivebits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_6: + port->serialport->setBytesize(serial::bytesize_t::sixbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_7: + port->serialport->setBytesize(serial::bytesize_t::sevenbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_8: + port->serialport->setBytesize(serial::bytesize_t::eightbits); + result = 1; + break; + case FL_CTRL_SET_PARITY_NONE: + port->serialport->setParity(serial::parity_t::parity_none); + result = 1; + break; + case FL_CTRL_SET_PARITY_ODD: + port->serialport->setParity(serial::parity_t::parity_odd); + result = 1; + break; + case FL_CTRL_SET_PARITY_EVEN: + port->serialport->setParity(serial::parity_t::parity_even); + result = 1; + break; + case FL_CTRL_SET_PARITY_MARK: + port->serialport->setParity(serial::parity_t::parity_mark); + result = 1; + break; + case FL_CTRL_SET_PARITY_SPACE: + port->serialport->setParity(serial::parity_t::parity_space); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_TWO: + port->serialport->setStopbits(serial::stopbits_t::stopbits_two); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_NONE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_HARDWARE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware); + result = 1; + break; + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software); + result = 1; + case FL_CTRL_SET_FLOWCONTROL_SOFTWARE: + break; + case FL_CTRL_GET_STATUS_CHANGE: + port->serialport->waitForChange(); + result = 1; + break; + + default: + result = -1; + break; + } + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + return result; +} + +FFI_PLUGIN_EXPORT int fl_free(void) +{ + // Join every live SerialThread before the Dart isolate tears down on hot + // restart. Without this, threads holding freed NativeCallable pointers + // crash with "Callback invoked after it has been deleted". + for (int i = 0; i < MAX_PORT_COUNT; i++) + _fl_close_slot(i); + + flserial_count = 0; + current_port = -1; + return 0; +} diff --git a/packages/flserial/src/flserial.def b/packages/flserial/src/flserial.def new file mode 100644 index 00000000..9425a774 --- /dev/null +++ b/packages/flserial/src/flserial.def @@ -0,0 +1,11 @@ +LIBRARY flserial +EXPORTS + fl_init + fl_open + fl_read + fl_write + fl_close + fl_ctrl + fl_free + fl_ports + fl_set_callback \ No newline at end of file diff --git a/packages/flserial/src/flserial.h b/packages/flserial/src/flserial.h new file mode 100644 index 00000000..88f0b11c --- /dev/null +++ b/packages/flserial/src/flserial.h @@ -0,0 +1,79 @@ +#include +#include +#include + +#if _WIN32 +#include +#else +#include +#include +#endif + +#if _WIN32 +#define FFI_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FFI_PLUGIN_EXPORT +#endif + + +#define MAX_PORT_FIFO_LEN 256*1024 +#define MAX_PORT_NAME_LEN 512 +#define MAX_PORT_COUNT 16 + +typedef enum FlCtrl { + FL_CTRL_LAST_ERROR, + FL_CTRL_IS_PORT_OPEN, + FL_CTRL_BREAK, + FL_CTRL_SET_RTS, + FL_CTRL_GET_CTS, + FL_CTRL_SET_DTR, + FL_CTRL_GET_DSR, + FL_CTRL_SET_BYTESIZE_5, + FL_CTRL_SET_BYTESIZE_6, + FL_CTRL_SET_BYTESIZE_7, + FL_CTRL_SET_BYTESIZE_8, + FL_CTRL_SET_PARITY_NONE, + FL_CTRL_SET_PARITY_ODD, + FL_CTRL_SET_PARITY_EVEN, + FL_CTRL_SET_PARITY_MARK, + FL_CTRL_SET_PARITY_SPACE, + FL_CTRL_SET_STOPBITS_ONE, + FL_CTRL_SET_STOPBITS_TWO, + FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, + FL_CTRL_SET_FLOWCONTROL_NONE, + FL_CTRL_SET_FLOWCONTROL_HARDWARE, + FL_CTRL_SET_FLOWCONTROL_SOFTWARE, + FL_CTRL_GET_STATUS_CHANGE, + FL_CTRL_LAST, +} FlCtrl; + +typedef enum FlError { + FL_ERROR_OK, + FL_ERROR_UNKNOW, + FL_ERROR_PORT_ALLREADY_OPEN, + FL_ERROR_PORT_NOT_EXIST, + FL_ERROR_IO, + FL_ERROR_HANDLER, + FL_ERROR_LAST, +} FlError; + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*flcallback)(unsigned int, unsigned int); + +FFI_PLUGIN_EXPORT int fl_init (int portCount); +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb); +FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff); +FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate); +FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff); +FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data); +FFI_PLUGIN_EXPORT int fl_close (int flh); +FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value); +FFI_PLUGIN_EXPORT int fl_free (void); + + +#ifdef __cplusplus +} +#endif diff --git a/packages/flserial/src/native_libs/include/cglob.h b/packages/flserial/src/native_libs/include/cglob.h new file mode 100644 index 00000000..8da8abd9 --- /dev/null +++ b/packages/flserial/src/native_libs/include/cglob.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)glob.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD$ + */ + +#ifndef _GLOB_H_ +#define _GLOB_H_ + +#include +#include + +#ifndef _SIZE_T_DECLARED +typedef size_t __size_t; +#define _SIZE_T_DECLARED +#endif + +struct stat; +typedef struct { + size_t gl_pathc; /* Count of total paths so far. */ + size_t gl_matchc; /* Count of paths matching pattern. */ + size_t gl_offs; /* Reserved at beginning of gl_pathv. */ + int gl_flags; /* Copy of flags parameter to glob. */ + char **gl_pathv; /* List of paths matching pattern. */ + /* Copy of errfunc parameter to glob. */ + int (*gl_errfunc)(const char *, int); + + /* + * Alternate filesystem access methods for glob; replacement + * versions of closedir(3), readdir(3), opendir(3), stat(2) + * and lstat(2). + */ + void (*gl_closedir)(void *); + struct dirent *(*gl_readdir)(void *); + void *(*gl_opendir)(const char *); + int (*gl_lstat)(const char *, struct stat *); + int (*gl_stat)(const char *, struct stat *); +} cglob_t; + + +/* Believed to have been introduced in 1003.2-1992 */ +#define GLOB_APPEND 0x0001 /* Append to output from previous call. */ +#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */ +#define GLOB_ERR 0x0004 /* Return on error. */ +#define GLOB_MARK 0x0008 /* Append / to matching directories. */ +#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */ +#define GLOB_NOSORT 0x0020 /* Don't sort. */ +#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */ + +/* Error values returned by glob(3) */ +#define GLOB_NOSPACE (-1) /* Malloc call failed. */ +#define GLOB_ABORTED (-2) /* Unignored error. */ +#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */ +#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */ + + + +#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */ +#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */ +#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */ +#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */ +#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */ +#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */ +#define GLOB_LIMIT 0x1000 /* limit number of returned paths */ + +/* source compatibility, these are the old names */ +#define GLOB_MAXPATH GLOB_LIMIT +#define GLOB_ABEND GLOB_ABORTED + +__BEGIN_DECLS +int cglob(const char *, int, int (*)(const char *, int), cglob_t *); +void cglobfree(cglob_t *); +__END_DECLS + +#endif /* !_GLOB_H_ */ diff --git a/packages/flserial/src/native_libs/include/ringbuffer.h b/packages/flserial/src/native_libs/include/ringbuffer.h new file mode 100644 index 00000000..36da6eb1 --- /dev/null +++ b/packages/flserial/src/native_libs/include/ringbuffer.h @@ -0,0 +1,144 @@ +#include +#include +#include +/** + * @file + * Prototypes and structures for the ring buffer module. + */ + +#ifndef RINGBUFFER_H +#define RINGBUFFER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RING_BUFFER_ASSERT(x) assert(x) + +/** + * Checks if the buffer_size is a power of two. + * Due to the design only RING_BUFFER_SIZE-1 items + * can be contained in the buffer. + * buffer_size must be a power of two. +*/ +#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0) + +/** + * The type which is used to hold the size + * and the indicies of the buffer. + */ +typedef size_t ring_buffer_size_t; + +/** + * Used as a modulo operator + * as a % b = (a & (b − 1)) + * where \c a is a positive index in the buffer and + * \c b is the (power of two) size of the buffer. + */ +#define RING_BUFFER_MASK(rb) (rb->buffer_mask) + +/** + * Simplifies the use of struct ring_buffer_t. + */ +typedef struct ring_buffer_t ring_buffer_t; + +/** + * Structure which holds a ring buffer. + * The buffer contains a buffer array + * as well as metadata for the ring buffer. + */ +struct ring_buffer_t { + /** Buffer memory. */ + char *buffer; + /** Buffer mask. */ + ring_buffer_size_t buffer_mask; + /** Index of tail. */ + ring_buffer_size_t tail_index; + /** Index of head. */ + ring_buffer_size_t head_index; +}; + +/** + * Initializes the ring buffer pointed to by buffer. + * This function can also be used to empty/reset the buffer. + * The resulting buffer can contain buf_size-1 bytes. + * @param buffer The ring buffer to initialize. + * @param buf The buffer allocated for the ringbuffer. + * @param buf_size The size of the allocated ringbuffer. + */ +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size); + +/** + * Adds a byte to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data The byte to place. + */ +void ring_buffer_queue(ring_buffer_t *buffer, char data); + +/** + * Adds an array of bytes to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data A pointer to the array of bytes to place in the queue. + * @param size The size of the array. + */ +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size); + +/** + * Returns the oldest byte in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data); + +/** + * Returns the len oldest bytes in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the array at which the data should be placed. + * @param len The maximum number of bytes to return. + * @return The number of bytes returned. + */ +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len); +/** + * Peeks a ring buffer, i.e. returns an element without removing it. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @param index The index to peek. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index); + + +/** + * Returns whether a ring buffer is empty. + * @param buffer The buffer for which it should be returned whether it is empty. + * @return 1 if empty; 0 otherwise. + */ +inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) { + return (buffer->head_index == buffer->tail_index); +} + +/** + * Returns whether a ring buffer is full. + * @param buffer The buffer for which it should be returned whether it is full. + * @return 1 if full; 0 otherwise. + */ +inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer); +} + +/** + * Returns the number of items in a ring buffer. + * @param buffer The buffer for which the number of items should be returned. + * @return The number of items in the ring buffer. + */ +inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)); +} + +#ifdef __cplusplus +} +#endif + +#endif /* RINGBUFFER_H */ diff --git a/packages/flserial/src/native_libs/include/serial/impl/unix.h b/packages/flserial/src/native_libs/include/serial/impl/unix.h new file mode 100644 index 00000000..02d85e9d --- /dev/null +++ b/packages/flserial/src/native_libs/include/serial/impl/unix.h @@ -0,0 +1,221 @@ +/*! + * \file serial/impl/unix.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a unix based pimpl for the Serial class. This implementation is + * based off termios.h and uses select for multiplexing the IO ports. + * + */ + +#if !defined(_WIN32) + +#ifndef SERIAL_IMPL_UNIX_H +#define SERIAL_IMPL_UNIX_H + +#include "../../../include/serial/serial.h" + +#include + +namespace serial { + +using std::size_t; +using std::string; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class MillisecondTimer { +public: + MillisecondTimer(const uint32_t millis); + int64_t remaining(); + +private: + static timespec timespec_now(); + timespec expiry; +}; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + string port_; // Path to the file descriptor + int fd_; // The current file descriptor + + bool is_open_; + bool xonxoff_; + bool rtscts_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + pthread_mutex_t read_mutex; + // Mutex used to lock the write functions + pthread_mutex_t write_mutex; +}; + +} + +#endif // SERIAL_IMPL_UNIX_H + +#endif // !defined(_WIN32) diff --git a/packages/flserial/src/native_libs/include/serial/impl/win.h b/packages/flserial/src/native_libs/include/serial/impl/win.h new file mode 100644 index 00000000..2c0c6cde --- /dev/null +++ b/packages/flserial/src/native_libs/include/serial/impl/win.h @@ -0,0 +1,207 @@ +/*! + * \file serial/impl/windows.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a windows implementation of the Serial class interface. + * + */ + +#if defined(_WIN32) + +#ifndef SERIAL_IMPL_WINDOWS_H +#define SERIAL_IMPL_WINDOWS_H + +#include "serial/serial.h" + +#include "windows.h" + +namespace serial { + +using std::string; +using std::wstring; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + wstring port_; // Path to the file descriptor + HANDLE fd_; + + bool is_open_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + HANDLE read_mutex; + // Mutex used to lock the write functions + HANDLE write_mutex; +}; + +} + +#endif // SERIAL_IMPL_WINDOWS_H + +#endif // if defined(_WIN32) diff --git a/packages/flserial/src/native_libs/include/serial/serial.h b/packages/flserial/src/native_libs/include/serial/serial.h new file mode 100644 index 00000000..642febf3 --- /dev/null +++ b/packages/flserial/src/native_libs/include/serial/serial.h @@ -0,0 +1,780 @@ +/*! + * \file serial/serial.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a cross platform interface for interacting with Serial Ports. + */ + +#ifndef SERIAL_H +#define SERIAL_H + +#include +#include +#include +#include +#include +#include +#include +#include "v8stdint.h" + + + +#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \ +__LINE__, (message), (errorno) ) + +#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \ +__LINE__, (message) ) + +namespace serial { + +/*! + * Enumeration defines the possible bytesizes for the serial port. + */ +typedef enum { + fivebits = 5, + sixbits = 6, + sevenbits = 7, + eightbits = 8 +} bytesize_t; + +/*! + * Enumeration defines the possible parity types for the serial port. + */ +typedef enum { + parity_none = 0, + parity_odd = 1, + parity_even = 2, + parity_mark = 3, + parity_space = 4 +} parity_t; + +/*! + * Enumeration defines the possible stopbit types for the serial port. + */ +typedef enum { + stopbits_one = 1, + stopbits_two = 2, + stopbits_one_point_five +} stopbits_t; + +/*! + * Enumeration defines the possible flowcontrol types for the serial port. + */ +typedef enum { + flowcontrol_none = 0, + flowcontrol_software, + flowcontrol_hardware +} flowcontrol_t; + +/*! + * Structure for setting the timeout of the serial port, times are + * in milliseconds. + * + * In order to disable the interbyte timeout, set it to Timeout::max(). + */ +struct Timeout { +#ifdef max +# undef max +#endif + static uint32_t max() {return std::numeric_limits::max();} + /*! + * Convenience function to generate Timeout structs using a + * single absolute timeout. + * + * \param timeout A long that defines the time in milliseconds until a + * timeout occurs after a call to read or write is made. + * + * \return Timeout struct that represents this simple timeout provided. + */ + static Timeout simpleTimeout(uint32_t timeout) { + return Timeout(10, timeout, 0, timeout, 0); + } + + /*! Number of milliseconds between bytes received to timeout on. */ + uint32_t inter_byte_timeout; + /*! A constant number of milliseconds to wait after calling read. */ + uint32_t read_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling read. + */ + uint32_t read_timeout_multiplier; + /*! A constant number of milliseconds to wait after calling write. */ + uint32_t write_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling write. + */ + uint32_t write_timeout_multiplier; + + explicit Timeout (uint32_t inter_byte_timeout_=0, + uint32_t read_timeout_constant_=0, + uint32_t read_timeout_multiplier_=0, + uint32_t write_timeout_constant_=0, + uint32_t write_timeout_multiplier_=0) + : inter_byte_timeout(inter_byte_timeout_), + read_timeout_constant(read_timeout_constant_), + read_timeout_multiplier(read_timeout_multiplier_), + write_timeout_constant(write_timeout_constant_), + write_timeout_multiplier(write_timeout_multiplier_) + {} +}; + +/*! + * Class that provides a portable serial port interface. + */ +class Serial { +public: + /*! + * Creates a Serial object and opens the port if a port is specified, + * otherwise it remains closed until serial::Serial::open is called. + * + * \param port A std::string containing the address of the serial port, + * which would be something like 'COM1' on Windows and '/dev/ttyS0' + * on Linux. + * + * \param baudrate An unsigned 32-bit integer that represents the baudrate + * + * \param timeout A serial::Timeout struct that defines the timeout + * conditions for the serial port. \see serial::Timeout + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \param flowcontrol Type of flowcontrol used, default is + * flowcontrol_none, possible values are: flowcontrol_none, + * flowcontrol_software, flowcontrol_hardware + * + * \throw serial::PortNotOpenedException + * \throw serial::IOException + * \throw std::invalid_argument + */ + Serial (const std::string &port = "", + uint32_t baudrate = 9600, + Timeout timeout = Timeout(), + bytesize_t bytesize = eightbits, + parity_t parity = parity_none, + stopbits_t stopbits = stopbits_one, + flowcontrol_t flowcontrol = flowcontrol_none); + + /*! Destructor */ + virtual ~Serial (); + + /*! + * Opens the serial port as long as the port is set and the port isn't + * already open. + * + * If the port is provided to the constructor then an explicit call to open + * is not needed. + * + * \see Serial::Serial + * + * \throw std::invalid_argument + * \throw serial::SerialException + * \throw serial::IOException + */ + void + open (); + + /*! Gets the open status of the serial port. + * + * \return Returns true if the port is open, false otherwise. + */ + bool + isOpen () const; + + /*! Closes the serial port. */ + void + close (); + + /*! Return the number of characters in the buffer. */ + size_t + available (); + + /*! Block until there is serial data to read or read_timeout_constant + * number of milliseconds have elapsed. The return value is true when + * the function exits with the port in a readable state, false otherwise + * (due to timeout or select interruption). */ + bool + waitReadable (); + + /*! Block for a period of time corresponding to the transmission time of + * count characters at present serial settings. This may be used in con- + * junction with waitReadable to read larger blocks of data from the + * port. */ + void + waitByteTimes (size_t count); + + /*! Read a given amount of bytes from the serial port into a given buffer. + * + * The read function will return in one of three cases: + * * The number of requested bytes was read. + * * In this case the number of bytes requested will match the size_t + * returned by read. + * * A timeout occurred, in this case the number of bytes read will not + * match the amount requested, but no exception will be thrown. One of + * two possible timeouts occurred: + * * The inter byte timeout expired, this means that number of + * milliseconds elapsed between receiving bytes from the serial port + * exceeded the inter byte timeout. + * * The total timeout expired, which is calculated by multiplying the + * read timeout multiplier by the number of requested bytes and then + * added to the read timeout constant. If that total number of + * milliseconds elapses after the initial call to read a timeout will + * occur. + * * An exception occurred, in this case an actual exception will be thrown. + * + * \param buffer An uint8_t array of at least the requested size. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (uint8_t *buffer, size_t size); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::vector of uint8_t. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::vector &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::string. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::string &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port and return a string + * containing the data. + * + * \param size A size_t defining how many bytes to be read. + * + * \return A std::string containing the data read from the port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + read (size_t size = 1); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param buffer A std::string reference used to store the data. + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A size_t representing the number of bytes read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A std::string containing the line. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + readline (size_t size = 65536, std::string eol = "\n"); + + /*! Reads in multiple lines until the serial port times out. + * + * This requires a timeout > 0 before it can be run. It will read until a + * timeout occurs and return a list of strings. + * + * \param size A maximum length of combined lines, defaults to 65536 (2^16) + * + * \param eol A string to match against for the EOL. + * + * \return A vector containing the lines. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::vector + readlines (size_t size = 65536, std::string eol = "\n"); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \param size A size_t that indicates how many bytes should be written from + * the given data buffer. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const uint8_t *data, size_t size); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::vector &data); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::string &data); + + /*! Sets the serial port identifier. + * + * \param port A const std::string reference containing the address of the + * serial port, which would be something like 'COM1' on Windows and + * '/dev/ttyS0' on Linux. + * + * \throw std::invalid_argument + */ + void + setPort (const std::string &port); + + /*! Gets the serial port identifier. + * + * \see Serial::setPort + * + * \throw std::invalid_argument + */ + std::string + getPort () const; + + /*! Sets the timeout for reads and writes using the Timeout struct. + * + * There are two timeout conditions described here: + * * The inter byte timeout: + * * The inter_byte_timeout component of serial::Timeout defines the + * maximum amount of time, in milliseconds, between receiving bytes on + * the serial port that can pass before a timeout occurs. Setting this + * to zero will prevent inter byte timeouts from occurring. + * * Total time timeout: + * * The constant and multiplier component of this timeout condition, + * for both read and write, are defined in serial::Timeout. This + * timeout occurs if the total time since the read or write call was + * made exceeds the specified time in milliseconds. + * * The limit is defined by multiplying the multiplier component by the + * number of requested bytes and adding that product to the constant + * component. In this way if you want a read call, for example, to + * timeout after exactly one second regardless of the number of bytes + * you asked for then set the read_timeout_constant component of + * serial::Timeout to 1000 and the read_timeout_multiplier to zero. + * This timeout condition can be used in conjunction with the inter + * byte timeout condition with out any problems, timeout will simply + * occur when one of the two timeout conditions is met. This allows + * users to have maximum control over the trade-off between + * responsiveness and efficiency. + * + * Read and write functions will return in one of three cases. When the + * reading or writing is complete, when a timeout occurs, or when an + * exception occurs. + * + * A timeout of 0 enables non-blocking mode. + * + * \param timeout A serial::Timeout struct containing the inter byte + * timeout, and the read and write timeout constants and multipliers. + * + * \see serial::Timeout + */ + void + setTimeout (Timeout &timeout); + + /*! Sets the timeout for reads and writes. */ + void + setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, + uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, + uint32_t write_timeout_multiplier) + { + Timeout timeout(inter_byte_timeout, read_timeout_constant, + read_timeout_multiplier, write_timeout_constant, + write_timeout_multiplier); + return setTimeout(timeout); + } + + /*! Gets the timeout for reads in seconds. + * + * \return A Timeout struct containing the inter_byte_timeout, and read + * and write timeout constants and multipliers. + * + * \see Serial::setTimeout + */ + Timeout + getTimeout () const; + + /*! Sets the baudrate for the serial port. + * + * Possible baudrates depends on the system but some safe baudrates include: + * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, + * 57600, 115200 + * Some other baudrates that are supported by some comports: + * 128000, 153600, 230400, 256000, 460800, 500000, 921600 + * + * \param baudrate An integer that sets the baud rate for the serial port. + * + * \throw std::invalid_argument + */ + void + setBaudrate (uint32_t baudrate); + + /*! Gets the baudrate for the serial port. + * + * \return An integer that sets the baud rate for the serial port. + * + * \see Serial::setBaudrate + * + * \throw std::invalid_argument + */ + uint32_t + getBaudrate () const; + + /*! Sets the bytesize for the serial port. + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \throw std::invalid_argument + */ + void + setBytesize (bytesize_t bytesize); + + /*! Gets the bytesize for the serial port. + * + * \see Serial::setBytesize + * + * \throw std::invalid_argument + */ + bytesize_t + getBytesize () const; + + /*! Sets the parity for the serial port. + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \throw std::invalid_argument + */ + void + setParity (parity_t parity); + + /*! Gets the parity for the serial port. + * + * \see Serial::setParity + * + * \throw std::invalid_argument + */ + parity_t + getParity () const; + + /*! Sets the stopbits for the serial port. + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \throw std::invalid_argument + */ + void + setStopbits (stopbits_t stopbits); + + /*! Gets the stopbits for the serial port. + * + * \see Serial::setStopbits + * + * \throw std::invalid_argument + */ + stopbits_t + getStopbits () const; + + /*! Sets the flow control for the serial port. + * + * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, + * possible values are: flowcontrol_none, flowcontrol_software, + * flowcontrol_hardware + * + * \throw std::invalid_argument + */ + void + setFlowcontrol (flowcontrol_t flowcontrol); + + /*! Gets the flow control for the serial port. + * + * \see Serial::setFlowcontrol + * + * \throw std::invalid_argument + */ + flowcontrol_t + getFlowcontrol () const; + + /*! Flush the input and output buffers */ + void + flush (); + + /*! Flush only the input buffer */ + void + flushInput (); + + /*! Flush only the output buffer */ + void + flushOutput (); + + /*! Sends the RS-232 break signal. See tcsendbreak(3). */ + void + sendBreak (int duration); + + /*! Set the break condition to a given level. Defaults to true. */ + void + setBreak (bool level = true); + + /*! Set the RTS handshaking line to the given level. Defaults to true. */ + void + setRTS (bool level = true); + + /*! Set the DTR handshaking line to the given level. Defaults to true. */ + void + setDTR (bool level = true); + + /*! + * Blocks until CTS, DSR, RI, CD changes or something interrupts it. + * + * Can throw an exception if an error occurs while waiting. + * You can check the status of CTS, DSR, RI, and CD once this returns. + * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a + * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a + * polling method is used which can give +-2ms. + * + * \return Returns true if one of the lines changed, false if something else + * occurred. + * + * \throw SerialException + */ + bool + waitForChange (); + + /*! Returns the current status of the CTS line. */ + bool + getCTS (); + + /*! Returns the current status of the DSR line. */ + bool + getDSR (); + + /*! Returns the current status of the RI line. */ + bool + getRI (); + + /*! Returns the current status of the CD line. */ + bool + getCD (); + +private: + // Disable copy constructors + Serial(const Serial&); + Serial& operator=(const Serial&); + + // Pimpl idiom, d_pointer + class SerialImpl; + SerialImpl *pimpl_; + + // Scoped Lock Classes + class ScopedReadLock; + class ScopedWriteLock; + + // Read common function + size_t + read_ (uint8_t *buffer, size_t size); + // Write common function + size_t + write_ (const uint8_t *data, size_t length); + +}; + +class SerialException : public std::exception +{ + // Disable copy constructors + SerialException& operator=(const SerialException&); + std::string e_what_; +public: + SerialException (const char *description) { + std::stringstream ss; + ss << "SerialException " << description << " failed."; + e_what_ = ss.str(); + } + SerialException (const SerialException& other) : e_what_(other.e_what_) {} + virtual ~SerialException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class IOException : public std::exception +{ + // Disable copy constructors + IOException& operator=(const IOException&); + std::string file_; + int line_; + std::string e_what_; + int errno_; +public: + explicit IOException (std::string file, int line, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; +#if defined(_WIN32) && !defined(__MINGW32__) + char error_str [1024]; + strerror_s(error_str, 1024, errnum); +#else + char * error_str = strerror(errnum); +#endif + ss << "IO Exception (" << errno_ << "): " << error_str; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + explicit IOException (std::string file, int line, const char * description, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; + ss << "IO Exception: " << description; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + virtual ~IOException() throw() {} + IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} + + int getErrorNumber () const { return errno_; } + + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class PortNotOpenedException : public std::exception +{ + // Disable copy constructors + const PortNotOpenedException& operator=(PortNotOpenedException); + std::string e_what_; +public: + PortNotOpenedException (const char * description) { + std::stringstream ss; + ss << "PortNotOpenedException " << description << " failed."; + e_what_ = ss.str(); + } + PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} + virtual ~PortNotOpenedException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +/*! + * Structure that describes a serial device. + */ +struct PortInfo { + + /*! Address of the serial port (this can be passed to the constructor of Serial). */ + std::string port; + + /*! Human readable description of serial device if available. */ + std::string description; + + /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ + std::string hardware_id; + +}; + +/* Lists the serial ports available on the system + * + * Returns a vector of available serial ports, each represented + * by a serial::PortInfo data structure: + * + * \return vector of serial::PortInfo. + */ +std::vector +list_ports(); + +} // namespace serial + +#endif diff --git a/packages/flserial/src/native_libs/include/serial/v8stdint.h b/packages/flserial/src/native_libs/include/serial/v8stdint.h new file mode 100644 index 00000000..f3be96b1 --- /dev/null +++ b/packages/flserial/src/native_libs/include/serial/v8stdint.h @@ -0,0 +1,57 @@ +// This header is from the v8 google project: +// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h + +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Load definitions of standard types. + +#ifndef V8STDINT_H_ +#define V8STDINT_H_ + +#include +#include + +#if defined(_WIN32) && !defined(__MINGW32__) + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; // NOLINT +typedef unsigned short uint16_t; // NOLINT +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +// intptr_t and friends are defined in crtdefs.h through stdio.h. + +#else + +#include + +#endif + +#endif // V8STDINT_H_ diff --git a/packages/flserial/src/native_libs/include/tinycthread.h b/packages/flserial/src/native_libs/include/tinycthread.h new file mode 100644 index 00000000..2fc7f628 --- /dev/null +++ b/packages/flserial/src/native_libs/include/tinycthread.h @@ -0,0 +1,479 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef _TINYCTHREAD_H_ +#define _TINYCTHREAD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @file +* @mainpage TinyCThread API Reference +* +* @section intro_sec Introduction +* TinyCThread is a minimal, portable implementation of basic threading +* classes for C. +* +* They closely mimic the functionality and naming of the C11 standard, and +* should be easily replaceable with the corresponding standard variants. +* +* @section port_sec Portability +* The Win32 variant uses the native Win32 API for implementing the thread +* classes, while for other systems, the POSIX threads API (pthread) is used. +* +* @section misc_sec Miscellaneous +* The following special keywords are available: #_Thread_local. +* +* For more detailed information, browse the different sections of this +* documentation. A good place to start is: +* tinycthread.h. +*/ + +/* Which platform are we on? */ +#if !defined(_TTHREAD_PLATFORM_DEFINED_) + #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) + #define _TTHREAD_WIN32_ + #else + #define _TTHREAD_POSIX_ + #endif + #define _TTHREAD_PLATFORM_DEFINED_ +#endif + +/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */ +#if defined(_TTHREAD_POSIX_) + #undef _FEATURES_H + #if !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L) + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L + #endif + #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500) + #undef _XOPEN_SOURCE + #define _XOPEN_SOURCE 500 + #endif + #define _XPG6 +#endif + +/* Generic includes */ +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include +#elif defined(_TTHREAD_WIN32_) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #define __UNDEF_LEAN_AND_MEAN + #endif + #include + #ifdef __UNDEF_LEAN_AND_MEAN + #undef WIN32_LEAN_AND_MEAN + #undef __UNDEF_LEAN_AND_MEAN + #endif +#endif + +/* Compiler-specific information */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define TTHREAD_NORETURN _Noreturn +#elif defined(__GNUC__) + #define TTHREAD_NORETURN __attribute__((__noreturn__)) +#else + #define TTHREAD_NORETURN +#endif + +/* If TIME_UTC is missing, provide it and provide a wrapper for + timespec_get. */ +#ifndef TIME_UTC +#define TIME_UTC 1 +#define _TTHREAD_EMULATE_TIMESPEC_GET_ + +#if defined(_TTHREAD_WIN32_) +struct _tthread_timespec { + time_t tv_sec; + long tv_nsec; +}; +#define timespec _tthread_timespec +#endif + +int _tthread_timespec_get(struct timespec *ts, int base); +#define timespec_get _tthread_timespec_get +#endif + +/** TinyCThread version (major number). */ +#define TINYCTHREAD_VERSION_MAJOR 1 +/** TinyCThread version (minor number). */ +#define TINYCTHREAD_VERSION_MINOR 2 +/** TinyCThread version (full version). */ +#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) + +/** +* @def _Thread_local +* Thread local storage keyword. +* A variable that is declared with the @c _Thread_local keyword makes the +* value of the variable local to each thread (known as thread-local storage, +* or TLS). Example usage: +* @code +* // This variable is local to each thread. +* _Thread_local int variable; +* @endcode +* @note The @c _Thread_local keyword is a macro that maps to the corresponding +* compiler directive (e.g. @c __declspec(thread)). +* @note This directive is currently not supported on Mac OS X (it will give +* a compiler error), since compile-time TLS is not supported in the Mac OS X +* executable format. Also, some older versions of MinGW (before GCC 4.x) do +* not support this directive, nor does the Tiny C Compiler. +* @hideinitializer +*/ + +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) + #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) + #define _Thread_local __thread + #else + #define _Thread_local __declspec(thread) + #endif +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9)) + #define _Thread_local __thread +#endif + +/* Macros */ +#if defined(_TTHREAD_WIN32_) +#define TSS_DTOR_ITERATIONS (4) +#else +#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS +#endif + +/* Function return values */ +#define thrd_error 0 /**< The requested operation failed */ +#define thrd_success 1 /**< The requested operation succeeded */ +#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */ +#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ +#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ + +/* Mutex types */ +#define mtx_plain 0 +#define mtx_timed 1 +#define mtx_recursive 2 + +/* Mutex */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + union { + CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */ + HANDLE mut; /* Mutex handle (used for timed mutex) */ + } mHandle; /* Mutex handle */ + int mAlreadyLocked; /* TRUE if the mutex is already locked */ + int mRecursive; /* TRUE if the mutex is recursive */ + int mTimed; /* TRUE if the mutex is timed */ +} mtx_t; +#else +typedef pthread_mutex_t mtx_t; +#endif + +/** Create a mutex object. +* @param mtx A mutex object. +* @param type Bit-mask that must have one of the following six values: +* @li @c mtx_plain for a simple non-recursive mutex +* @li @c mtx_timed for a non-recursive mutex that supports timeout +* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) +* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_init(mtx_t *mtx, int type); + +/** Release any resources used by the given mutex. +* @param mtx A mutex object. +*/ +void mtx_destroy(mtx_t *mtx); + +/** Lock the given mutex. +* Blocks until the given mutex can be locked. If the mutex is non-recursive, and +* the calling thread already has a lock on the mutex, this call will block +* forever. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_lock(mtx_t *mtx); + +/** Lock the given mutex, or block until a specific point in time. +* Blocks until either the given mutex can be locked, or the specified TIME_UTC +* based time. +* @param mtx A mutex object. +* @param ts A UTC based calendar time +* @return @ref The mtx_timedlock function returns thrd_success on success, or +* thrd_timedout if the time specified was reached without acquiring the +* requested resource, or thrd_error if the request could not be honored. +*/ +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); + +/** Try to lock the given mutex. +* The specified mutex shall support either test and return or timeout. If the +* mutex is already locked, the function returns without blocking. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_busy if the resource +* requested is already in use, or @ref thrd_error if the request could not be +* honored. +*/ +int mtx_trylock(mtx_t *mtx); + +/** Unlock the given mutex. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_unlock(mtx_t *mtx); + +/* Condition variable */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */ + unsigned int mWaitersCount; /* Count of the number of waiters. */ + CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */ +} cnd_t; +#else +typedef pthread_cond_t cnd_t; +#endif + +/** Create a condition variable object. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_init(cnd_t *cond); + +/** Release any resources used by the given condition variable. +* @param cond A condition variable object. +*/ +void cnd_destroy(cnd_t *cond); + +/** Signal a condition variable. +* Unblocks one of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_signal(cnd_t *cond); + +/** Broadcast a condition variable. +* Unblocks all of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_broadcast(cnd_t *cond); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex +* before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_wait(cnd_t *cond, mtx_t *mtx); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast, or until after the specified time. When the calling thread +* becomes unblocked it locks the mutex before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @param xt A point in time at which the request will time out (absolute time). +* @return @ref thrd_success upon success, or @ref thrd_timeout if the time +* specified in the call was reached without acquiring the requested resource, or +* @ref thrd_error if the request could not be honored. +*/ +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts); + +/* Thread */ +#if defined(_TTHREAD_WIN32_) +typedef HANDLE thrd_t; +#else +typedef pthread_t thrd_t; +#endif + +/** Thread start function. +* Any thread that is started with the @ref thrd_create() function must be +* started through a function of this type. +* @param arg The thread argument (the @c arg argument of the corresponding +* @ref thrd_create() call). +* @return The thread return value, which can be obtained by another thread +* by using the @ref thrd_join() function. +*/ +typedef int (*thrd_start_t)(void *arg); + +/** Create a new thread. +* @param thr Identifier of the newly created thread. +* @param func A function pointer to the function that will be executed in +* the new thread. +* @param arg An argument to the thread function. +* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could +* be allocated for the thread requested, or @ref thrd_error if the request +* could not be honored. +* @note A thread’s identifier may be reused for a different thread once the +* original thread has exited and either been detached or joined to another +* thread. +*/ +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); + +/** Identify the calling thread. +* @return The identifier of the calling thread. +*/ +thrd_t thrd_current(void); + +/** Dispose of any resources allocated to the thread when that thread exits. + * @return thrd_success, or thrd_error on error +*/ +int thrd_detach(thrd_t thr); + +/** Compare two thread identifiers. +* The function determines if two thread identifiers refer to the same thread. +* @return Zero if the two thread identifiers refer to different threads. +* Otherwise a nonzero value is returned. +*/ +int thrd_equal(thrd_t thr0, thrd_t thr1); + +/** Terminate execution of the calling thread. +* @param res Result code of the calling thread. +*/ +TTHREAD_NORETURN void thrd_exit(int res); + +/** Wait for a thread to terminate. +* The function joins the given thread with the current thread by blocking +* until the other thread has terminated. +* @param thr The thread to join with. +* @param res If this pointer is not NULL, the function will store the result +* code of the given thread in the integer pointed to by @c res. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int thrd_join(thrd_t thr, int *res); + +/** Put the calling thread to sleep. +* Suspend execution of the calling thread. +* @param duration Interval to sleep for +* @param remaining If non-NULL, this parameter will hold the remaining +* time until time_point upon return. This will +* typically be zero, but if the thread was woken up +* by a signal that is not ignored before duration was +* reached @c remaining will hold a positive time. +* @return 0 (zero) on successful sleep, -1 if an interrupt occurred, +* or a negative value if the operation fails. +*/ +int thrd_sleep(const struct timespec *duration, struct timespec *remaining); + +/** Yield execution to another thread. +* Permit other threads to run, even if the current thread would ordinarily +* continue to run. +*/ +void thrd_yield(void); + +/* Thread local storage */ +#if defined(_TTHREAD_WIN32_) +typedef DWORD tss_t; +#else +typedef pthread_key_t tss_t; +#endif + +/** Destructor function for a thread-specific storage. +* @param val The value of the destructed thread-specific storage. +*/ +typedef void (*tss_dtor_t)(void *val); + +/** Create a thread-specific storage. +* @param key The unique key identifier that will be set if the function is +* successful. +* @param dtor Destructor function. This can be NULL. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +* @note On Windows, the @c dtor will definitely be called when +* appropriate for threads created with @ref thrd_create. It will be +* called for other threads in most cases, the possible exception being +* for DLLs loaded with LoadLibraryEx. In order to be certain, you +* should use @ref thrd_create whenever possible. +*/ +int tss_create(tss_t *key, tss_dtor_t dtor); + +/** Delete a thread-specific storage. +* The function releases any resources used by the given thread-specific +* storage. +* @param key The key that shall be deleted. +*/ +void tss_delete(tss_t key); + +/** Get the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @return The value for the current thread held in the given thread-specific +* storage. +*/ +void *tss_get(tss_t key); + +/** Set the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @param val The value of the thread-specific storage to set for the current +* thread. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int tss_set(tss_t key, void *val); + +#if defined(_TTHREAD_WIN32_) + typedef struct { + LONG volatile status; + CRITICAL_SECTION lock; + } once_flag; + #define ONCE_FLAG_INIT {0,} +#else + #define once_flag pthread_once_t + #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT +#endif + +/** Invoke a callback exactly once + * @param flag Flag used to ensure the callback is invoked exactly + * once. + * @param func Callback to invoke. + */ +#if defined(_TTHREAD_WIN32_) + void call_once(once_flag *flag, void (*func)(void)); +#else + #define call_once(flag,func) pthread_once(flag,func) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TINYTHREAD_H_ */ diff --git a/packages/flserial/src/native_libs/src/LICENSE_glob b/packages/flserial/src/native_libs/src/LICENSE_glob new file mode 100644 index 00000000..8c49b6b4 --- /dev/null +++ b/packages/flserial/src/native_libs/src/LICENSE_glob @@ -0,0 +1,34 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ \ No newline at end of file diff --git a/packages/flserial/src/native_libs/src/LICENSE_ringbuffer b/packages/flserial/src/native_libs/src/LICENSE_ringbuffer new file mode 100644 index 00000000..4e5491e4 --- /dev/null +++ b/packages/flserial/src/native_libs/src/LICENSE_ringbuffer @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Kalør + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/flserial/src/native_libs/src/LICENSE_serial b/packages/flserial/src/native_libs/src/LICENSE_serial new file mode 100644 index 00000000..bd087f8d --- /dev/null +++ b/packages/flserial/src/native_libs/src/LICENSE_serial @@ -0,0 +1,7 @@ +Copyright (c) 2012 William Woodall, John Harrison + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/flserial/src/native_libs/src/LICENSE_tinycthread b/packages/flserial/src/native_libs/src/LICENSE_tinycthread new file mode 100644 index 00000000..d24cfe88 --- /dev/null +++ b/packages/flserial/src/native_libs/src/LICENSE_tinycthread @@ -0,0 +1,25 @@ + +License +------- + +Copyright (c) 2012 Marcus Geelnard + 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. diff --git a/packages/flserial/src/native_libs/src/cglob.c b/packages/flserial/src/native_libs/src/cglob.c new file mode 100644 index 00000000..7903dbc4 --- /dev/null +++ b/packages/flserial/src/native_libs/src/cglob.c @@ -0,0 +1,908 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +/* + * glob(3) -- a superset of the one defined in POSIX 1003.2. + * + * The [!...] convention to negate a range is supported (SysV, Posix, ksh). + * + * Optional extra services, controlled by flags not defined by POSIX: + * + * GLOB_QUOTE: + * Escaping convention: \ inhibits any special meaning the following + * character might have (except \ at end of string is retained). + * GLOB_MAGCHAR: + * Set in gl_flags if pattern contained a globbing character. + * GLOB_NOMAGIC: + * Same as GLOB_NOCHECK, but it will only append pattern if it did + * not contain any magic characters. [Used in csh style globbing] + * GLOB_ALTDIRFUNC: + * Use alternately specified directory access functions. + * GLOB_TILDE: + * expand ~user/foo to the /home/dir/of/user/foo + * GLOB_BRACE: + * expand {1,2}{a,b} to 1a 1b 2a 2b + * gl_matchc: + * Number of matches in the current invocation of glob. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing - even if + * GLOB_NOCHECK is specified. + * 2. Illegal byte sequences in filenames are handled by treating them as + * single-byte characters with a value of the first byte of the sequence + * cast to wchar_t. + * 3. State-dependent encodings are not currently supported. + */ + +#include +#include + +#include +#include +#include +#include "cglob.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define DOLLAR '$' +#define DOT '.' +#define EOS '\0' +#define LBRACKET '[' +#define NOT '!' +#define QUESTION '?' +#define QUOTE '\\' +#define RANGE '-' +#define RBRACKET ']' +#define SEP '/' +#define STAR '*' +#define TILDE '~' +#define UNDERSCORE '_' +#define LBRACE '{' +#define RBRACE '}' +#define SLASH '/' +#define COMMA ',' + +#ifndef DEBUG + +#define M_QUOTE 0x8000000000ULL +#define M_PROTECT 0x4000000000ULL +#define M_MASK 0xffffffffffULL +#define M_CHAR 0x00ffffffffULL + +typedef uint_fast64_t Char; + +#else + +#define M_QUOTE 0x80 +#define M_PROTECT 0x40 +#define M_MASK 0xff +#define M_CHAR 0x7f + +typedef char Char; + +#endif + + +#define CHAR(c) ((Char)((c)&M_CHAR)) +#define META(c) ((Char)((c)|M_QUOTE)) +#define M_ALL META('*') +#define M_END META(']') +#define M_NOT META('!') +#define M_ONE META('?') +#define M_RNG META('-') +#define M_SET META('[') +#define ismeta(c) (((c)&M_QUOTE) != 0) + + +static int compare(const void *, const void *); +static int g_Ctoc(const Char *, char *, size_t); +static int g_lstat(Char *, struct stat *, cglob_t *); +static DIR *g_opendir(Char *, cglob_t *); +static const Char *g_strchr(const Char *, wchar_t); +#ifdef notdef +static Char *g_strcat(Char *, const Char *); +#endif +static int g_stat(Char *, struct stat *, cglob_t *); +static int glob0(const Char *, cglob_t *, size_t *); +static int glob1(Char *, cglob_t *, size_t *); +static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int globextend(const Char *, cglob_t *, size_t *); +static const Char * + globtilde(const Char *, Char *, size_t, cglob_t *); +static int globexp1(const Char *, cglob_t *, size_t *); +static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *); +static int match(Char *, Char *, Char *); +#ifdef DEBUG +static void qprintf(const char *, Char *); +#endif + +int +cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob) +{ + const char *patnext; + size_t limit; + Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + patnext = pattern; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathc = 0; + pglob->gl_pathv = NULL; + if (!(flags & GLOB_DOOFFS)) + pglob->gl_offs = 0; + } + + if (flags & GLOB_LIMIT) { + limit = pglob->gl_matchc; + if (limit == 0) + limit = ARG_MAX; + } else + limit = 0; + + pglob->gl_flags = flags & ~GLOB_MAGCHAR; + pglob->gl_errfunc = errfunc; + pglob->gl_matchc = 0; + + bufnext = patbuf; + bufend = bufnext + MAXPATHLEN - 1; + if (flags & GLOB_NOESCAPE) { + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc; + patnext += clen; + } + } else { + /* Protect the quoted characters. */ + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + if (*patnext == QUOTE) { + if (*++patnext == EOS) { + *bufnext++ = QUOTE | M_PROTECT; + continue; + } + prot = M_PROTECT; + } else + prot = 0; + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc | prot; + patnext += clen; + } + } + *bufnext = EOS; + + if (flags & GLOB_BRACE) + return globexp1(patbuf, pglob, &limit); + else + return glob0(patbuf, pglob, &limit); +} + +/* + * Expand recursively a glob {} pattern. When there is no more expansion + * invoke the standard globbing routine to glob the rest of the magic + * characters + */ +static int +globexp1(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char* ptr = pattern; + int rv; + + /* Protect a single {}, for find(1), like csh */ + if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) + return glob0(pattern, pglob, limit); + + while ((ptr = g_strchr(ptr, LBRACE)) != NULL) + if (!globexp2(ptr, pattern, pglob, &rv, limit)) + return rv; + + return glob0(pattern, pglob, limit); +} + + +/* + * Recursive brace globbing helper. Tries to expand a single brace. + * If it succeeds then it invokes globexp1 with the new pattern. + * If it fails then it tries to glob the rest of the pattern and returns. + */ +static int +globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit) +{ + int i; + Char *lm, *ls; + const Char *pe, *pm, *pm1, *pl; + Char patbuf[MAXPATHLEN]; + + /* copy part up to the brace */ + for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++) + continue; + *lm = EOS; + ls = lm; + + /* Find the balanced brace */ + for (i = 0, pe = ++ptr; *pe; pe++) + if (*pe == LBRACKET) { + /* Ignore everything between [] */ + for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++) + continue; + if (*pe == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pe = pm; + } + } + else if (*pe == LBRACE) + i++; + else if (*pe == RBRACE) { + if (i == 0) + break; + i--; + } + + /* Non matching braces; just glob the pattern */ + if (i != 0 || *pe == EOS) { + *rv = glob0(patbuf, pglob, limit); + return 0; + } + + for (i = 0, pl = pm = ptr; pm <= pe; pm++) + switch (*pm) { + case LBRACKET: + /* Ignore everything between [] */ + for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++) + continue; + if (*pm == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pm = pm1; + } + break; + + case LBRACE: + i++; + break; + + case RBRACE: + if (i) { + i--; + break; + } + /* FALLTHROUGH */ + case COMMA: + if (i && *pm == COMMA) + break; + else { + /* Append the current string */ + for (lm = ls; (pl < pm); *lm++ = *pl++) + continue; + /* + * Append the rest of the pattern after the + * closing brace + */ + for (pl = pe + 1; (*lm++ = *pl++) != EOS;) + continue; + + /* Expand the current pattern */ +#ifdef DEBUG + qprintf("globexp2:", patbuf); +#endif + *rv = globexp1(patbuf, pglob, limit); + + /* move after the comma, to the next string */ + pl = pm + 1; + } + break; + + default: + break; + } + *rv = 0; + return 0; +} + + + +/* + * expand tilde from the passwd file. + */ +static const Char * +globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob) +{ + struct passwd *pwd; + char *h; + const Char *p; + Char *b, *eb; + + if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE)) + return pattern; + + /* + * Copy up to the end of the string or / + */ + eb = &patbuf[patbuf_len - 1]; + for (p = pattern + 1, h = (char *) patbuf; + h < (char *)eb && *p && *p != SLASH; *h++ = *p++) + continue; + + *h = EOS; + + if (((char *) patbuf)[0] == EOS) { + /* + * handle a plain ~ or ~/ by expanding $HOME first (iff + * we're not running setuid or setgid) and then trying + * the password file + */ + /*if (issetugid() != 0 || + (h = getenv("HOME")) == NULL) { + if (((h = getlogin()) != NULL && + (pwd = getpwnam(h)) != NULL) || + (pwd = getpwuid(getuid())) != NULL) + h = pwd->pw_dir; + else + return pattern; + }*/ + } + else { + /* + * Expand a ~user + */ + if ((pwd = getpwnam((char*) patbuf)) == NULL) + return pattern; + else + h = pwd->pw_dir; + } + + /* Copy the home directory */ + for (b = patbuf; b < eb && *h; *b++ = *h++) + continue; + + /* Append the rest of the pattern */ + while (b < eb && (*b++ = *p++) != EOS) + continue; + *b = EOS; + + return patbuf; +} + + +/* + * The main glob() routine: compiles the pattern (optionally processing + * quotes), calls glob1() to do the real pattern matching, and finally + * sorts the list (unless unsorted operation is requested). Returns 0 + * if things went well, nonzero if errors occurred. + */ +static int +glob0(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char *qpatnext; + int err; + size_t oldpathc; + Char *bufnext, c, patbuf[MAXPATHLEN]; + + qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); + oldpathc = pglob->gl_pathc; + bufnext = patbuf; + + /* We don't need to check for buffer overflow any more. */ + while ((c = *qpatnext++) != EOS) { + switch (c) { + case LBRACKET: + c = *qpatnext; + if (c == NOT) + ++qpatnext; + if (*qpatnext == EOS || + g_strchr(qpatnext+1, RBRACKET) == NULL) { + *bufnext++ = LBRACKET; + if (c == NOT) + --qpatnext; + break; + } + *bufnext++ = M_SET; + if (c == NOT) + *bufnext++ = M_NOT; + c = *qpatnext++; + do { + *bufnext++ = CHAR(c); + if (*qpatnext == RANGE && + (c = qpatnext[1]) != RBRACKET) { + *bufnext++ = M_RNG; + *bufnext++ = CHAR(c); + qpatnext += 2; + } + } while ((c = *qpatnext++) != RBRACKET); + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_END; + break; + case QUESTION: + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_ONE; + break; + case STAR: + pglob->gl_flags |= GLOB_MAGCHAR; + /* collapse adjacent stars to one, + * to avoid exponential behavior + */ + if (bufnext == patbuf || bufnext[-1] != M_ALL) + *bufnext++ = M_ALL; + break; + default: + *bufnext++ = CHAR(c); + break; + } + } + *bufnext = EOS; +#ifdef DEBUG + qprintf("glob0:", patbuf); +#endif + + if ((err = glob1(patbuf, pglob, limit)) != 0) + return(err); + + /* + * If there was no match we are going to append the pattern + * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified + * and the pattern did not contain any magic characters + * GLOB_NOMAGIC is there just for compatibility with csh. + */ + if (pglob->gl_pathc == oldpathc) { + if (((pglob->gl_flags & GLOB_NOCHECK) || + ((pglob->gl_flags & GLOB_NOMAGIC) && + !(pglob->gl_flags & GLOB_MAGCHAR)))) + return(globextend(pattern, pglob, limit)); + else + return(GLOB_NOMATCH); + } + if (!(pglob->gl_flags & GLOB_NOSORT)) + qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, + pglob->gl_pathc - oldpathc, sizeof(char *), compare); + return(0); +} + +static int +compare(const void *p, const void *q) +{ + return(strcmp(*(char **)p, *(char **)q)); +} + +static int +glob1(Char *pattern, cglob_t *pglob, size_t *limit) +{ + Char pathbuf[MAXPATHLEN]; + + /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ + if (*pattern == EOS) + return(0); + return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, + pattern, pglob, limit)); +} + +/* + * The functions glob2 and glob3 are mutually recursive; there is one level + * of recursion for each segment in the pattern that contains one or more + * meta characters. + */ +static int +glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern, + cglob_t *pglob, size_t *limit) +{ + struct stat sb; + Char *p, *q; + int anymeta; + + /* + * Loop over pattern segments until end of pattern or until + * segment with meta character found. + */ + for (anymeta = 0;;) { + if (*pattern == EOS) { /* End of pattern? */ + *pathend = EOS; + if (g_lstat(pathbuf, &sb, pglob)) + return(0); + + if (((pglob->gl_flags & GLOB_MARK) && + pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) + || (S_ISLNK(sb.st_mode) && + (g_stat(pathbuf, &sb, pglob) == 0) && + S_ISDIR(sb.st_mode)))) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = SEP; + *pathend = EOS; + } + ++pglob->gl_matchc; + return(globextend(pathbuf, pglob, limit)); + } + + /* Find end of next segment, copy tentatively to pathend. */ + q = pathend; + p = pattern; + while (*p != EOS && *p != SEP) { + if (ismeta(*p)) + anymeta = 1; + if (q + 1 > pathend_last) + return (GLOB_ABORTED); + *q++ = *p++; + } + + if (!anymeta) { /* No expansion, do next segment. */ + pathend = q; + pattern = p; + while (*pattern == SEP) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = *pattern++; + } + } else /* Need expansion, recurse. */ + return(glob3(pathbuf, pathend, pathend_last, pattern, p, + pglob, limit)); + } + /* NOTREACHED */ +} + +static int +glob3(Char *pathbuf, Char *pathend, Char *pathend_last, + Char *pattern, Char *restpattern, + cglob_t *pglob, size_t *limit) +{ + struct dirent *dp; + DIR *dirp; + int err; + char buf[MAXPATHLEN]; + + /* + * The readdirfunc declaration can't be prototyped, because it is + * assigned, below, to two functions which are prototyped in glob.h + * and dirent.h as taking pointers to differently typed opaque + * structures. + */ + struct dirent *(*readdirfunc)(); + + if (pathend > pathend_last) + return (GLOB_ABORTED); + *pathend = EOS; + errno = 0; + + if ((dirp = g_opendir(pathbuf, pglob)) == NULL) { + /* TODO: don't call for ENOENT or ENOTDIR? */ + if (pglob->gl_errfunc) { + if (g_Ctoc(pathbuf, buf, sizeof(buf))) + return (GLOB_ABORTED); + if (pglob->gl_errfunc(buf, errno) || + pglob->gl_flags & GLOB_ERR) + return (GLOB_ABORTED); + } + return(0); + } + + err = 0; + + /* Search directory for matching names. */ + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + readdirfunc = pglob->gl_readdir; + else + readdirfunc = readdir; + while ((dp = (*readdirfunc)(dirp))) { + char *sc; + Char *dc; + wchar_t wc; + size_t clen; + mbstate_t mbs; + + /* Initial DOT must be matched literally. */ + if (dp->d_name[0] == DOT && *pattern != DOT) + continue; + memset(&mbs, 0, sizeof(mbs)); + dc = pathend; + sc = dp->d_name; + while (dc < pathend_last) { + clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) { + wc = *sc; + clen = 1; + memset(&mbs, 0, sizeof(mbs)); + } + if ((*dc++ = wc) == EOS) + break; + sc += clen; + } + if (!match(pathend, pattern, restpattern)) { + *pathend = EOS; + continue; + } + err = glob2(pathbuf, --dc, pathend_last, restpattern, + pglob, limit); + if (err) + break; + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + (*pglob->gl_closedir)(dirp); + else + closedir(dirp); + return(err); +} + + +/* + * Extend the gl_pathv member of a glob_t structure to accomodate a new item, + * add the new item, and update gl_pathc. + * + * This assumes the BSD realloc, which only copies the block when its size + * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic + * behavior. + * + * Return 0 if new item added, error code if memory couldn't be allocated. + * + * Invariant of the glob_t structure: + * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and + * gl_pathv points to (gl_offs + gl_pathc + 1) items. + */ +static int +globextend(const Char *path, cglob_t *pglob, size_t *limit) +{ + char **pathv; + size_t i, newsize, len; + char *copy; + const Char *p; + + if (*limit && pglob->gl_pathc > *limit) { + errno = 0; + return (GLOB_NOSPACE); + } + + newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); + pathv = pglob->gl_pathv ? + realloc((char *)pglob->gl_pathv, newsize) : + malloc(newsize); + if (pathv == NULL) { + if (pglob->gl_pathv) { + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } + return(GLOB_NOSPACE); + } + + if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { + /* first time around -- clear initial gl_offs items */ + pathv += pglob->gl_offs; + for (i = pglob->gl_offs + 1; --i > 0; ) + *--pathv = NULL; + } + pglob->gl_pathv = pathv; + + for (p = path; *p++;) + continue; + len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */ + if ((copy = malloc(len)) != NULL) { + if (g_Ctoc(path, copy, len)) { + free(copy); + return (GLOB_NOSPACE); + } + pathv[pglob->gl_offs + pglob->gl_pathc++] = copy; + } + pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; + return(copy == NULL ? GLOB_NOSPACE : 0); +} + +/* + * pattern matching function for filenames. Each occurrence of the * + * pattern causes a recursion level. + */ +static int +match(Char *name, Char *pat, Char *patend) +{ + int ok, negate_range; + Char c, k; + + while (pat < patend) { + c = *pat++; + switch (c & M_MASK) { + case M_ALL: + if (pat == patend) + return(1); + do + if (match(name, pat, patend)) + return(1); + while (*name++ != EOS); + return(0); + case M_ONE: + if (*name++ == EOS) + return(0); + break; + case M_SET: + ok = 0; + if ((k = *name++) == EOS) + return(0); + if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS) + ++pat; + while (((c = *pat++) & M_MASK) != M_END) + if ((*pat & M_MASK) == M_RNG) { + if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1; + pat += 2; + } else if (c == k) + ok = 1; + if (ok == negate_range) + return(0); + break; + default: + if (*name++ != c) + return(0); + break; + } + } + return(*name == EOS); +} + +/* Free allocated data belonging to a glob_t structure. */ +void +cglobfree(cglob_t *pglob) +{ + size_t i; + char **pp; + + if (pglob->gl_pathv != NULL) { + pp = pglob->gl_pathv + pglob->gl_offs; + for (i = pglob->gl_pathc; i--; ++pp) + if (*pp) + free(*pp); + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } +} + +static DIR * +g_opendir(Char *str, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (!*str) + strcpy(buf, "."); + else { + if (g_Ctoc(str, buf, sizeof(buf))) + return (NULL); + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_opendir)(buf)); + + return(opendir(buf)); +} + +static int +g_lstat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_lstat)(buf, sb)); + return(lstat(buf, sb)); +} + +static int +g_stat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_stat)(buf, sb)); + return(stat(buf, sb)); +} + +static const Char * +g_strchr(const Char *str, wchar_t ch) +{ + + do { + if (*str == ch) + return (str); + } while (*str++); + return (NULL); +} + +static int +g_Ctoc(const Char *str, char *buf, size_t len) +{ + mbstate_t mbs; + size_t clen; + + memset(&mbs, 0, sizeof(mbs)); + while (len >= MB_CUR_MAX) { + clen = wcrtomb(buf, *str, &mbs); + if (clen == (size_t)-1) + return (1); + if (*str == L'\0') + return (0); + str++; + buf += clen; + len -= clen; + } + return (1); +} + +#ifdef DEBUG +static void +qprintf(const char *str, Char *s) +{ + Char *p; + + (void)printf("%s:\n", str); + for (p = s; *p; p++) + (void)printf("%c", CHAR(*p)); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", *p & M_PROTECT ? '"' : ' '); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", ismeta(*p) ? '_' : ' '); + (void)printf("\n"); +} +#endif diff --git a/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp new file mode 100644 index 00000000..5799d6ac --- /dev/null +++ b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp @@ -0,0 +1,342 @@ +#if defined(__linux__) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef ANDROID +#include "cglob.h" +#else +#include +#define cglob glob +#define cglobfree globfree +#define cglob_t glob_t +#endif +#include +#include +#include + +#include "serial/serial.h" + +using serial::PortInfo; +using std::istringstream; +using std::ifstream; +using std::getline; +using std::vector; +using std::string; +using std::cout; +using std::endl; + +static vector glob(const vector& patterns); +static string basename(const string& path); +static string dirname(const string& path); +static bool path_exists(const string& path); +static string realpath(const string& path); +static string usb_sysfs_friendly_name(const string& sys_usb_path); +static vector get_sysfs_info(const string& device_path); +static string read_line(const string& file); +static string usb_sysfs_hw_string(const string& sysfs_path); +static string format(const char* format, ...); + +vector +glob(const vector& patterns) +{ + vector paths_found; + + if(patterns.size() == 0) + return paths_found; + + cglob_t glob_results; + + int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results); + + vector::const_iterator iter = patterns.begin(); + + while(++iter != patterns.end()) + { + glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results); + } + + for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++) + { + paths_found.push_back(glob_results.gl_pathv[path_index]); + } + + cglobfree(&glob_results); + + return paths_found; +} + +string +basename(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + + return string(path, pos+1, string::npos); +} + +string +dirname(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + else if(pos == 0) + return "/"; + + return string(path, 0, pos); +} + +bool +path_exists(const string& path) +{ + struct stat sb; + + if( stat(path.c_str(), &sb ) == 0 ) + return true; + + return false; +} + +string +realpath(const string& path) +{ + char* real_path = realpath(path.c_str(), NULL); + + string result; + + if(real_path != NULL) + { + result = real_path; + + free(real_path); + } + + return result; +} + +string +usb_sysfs_friendly_name(const string& sys_usb_path) +{ + unsigned int device_number = 0; + + istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number; + + string manufacturer = read_line( sys_usb_path + "/manufacturer" ); + + string product = read_line( sys_usb_path + "/product" ); + + string serial = read_line( sys_usb_path + "/serial" ); + + if( manufacturer.empty() && product.empty() && serial.empty() ) + return ""; + + return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() ); +} + +vector +get_sysfs_info(const string& device_path) +{ + string device_name = basename( device_path ); + + string friendly_name; + + string hardware_id; + + string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() ); + + if( device_name.compare(0,6,"ttyUSB") == 0 ) + { + sys_device_path = dirname( dirname( realpath( sys_device_path ) ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else if( device_name.compare(0,6,"ttyACM") == 0 ) + { + sys_device_path = dirname( realpath( sys_device_path ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else + { + // Try to read ID string of PCI device + + string sys_id_path = sys_device_path + "/id"; + + if( path_exists( sys_id_path ) ) + hardware_id = read_line( sys_id_path ); + } + + if( friendly_name.empty() ) + friendly_name = device_name; + + if( hardware_id.empty() ) + hardware_id = "n/a"; + + vector result; + result.push_back(friendly_name); + result.push_back(hardware_id); + + return result; +} + +string +read_line(const string& file) +{ + ifstream ifs(file.c_str(), ifstream::in); + + string line; + + if(ifs) + { + getline(ifs, line); + } + + return line; +} + +string +format(const char* format, ...) +{ + va_list ap; + + size_t buffer_size_bytes = 256; + + string result; + + char* buffer = (char*)malloc(buffer_size_bytes); + + if( buffer == NULL ) + return result; + + bool done = false; + + unsigned int loop_count = 0; + + while(!done) + { + va_start(ap, format); + + int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap); + + if( return_value < 0 ) + { + done = true; + } + else if( return_value >= buffer_size_bytes ) + { + // Realloc and try again. + + buffer_size_bytes = return_value + 1; + + char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes); + + if( new_buffer_ptr == NULL ) + { + done = true; + } + else + { + buffer = new_buffer_ptr; + } + } + else + { + result = buffer; + done = true; + } + + va_end(ap); + + if( ++loop_count > 5 ) + done = true; + } + + free(buffer); + + return result; +} + +string +usb_sysfs_hw_string(const string& sysfs_path) +{ + string serial_number = read_line( sysfs_path + "/serial" ); + + if( serial_number.length() > 0 ) + { + serial_number = format( "SNR=%s", serial_number.c_str() ); + } + + string vid = read_line( sysfs_path + "/idVendor" ); + + string pid = read_line( sysfs_path + "/idProduct" ); + + return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() ); +} + +vector +serial::list_ports() +{ + vector results; + + vector search_globs; + search_globs.push_back("/dev/ttyACM*"); + search_globs.push_back("/dev/ttyS*"); + search_globs.push_back("/dev/ttyUSB*"); + search_globs.push_back("/dev/tty.*"); + search_globs.push_back("/dev/cu.*"); + search_globs.push_back("/dev/rfcomm*"); + + vector devices_found = glob( search_globs ); + + vector::iterator iter = devices_found.begin(); + + while( iter != devices_found.end() ) + { + string device = *iter++; + + vector sysfs_info = get_sysfs_info( device ); + + string friendly_name = sysfs_info[0]; + + string hardware_id = sysfs_info[1]; + + PortInfo device_entry; + device_entry.port = device; + device_entry.description = friendly_name; + device_entry.hardware_id = hardware_id; + + results.push_back( device_entry ); + + } + + return results; +} + +#endif // defined(__linux__) diff --git a/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp new file mode 100644 index 00000000..8005c62b --- /dev/null +++ b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp @@ -0,0 +1,286 @@ +#if defined(__APPLE__) + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../../../include/serial/serial.h" + +using serial::PortInfo; +using std::string; +using std::vector; + +#define HARDWARE_ID_STRING_LENGTH 128 + +string cfstring_to_string( CFStringRef cfstring ); +string get_device_path( io_object_t& serial_port ); +string get_class_name( io_object_t& obj ); +io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port ); +string get_string_property( io_object_t& device, const char* property ); +uint16_t get_int_property( io_object_t& device, const char* property ); +string rtrim(const string& str); + +string +cfstring_to_string( CFStringRef cfstring ) +{ + char cstring[MAXPATHLEN]; + string result; + + if( cfstring ) + { + Boolean success = CFStringGetCString( cfstring, + cstring, + sizeof(cstring), + kCFStringEncodingASCII ); + + if( success ) + result = cstring; + } + + return result; +} + +string +get_device_path( io_object_t& serial_port ) +{ + CFTypeRef callout_path; + string device_path; + + callout_path = IORegistryEntryCreateCFProperty( serial_port, + CFSTR(kIOCalloutDeviceKey), + kCFAllocatorDefault, + 0 ); + + if (callout_path) + { + if( CFGetTypeID(callout_path) == CFStringGetTypeID() ) + device_path = cfstring_to_string( static_cast(callout_path) ); + + CFRelease(callout_path); + } + + return device_path; +} + +string +get_class_name( io_object_t& obj ) +{ + string result; + io_name_t class_name; + kern_return_t kern_result; + + kern_result = IOObjectGetClass( obj, class_name ); + + if( kern_result == KERN_SUCCESS ) + result = class_name; + + return result; +} + +io_registry_entry_t +get_parent_iousb_device( io_object_t& serial_port ) +{ + io_object_t device = serial_port; + io_registry_entry_t parent = 0; + io_registry_entry_t result = 0; + kern_return_t kern_result = KERN_FAILURE; + string name = get_class_name(device); + + // Walk the IO Registry tree looking for this devices parent IOUSBDevice. + while( name != "IOUSBDevice" ) + { + kern_result = IORegistryEntryGetParentEntry( device, + kIOServicePlane, + &parent ); + + if(kern_result != KERN_SUCCESS) + { + result = 0; + break; + } + + device = parent; + + name = get_class_name(device); + } + + if(kern_result == KERN_SUCCESS) + result = device; + + return result; +} + +string +get_string_property( io_object_t& device, const char* property ) +{ + string property_name; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty( + device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if( name_as_cfstring ) + { + if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() ) + property_name = cfstring_to_string( static_cast(name_as_cfstring) ); + + CFRelease(name_as_cfstring); + } + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + } + + return property_name; +} + +uint16_t +get_int_property( io_object_t& device, const char* property ) +{ + uint16_t result = 0; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef number = IORegistryEntryCreateCFProperty( device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + + if( number ) + { + if( CFGetTypeID(number) == CFNumberGetTypeID() ) + { + bool success = CFNumberGetValue( static_cast(number), + kCFNumberSInt16Type, + &result ); + + if( !success ) + result = 0; + } + + CFRelease(number); + } + + } + + return result; +} + +string rtrim(const string& str) +{ + string result = str; + + string whitespace = " \t\f\v\n\r"; + + std::size_t found = result.find_last_not_of(whitespace); + + if (found != std::string::npos) + result.erase(found+1); + else + result.clear(); + + return result; +} + +vector +serial::list_ports(void) +{ + vector devices_found; + CFMutableDictionaryRef classes_to_match; + io_iterator_t serial_port_iterator; + io_object_t serial_port; + mach_port_t master_port; + kern_return_t kern_result; + + kern_result = IOMasterPort(MACH_PORT_NULL, &master_port); + + if(kern_result != KERN_SUCCESS) + return devices_found; + + classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue); + + if (classes_to_match == NULL) + return devices_found; + + CFDictionarySetValue( classes_to_match, + CFSTR(kIOSerialBSDTypeKey), + CFSTR(kIOSerialBSDAllTypes) ); + + kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator); + + if (KERN_SUCCESS != kern_result) + return devices_found; + + while ( (serial_port = IOIteratorNext(serial_port_iterator)) ) + { + string device_path = get_device_path( serial_port ); + io_registry_entry_t parent = get_parent_iousb_device( serial_port ); + IOObjectRelease(serial_port); + + if( device_path.empty() ) + continue; + + PortInfo port_info; + port_info.port = device_path; + port_info.description = "n/a"; + port_info.hardware_id = "n/a"; + + string device_name = rtrim( get_string_property( parent, "USB Product Name" ) ); + string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") ); + string description = rtrim( vendor_name + " " + device_name ); + if( !description.empty() ) + port_info.description = description; + + string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) ); + uint16_t vendor_id = get_int_property( parent, "idVendor" ); + uint16_t product_id = get_int_property( parent, "idProduct" ); + + if( vendor_id && product_id ) + { + char cstring[HARDWARE_ID_STRING_LENGTH]; + + if(serial_number.empty()) + serial_number = "None"; + + int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s", + vendor_id, + product_id, + serial_number.c_str() ); + + if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) ) + port_info.hardware_id = cstring; + } + + devices_found.push_back(port_info); + } + + IOObjectRelease(serial_port_iterator); + return devices_found; +} + +#endif // defined(__APPLE__) diff --git a/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp new file mode 100644 index 00000000..7da40c44 --- /dev/null +++ b/packages/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp @@ -0,0 +1,152 @@ +#if defined(_WIN32) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include "serial/serial.h" +#include +#include +#include +#include +#include +#include + +using serial::PortInfo; +using std::vector; +using std::string; + +static const DWORD port_name_max_length = 256; +static const DWORD friendly_name_max_length = 256; +static const DWORD hardware_id_max_length = 256; + +// Convert a wide Unicode string to an UTF8 string +std::string utf8_encode(const std::wstring &wstr) +{ + int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); + std::string strTo( size_needed, 0 ); + WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); + return strTo; +} + +vector +serial::list_ports() +{ + vector devices_found; + + HDEVINFO device_info_set = SetupDiGetClassDevs( + (const GUID *) &GUID_DEVCLASS_PORTS, + NULL, + NULL, + DIGCF_PRESENT); + + unsigned int device_info_set_index = 0; + SP_DEVINFO_DATA device_info_data; + + device_info_data.cbSize = sizeof(SP_DEVINFO_DATA); + + while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data)) + { + device_info_set_index++; + + // Get port name + + HKEY hkey = SetupDiOpenDevRegKey( + device_info_set, + &device_info_data, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + TCHAR port_name[port_name_max_length]; + DWORD port_name_length = port_name_max_length; + + LONG return_code = RegQueryValueEx( + hkey, + _T("PortName"), + NULL, + NULL, + (LPBYTE)port_name, + &port_name_length); + + RegCloseKey(hkey); + + if(return_code != EXIT_SUCCESS) + continue; + + if(port_name_length > 0 && port_name_length <= port_name_max_length) + port_name[port_name_length-1] = '\0'; + else + port_name[0] = '\0'; + + // Ignore parallel ports + + if(_tcsstr(port_name, _T("LPT")) != NULL) + continue; + + // Get port friendly name + + TCHAR friendly_name[friendly_name_max_length]; + DWORD friendly_name_actual_length = 0; + + BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_FRIENDLYNAME, + NULL, + (PBYTE)friendly_name, + friendly_name_max_length, + &friendly_name_actual_length); + + if(got_friendly_name == TRUE && friendly_name_actual_length > 0) + friendly_name[friendly_name_actual_length-1] = '\0'; + else + friendly_name[0] = '\0'; + + // Get hardware ID + + TCHAR hardware_id[hardware_id_max_length]; + DWORD hardware_id_actual_length = 0; + + BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + NULL, + (PBYTE)hardware_id, + hardware_id_max_length, + &hardware_id_actual_length); + + if(got_hardware_id == TRUE && hardware_id_actual_length > 0) + hardware_id[hardware_id_actual_length-1] = '\0'; + else + hardware_id[0] = '\0'; + + #ifdef UNICODE + std::string portName = utf8_encode(port_name); + std::string friendlyName = utf8_encode(friendly_name); + std::string hardwareId = utf8_encode(hardware_id); + #else + std::string portName = port_name; + std::string friendlyName = friendly_name; + std::string hardwareId = hardware_id; + #endif + + PortInfo port_entry; + port_entry.port = portName; + port_entry.description = friendlyName; + port_entry.hardware_id = hardwareId; + + devices_found.push_back(port_entry); + } + + SetupDiDestroyDeviceInfoList(device_info_set); + + return devices_found; +} + +#endif // #if defined(_WIN32) diff --git a/packages/flserial/src/native_libs/src/impl/unix.cpp b/packages/flserial/src/native_libs/src/impl/unix.cpp new file mode 100644 index 00000000..689c08cf --- /dev/null +++ b/packages/flserial/src/native_libs/src/impl/unix.cpp @@ -0,0 +1,1087 @@ +/* Copyright 2012 William Woodall and John Harrison + * + * Additional Contributors: Christopher Baker @bakercp + */ + +#if !defined(_WIN32) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +# include +#endif + +#include +#include +#include +#ifdef __MACH__ +#include +#include +#include +#endif + +#include "../../include/serial/impl/unix.h" + +#ifndef TIOCINQ +#ifdef FIONREAD +#define TIOCINQ FIONREAD +#else +#define TIOCINQ 0x541B +#endif +#endif + +#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3) +#include +#endif + +using std::string; +using std::stringstream; +using std::invalid_argument; +using serial::MillisecondTimer; +using serial::Serial; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + + +MillisecondTimer::MillisecondTimer (const uint32_t millis) + : expiry(timespec_now()) +{ + int64_t tv_nsec = expiry.tv_nsec + (millis * 1e6); + if (tv_nsec >= 1e9) { + int64_t sec_diff = tv_nsec / static_cast (1e9); + expiry.tv_nsec = tv_nsec % static_cast(1e9); + expiry.tv_sec += sec_diff; + } else { + expiry.tv_nsec = tv_nsec; + } +} + +int64_t +MillisecondTimer::remaining () +{ + timespec now(timespec_now()); + int64_t millis = (expiry.tv_sec - now.tv_sec) * 1e3; + millis += (expiry.tv_nsec - now.tv_nsec) / 1e6; + return millis; +} + +timespec +MillisecondTimer::timespec_now () +{ + timespec time; +# ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + time.tv_sec = mts.tv_sec; + time.tv_nsec = mts.tv_nsec; +# else + clock_gettime(CLOCK_MONOTONIC, &time); +# endif + return time; +} + +timespec +timespec_from_ms (const uint32_t millis) +{ + timespec time; + time.tv_sec = millis / 1e3; + time.tv_nsec = (millis - (time.tv_sec * 1e3)) * 1e6; + return time; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port), fd_ (-1), is_open_ (false), xonxoff_ (false), rtscts_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + pthread_mutex_init(&this->read_mutex, NULL); + pthread_mutex_init(&this->write_mutex, NULL); + if (port_.empty () == false) + open (); +} + +Serial::SerialImpl::~SerialImpl () +{ + close(); + pthread_mutex_destroy(&this->read_mutex); + pthread_mutex_destroy(&this->write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + + int err = errno; + if (fd_ == -1) { + switch (err) { + case EINTR: + // Recurse because this is a recoverable error. + open (); + return; + case ENFILE: + case EMFILE: + THROW (IOException, "Too many file handles open."); + default: + char buff[32]; + sprintf(buff, "%08X", err); + THROW (IOException, buff); + } + } + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == -1) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + struct termios options; // The options for the file descriptor + + if (tcgetattr(fd_, &options) == -1) { + THROW (IOException, "::tcgetattr"); + } + + // set up raw mode / no echo / binary + options.c_cflag |= (tcflag_t) (CLOCAL | CREAD); + options.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | + ISIG | IEXTEN); //|ECHOPRT + + options.c_oflag &= (tcflag_t) ~(OPOST); + options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK); +#ifdef IUCLC + options.c_iflag &= (tcflag_t) ~IUCLC; +#endif +#ifdef PARMRK + options.c_iflag &= (tcflag_t) ~PARMRK; +#endif + + // setup baud rate + bool custom_baud = false; + speed_t baud; + switch (baudrate_) { +#ifdef B0 + case 0: baud = B0; break; +#endif +#ifdef B50 + case 50: baud = B50; break; +#endif +#ifdef B75 + case 75: baud = B75; break; +#endif +#ifdef B110 + case 110: baud = B110; break; +#endif +#ifdef B134 + case 134: baud = B134; break; +#endif +#ifdef B150 + case 150: baud = B150; break; +#endif +#ifdef B200 + case 200: baud = B200; break; +#endif +#ifdef B300 + case 300: baud = B300; break; +#endif +#ifdef B600 + case 600: baud = B600; break; +#endif +#ifdef B1200 + case 1200: baud = B1200; break; +#endif +#ifdef B1800 + case 1800: baud = B1800; break; +#endif +#ifdef B2400 + case 2400: baud = B2400; break; +#endif +#ifdef B4800 + case 4800: baud = B4800; break; +#endif +#ifdef B7200 + case 7200: baud = B7200; break; +#endif +#ifdef B9600 + case 9600: baud = B9600; break; +#endif +#ifdef B14400 + case 14400: baud = B14400; break; +#endif +#ifdef B19200 + case 19200: baud = B19200; break; +#endif +#ifdef B28800 + case 28800: baud = B28800; break; +#endif +#ifdef B57600 + case 57600: baud = B57600; break; +#endif +#ifdef B76800 + case 76800: baud = B76800; break; +#endif +#ifdef B38400 + case 38400: baud = B38400; break; +#endif +#ifdef B115200 + case 115200: baud = B115200; break; +#endif +#ifdef B128000 + case 128000: baud = B128000; break; +#endif +#ifdef B153600 + case 153600: baud = B153600; break; +#endif +#ifdef B230400 + case 230400: baud = B230400; break; +#endif +#ifdef B256000 + case 256000: baud = B256000; break; +#endif +#ifdef B460800 + case 460800: baud = B460800; break; +#endif +#ifdef B500000 + case 500000: baud = B500000; break; +#endif +#ifdef B576000 + case 576000: baud = B576000; break; +#endif +#ifdef B921600 + case 921600: baud = B921600; break; +#endif +#ifdef B1000000 + case 1000000: baud = B1000000; break; +#endif +#ifdef B1152000 + case 1152000: baud = B1152000; break; +#endif +#ifdef B1500000 + case 1500000: baud = B1500000; break; +#endif +#ifdef B2000000 + case 2000000: baud = B2000000; break; +#endif +#ifdef B2500000 + case 2500000: baud = B2500000; break; +#endif +#ifdef B3000000 + case 3000000: baud = B3000000; break; +#endif +#ifdef B3500000 + case 3500000: baud = B3500000; break; +#endif +#ifdef B4000000 + case 4000000: baud = B4000000; break; +#endif + default: + custom_baud = true; + } + if (custom_baud == false) { +#ifdef _BSD_SOURCE + ::cfsetspeed(&options, baud); +#else + ::cfsetispeed(&options, baud); + ::cfsetospeed(&options, baud); +#endif + } + + // setup char len + options.c_cflag &= (tcflag_t) ~CSIZE; + if (bytesize_ == eightbits) + options.c_cflag |= CS8; + else if (bytesize_ == sevenbits) + options.c_cflag |= CS7; + else if (bytesize_ == sixbits) + options.c_cflag |= CS6; + else if (bytesize_ == fivebits) + options.c_cflag |= CS5; + else + throw invalid_argument ("invalid char len"); + // setup stopbits + if (stopbits_ == stopbits_one) + options.c_cflag &= (tcflag_t) ~(CSTOPB); + else if (stopbits_ == stopbits_one_point_five) + // ONE POINT FIVE same as TWO.. there is no POSIX support for 1.5 + options.c_cflag |= (CSTOPB); + else if (stopbits_ == stopbits_two) + options.c_cflag |= (CSTOPB); + else + throw invalid_argument ("invalid stop bit"); + // setup parity + options.c_iflag &= (tcflag_t) ~(INPCK | ISTRIP); + if (parity_ == parity_none) { + options.c_cflag &= (tcflag_t) ~(PARENB | PARODD); + } else if (parity_ == parity_even) { + options.c_cflag &= (tcflag_t) ~(PARODD); + options.c_cflag |= (PARENB); + } else if (parity_ == parity_odd) { + options.c_cflag |= (PARENB | PARODD); + } +#ifdef CMSPAR + else if (parity_ == parity_mark) { + options.c_cflag |= (PARENB | CMSPAR | PARODD); + } + else if (parity_ == parity_space) { + options.c_cflag |= (PARENB | CMSPAR); + options.c_cflag &= (tcflag_t) ~(PARODD); + } +#else + // CMSPAR is not defined on OSX. So do not support mark or space parity. + else if (parity_ == parity_mark || parity_ == parity_space) { + throw invalid_argument ("OS does not support mark or space parity"); + } +#endif // ifdef CMSPAR + else { + throw invalid_argument ("invalid parity"); + } + // setup flow control + if (flowcontrol_ == flowcontrol_none) { + xonxoff_ = false; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_software) { + xonxoff_ = true; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_hardware) { + xonxoff_ = false; + rtscts_ = true; + } + // xonxoff +#ifdef IXANY + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); //|IXANY) + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF | IXANY); +#else + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF); +#endif + // rtscts +#ifdef CRTSCTS + if (rtscts_) + options.c_cflag |= (CRTSCTS); + else + options.c_cflag &= (unsigned long) ~(CRTSCTS); +#elif defined CNEW_RTSCTS + if (rtscts_) + options.c_cflag |= (CNEW_RTSCTS); + else + options.c_cflag &= (unsigned long) ~(CNEW_RTSCTS); +#else +#error "OS Support seems wrong." +#endif + + // http://www.unixwiz.net/techtips/termios-vmin-vtime.html + // this basically sets the read call up to be a polling read, + // but we are using select to ensure there is data available + // to read before each call, so we should never needlessly poll + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + + // activate settings + ::tcsetattr (fd_, TCSANOW, &options); + + // apply custom baud rate, if any + if (custom_baud == true) { + // OS X support +#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4) + // Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates + // other than those specified by POSIX. The driver for the underlying serial hardware + // ultimately determines which baud rates can be used. This ioctl sets both the input + // and output speed. + speed_t new_baud = static_cast (baudrate_); + // PySerial uses IOSSIOSPEED=0x80045402 + if (-1 == ioctl (fd_, IOSSIOSPEED, &new_baud, 1)) { + THROW (IOException, errno); + } + // Linux Support +#elif defined(__linux__) && defined (TIOCSSERIAL) + struct serial_struct ser; + + if (-1 == ioctl (fd_, TIOCGSERIAL, &ser)) { + THROW (IOException, errno); + } + + // set custom divisor + ser.custom_divisor = ser.baud_base / static_cast (baudrate_); + // update flags + ser.flags &= ~ASYNC_SPD_MASK; + ser.flags |= ASYNC_SPD_CUST; + + if (-1 == ioctl (fd_, TIOCSSERIAL, &ser)) { + THROW (IOException, errno); + } +#else + throw invalid_argument ("OS does not currently support custom bauds"); +#endif + } + + // Update byte_time_ based on the new settings. + uint32_t bit_time_ns = 1e9 / baudrate_; + byte_time_ns_ = bit_time_ns * (1 + bytesize_ + parity_ + stopbits_); + + // Compensate for the stopbits_one_point_five enum being equal to int 3, + // and not 1.5. + if (stopbits_ == stopbits_one_point_five) { + byte_time_ns_ += ((1.5 - stopbits_one_point_five) * bit_time_ns); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != -1) { + int ret; + ret = ::close (fd_); + if (ret == 0) { + fd_ = -1; + } else { + THROW (IOException, errno); + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + int count = 0; + if (-1 == ioctl (fd_, TIOCINQ, &count)) { + THROW (IOException, errno); + } else { + return static_cast (count); + } +} + +bool +Serial::SerialImpl::waitReadable (uint32_t timeout) +{ + // Setup a select call to block for serial data or a timeout + fd_set readfds; + FD_ZERO (&readfds); + FD_SET (fd_, &readfds); + timespec timeout_ts (timespec_from_ms (timeout)); + int r = pselect (fd_ + 1, &readfds, NULL, NULL, &timeout_ts, NULL); + + if (r < 0) { + // Select was interrupted + if (errno == EINTR) { + return false; + } + // Otherwise there was some error + THROW (IOException, errno); + } + // Timeout occurred + if (r == 0) { + return false; + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + if (!FD_ISSET (fd_, &readfds)) { + THROW (IOException, "select reports ready to read, but our fd isn't" + " in the list, this shouldn't happen!"); + } + // Data available to read. + return true; +} + +void +Serial::SerialImpl::waitByteTimes (size_t count) +{ + timespec wait_time = { 0, static_cast(byte_time_ns_ * count)}; + pselect (0, NULL, NULL, NULL, &wait_time, NULL); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + // If the port is not open, throw + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + size_t bytes_read = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.read_timeout_constant; + total_timeout_ms += timeout_.read_timeout_multiplier * static_cast (size); + MillisecondTimer total_timeout(total_timeout_ms); + + // Pre-fill buffer with available bytes + { + ssize_t bytes_read_now = ::read (fd_, buf, size); + if (bytes_read_now > 0) { + bytes_read = bytes_read_now; + } + } + + while (bytes_read < size) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + if (timeout_remaining_ms <= 0) { + // Timed out + break; + } + // Timeout for the next select is whichever is less of the remaining + // total read timeout and the inter-byte timeout. + uint32_t timeout = std::min(static_cast (timeout_remaining_ms), + timeout_.inter_byte_timeout); + // Wait for the device to be readable, and then attempt to read. + if (waitReadable(timeout)) { + // If it's a fixed-length multi-byte read, insert a wait here so that + // we can attempt to grab the whole thing in a single IO call. Skip + // this wait if a non-max inter_byte_timeout is specified. + if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) { + size_t bytes_available = available(); + if (bytes_available + bytes_read < size) { + waitByteTimes(size - (bytes_available + bytes_read)); + } + } + // This should be non-blocking returning only what is available now + // Then returning so that select can block again. + ssize_t bytes_read_now = + ::read (fd_, buf + bytes_read, size - bytes_read); + // read should always return some data as select reported it was + // ready to read when we get to this point. + if (bytes_read_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to read immediately + // but reading returns nothing. + throw SerialException ("device reports readiness to read but " + "returned no data (device disconnected?)"); + } + // Update bytes_read + bytes_read += static_cast (bytes_read_now); + // If bytes_read == size then we have read everything we need + if (bytes_read == size) { + break; + } + // If bytes_read < size then we have more to read + if (bytes_read < size) { + continue; + } + // If bytes_read > size then we have over read, which shouldn't happen + if (bytes_read > size) { + throw SerialException ("read over read, too many bytes where " + "read, this shouldn't happen, might be " + "a logical error!"); + } + } + } + return bytes_read; +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + fd_set writefds; + size_t bytes_written = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.write_timeout_constant; + total_timeout_ms += timeout_.write_timeout_multiplier * static_cast (length); + MillisecondTimer total_timeout(total_timeout_ms); + + bool first_iteration = true; + while (bytes_written < length) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + // Only consider the timeout if it's not the first iteration of the loop + // otherwise a timeout of 0 won't be allowed through + if (!first_iteration && (timeout_remaining_ms <= 0)) { + // Timed out + break; + } + first_iteration = false; + + timespec timeout(timespec_from_ms(timeout_remaining_ms)); + + FD_ZERO (&writefds); + FD_SET (fd_, &writefds); + + // Do the select + int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL); + + // Figure out what happened by looking at select's response 'r' + /** Error **/ + if (r < 0) { + // Select was interrupted, try again + if (errno == EINTR) { + continue; + } + // Otherwise there was some error + THROW (IOException, errno); + } + /** Timeout **/ + if (r == 0) { + break; + } + /** Port ready to write **/ + if (r > 0) { + // Make sure our file descriptor is in the ready to write list + if (FD_ISSET (fd_, &writefds)) { + // This will write some + ssize_t bytes_written_now = + ::write (fd_, data + bytes_written, length - bytes_written); + + // even though pselect returned readiness the call might still be + // interrupted. In that case simply retry. + if (bytes_written_now == -1 && errno == EINTR) { + continue; + } + + // write should always return some data as select reported it was + // ready to write when we get to this point. + if (bytes_written_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to write immediately + // but writing returns nothing. + std::stringstream strs; + strs << "device reports readiness to write but " + "returned no data (device disconnected?)"; + strs << " errno=" << errno; + strs << " bytes_written_now= " << bytes_written_now; + strs << " bytes_written=" << bytes_written; + strs << " length=" << length; + throw SerialException(strs.str().c_str()); + } + // Update bytes_written + bytes_written += static_cast (bytes_written_now); + // If bytes_written == size then we have written everything we need to + if (bytes_written == length) { + break; + } + // If bytes_written < size then we have more to write + if (bytes_written < length) { + continue; + } + // If bytes_written > size then we have over written, which shouldn't happen + if (bytes_written > length) { + throw SerialException ("write over wrote, too many bytes where " + "written, this shouldn't happen, might be " + "a logical error!"); + } + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + THROW (IOException, "select reports ready to write, but our fd isn't" + " in the list, this shouldn't happen!"); + } + } + return bytes_written; +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = port; +} + +string +Serial::SerialImpl::getPort () const +{ + return port_; +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) + reconfigurePort (); +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) + reconfigurePort (); +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) + reconfigurePort (); +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) + reconfigurePort (); +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) + reconfigurePort (); +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + tcdrain (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushInput"); + } + tcflush (fd_, TCIFLUSH); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushOutput"); + } + tcflush (fd_, TCOFLUSH); +} + +void +Serial::SerialImpl::sendBreak (int duration) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::sendBreak"); + } + tcsendbreak (fd_, static_cast (duration / 4)); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + + if (level) { + if (-1 == ioctl (fd_, TIOCSBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCCBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + + int command = TIOCM_RTS; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + + int command = TIOCM_DTR; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +bool +Serial::SerialImpl::waitForChange () +{ +#ifndef TIOCMIWAIT + +while (is_open_ == true) { + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + if (0 != (status & TIOCM_CTS) + || 0 != (status & TIOCM_DSR) + || 0 != (status & TIOCM_RI) + || 0 != (status & TIOCM_CD)) + { + return true; + } + } + + usleep(1000); + } + + return false; +#else + int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS); + + if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) { + stringstream ss; + ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): " + << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + return true; +#endif +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCTS failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CTS); + } +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getDSR failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_DSR); + } +} + +bool +Serial::SerialImpl::getRI () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_RI); + } +} + +bool +Serial::SerialImpl::getCD () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCD failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CD); + } +} + +void +Serial::SerialImpl::readLock () +{ + int result = pthread_mutex_lock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::readUnlock () +{ + int result = pthread_mutex_unlock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeLock () +{ + int result = pthread_mutex_lock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeUnlock () +{ + int result = pthread_mutex_unlock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +#endif // !defined(_WIN32) diff --git a/packages/flserial/src/native_libs/src/impl/win.cpp b/packages/flserial/src/native_libs/src/impl/win.cpp new file mode 100644 index 00000000..cbccf048 --- /dev/null +++ b/packages/flserial/src/native_libs/src/impl/win.cpp @@ -0,0 +1,651 @@ +#if defined(_WIN32) + +/* Copyright 2012 William Woodall and John Harrison */ + +#include + +#include "serial/impl/win.h" + +using std::string; +using std::wstring; +using std::stringstream; +using std::invalid_argument; +using serial::Serial; +using serial::Timeout; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + +inline wstring +_prefix_port_if_needed(const wstring &input) +{ + static wstring windows_com_port_prefix = L"\\\\.\\"; + if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0) + { + return windows_com_port_prefix + input; + } + return input; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + if (port_.empty () == false) + open (); + read_mutex = CreateMutex(NULL, false, NULL); + write_mutex = CreateMutex(NULL, false, NULL); +} + +Serial::SerialImpl::~SerialImpl () +{ + this->close(); + CloseHandle(read_mutex); + CloseHandle(write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + // See: https://github.com/wjwwood/serial/issues/84 + wstring port_with_prefix = _prefix_port_if_needed(port_); + LPCWSTR lp_port = port_with_prefix.c_str(); + fd_ = CreateFileW(lp_port, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + 0); + + if (fd_ == INVALID_HANDLE_VALUE) { + DWORD create_file_err = GetLastError(); + stringstream ss; + switch (create_file_err) { + case ERROR_FILE_NOT_FOUND: + // Use this->getPort to convert to a std::string + ss << "Specified port, " << this->getPort() << ", does not exist."; + THROWEX (IOException, ss.str().c_str(), 1); + case ERROR_ACCESS_DENIED: + ss << "Specified port, " << this->getPort() << ", allready open."; + THROWEX (IOException, ss.str().c_str(), 2); + default: + ss << "Unknown error opening the serial port: " << create_file_err; + THROW (IOException, ss.str().c_str()); + } + } + + + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == INVALID_HANDLE_VALUE) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + DCB dcbSerialParams = {0}; + + dcbSerialParams.DCBlength=sizeof(dcbSerialParams); + + if (!GetCommState(fd_, &dcbSerialParams)) { + //error getting state + THROW (IOException, "Error getting the serial port state."); + } + + // setup baud rate + switch (baudrate_) { +#ifdef CBR_0 + case 0: dcbSerialParams.BaudRate = CBR_0; break; +#endif +#ifdef CBR_50 + case 50: dcbSerialParams.BaudRate = CBR_50; break; +#endif +#ifdef CBR_75 + case 75: dcbSerialParams.BaudRate = CBR_75; break; +#endif +#ifdef CBR_110 + case 110: dcbSerialParams.BaudRate = CBR_110; break; +#endif +#ifdef CBR_134 + case 134: dcbSerialParams.BaudRate = CBR_134; break; +#endif +#ifdef CBR_150 + case 150: dcbSerialParams.BaudRate = CBR_150; break; +#endif +#ifdef CBR_200 + case 200: dcbSerialParams.BaudRate = CBR_200; break; +#endif +#ifdef CBR_300 + case 300: dcbSerialParams.BaudRate = CBR_300; break; +#endif +#ifdef CBR_600 + case 600: dcbSerialParams.BaudRate = CBR_600; break; +#endif +#ifdef CBR_1200 + case 1200: dcbSerialParams.BaudRate = CBR_1200; break; +#endif +#ifdef CBR_1800 + case 1800: dcbSerialParams.BaudRate = CBR_1800; break; +#endif +#ifdef CBR_2400 + case 2400: dcbSerialParams.BaudRate = CBR_2400; break; +#endif +#ifdef CBR_4800 + case 4800: dcbSerialParams.BaudRate = CBR_4800; break; +#endif +#ifdef CBR_7200 + case 7200: dcbSerialParams.BaudRate = CBR_7200; break; +#endif +#ifdef CBR_9600 + case 9600: dcbSerialParams.BaudRate = CBR_9600; break; +#endif +#ifdef CBR_14400 + case 14400: dcbSerialParams.BaudRate = CBR_14400; break; +#endif +#ifdef CBR_19200 + case 19200: dcbSerialParams.BaudRate = CBR_19200; break; +#endif +#ifdef CBR_28800 + case 28800: dcbSerialParams.BaudRate = CBR_28800; break; +#endif +#ifdef CBR_57600 + case 57600: dcbSerialParams.BaudRate = CBR_57600; break; +#endif +#ifdef CBR_76800 + case 76800: dcbSerialParams.BaudRate = CBR_76800; break; +#endif +#ifdef CBR_38400 + case 38400: dcbSerialParams.BaudRate = CBR_38400; break; +#endif +#ifdef CBR_115200 + case 115200: dcbSerialParams.BaudRate = CBR_115200; break; +#endif +#ifdef CBR_128000 + case 128000: dcbSerialParams.BaudRate = CBR_128000; break; +#endif +#ifdef CBR_153600 + case 153600: dcbSerialParams.BaudRate = CBR_153600; break; +#endif +#ifdef CBR_230400 + case 230400: dcbSerialParams.BaudRate = CBR_230400; break; +#endif +#ifdef CBR_256000 + case 256000: dcbSerialParams.BaudRate = CBR_256000; break; +#endif +#ifdef CBR_460800 + case 460800: dcbSerialParams.BaudRate = CBR_460800; break; +#endif +#ifdef CBR_921600 + case 921600: dcbSerialParams.BaudRate = CBR_921600; break; +#endif + default: + // Try to blindly assign it + dcbSerialParams.BaudRate = baudrate_; + } + + // setup char len + if (bytesize_ == eightbits) + dcbSerialParams.ByteSize = 8; + else if (bytesize_ == sevenbits) + dcbSerialParams.ByteSize = 7; + else if (bytesize_ == sixbits) + dcbSerialParams.ByteSize = 6; + else if (bytesize_ == fivebits) + dcbSerialParams.ByteSize = 5; + else + throw invalid_argument ("invalid char len"); + + // setup stopbits + if (stopbits_ == stopbits_one) + dcbSerialParams.StopBits = ONESTOPBIT; + else if (stopbits_ == stopbits_one_point_five) + dcbSerialParams.StopBits = ONE5STOPBITS; + else if (stopbits_ == stopbits_two) + dcbSerialParams.StopBits = TWOSTOPBITS; + else + throw invalid_argument ("invalid stop bit"); + + // setup parity + if (parity_ == parity_none) { + dcbSerialParams.Parity = NOPARITY; + } else if (parity_ == parity_even) { + dcbSerialParams.Parity = EVENPARITY; + } else if (parity_ == parity_odd) { + dcbSerialParams.Parity = ODDPARITY; + } else if (parity_ == parity_mark) { + dcbSerialParams.Parity = MARKPARITY; + } else if (parity_ == parity_space) { + dcbSerialParams.Parity = SPACEPARITY; + } else { + throw invalid_argument ("invalid parity"); + } + + // setup flowcontrol + if (flowcontrol_ == flowcontrol_none) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + if (flowcontrol_ == flowcontrol_software) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = true; + dcbSerialParams.fInX = true; + } + if (flowcontrol_ == flowcontrol_hardware) { + dcbSerialParams.fOutxCtsFlow = true; + dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + + // activate settings + if (!SetCommState(fd_, &dcbSerialParams)){ + CloseHandle(fd_); + THROW (IOException, "Error setting serial port settings."); + } + + // Setup timeouts + COMMTIMEOUTS timeouts = {0}; + timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout; + timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant; + timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier; + timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant; + timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier; + if (!SetCommTimeouts(fd_, &timeouts)) { + THROW (IOException, "Error setting timeouts."); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != INVALID_HANDLE_VALUE) { + int ret; + ret = CloseHandle(fd_); + if (ret == 0) { + stringstream ss; + ss << "Error while closing serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } else { + fd_ = INVALID_HANDLE_VALUE; + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + COMSTAT cs; + if (!ClearCommError(fd_, NULL, &cs)) { + stringstream ss; + ss << "Error while checking status of the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return static_cast(cs.cbInQue); +} + +bool +Serial::SerialImpl::waitReadable (uint32_t /*timeout*/) +{ + THROW (IOException, "waitReadable is not implemented on Windows."); + return false; +} + +void +Serial::SerialImpl::waitByteTimes (size_t /*count*/) +{ + THROW (IOException, "waitByteTimes is not implemented on Windows."); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + DWORD bytes_read; + if (!ReadFile(fd_, buf, static_cast(size), &bytes_read, NULL)) { + stringstream ss; + ss << "Error while reading from the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_read); +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + DWORD bytes_written; + if (!WriteFile(fd_, data, static_cast(length), &bytes_written, NULL)) { + stringstream ss; + ss << "Error while writing to the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_written); +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = wstring(port.begin(), port.end()); +} + +string +Serial::SerialImpl::getPort () const +{ + return string(port_.begin(), port_.end()); +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; + if (is_open_) { + reconfigurePort (); + } +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) { + reconfigurePort (); + } +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) { + reconfigurePort (); + } +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) { + reconfigurePort (); + } +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) { + reconfigurePort (); + } +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) { + reconfigurePort (); + } +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + FlushFileBuffers (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushInput"); + } + PurgeComm(fd_, PURGE_RXCLEAR); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushOutput"); + } + PurgeComm(fd_, PURGE_TXCLEAR); +} + +void +Serial::SerialImpl::sendBreak (int /*duration*/) +{ + THROW (IOException, "sendBreak is not supported on Windows."); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + if (level) { + EscapeCommFunction (fd_, SETBREAK); + } else { + EscapeCommFunction (fd_, CLRBREAK); + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + if (level) { + EscapeCommFunction (fd_, SETRTS); + } else { + EscapeCommFunction (fd_, CLRRTS); + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + if (level) { + EscapeCommFunction (fd_, SETDTR); + } else { + EscapeCommFunction (fd_, CLRDTR); + } +} + +bool +Serial::SerialImpl::waitForChange () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::waitForChange"); + } + DWORD dwCommEvent; + + if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) { + // Error setting communications mask + return false; + } + + if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) { + // An error occurred waiting for the event. + return false; + } else { + // Event has occurred. + return true; + } +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the CTS line."); + } + + return (MS_CTS_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the DSR line."); + } + + return (MS_DSR_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getRI() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the RI line."); + } + + return (MS_RING_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getCD() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + // Error in GetCommModemStatus; + THROW (IOException, "Error getting the status of the CD line."); + } + + return (MS_RLSD_ON & dwModemStatus) != 0; +} + +void +Serial::SerialImpl::readLock() +{ + if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming read mutex."); + } +} + +void +Serial::SerialImpl::readUnlock() +{ + if (!ReleaseMutex(read_mutex)) { + THROW (IOException, "Error releasing read mutex."); + } +} + +void +Serial::SerialImpl::writeLock() +{ + if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming write mutex."); + } +} + +void +Serial::SerialImpl::writeUnlock() +{ + if (!ReleaseMutex(write_mutex)) { + THROW (IOException, "Error releasing write mutex."); + } +} + +#endif // #if defined(_WIN32) + diff --git a/packages/flserial/src/native_libs/src/ringbuffer.c b/packages/flserial/src/native_libs/src/ringbuffer.c new file mode 100644 index 00000000..39fbea59 --- /dev/null +++ b/packages/flserial/src/native_libs/src/ringbuffer.c @@ -0,0 +1,78 @@ +#include "ringbuffer.h" + +/** + * @file + * Implementation of ring buffer functions. + */ + +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) { + RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1); + buffer->buffer = buf; + buffer->buffer_mask = buf_size - 1; + buffer->tail_index = 0; + buffer->head_index = 0; +} + +void ring_buffer_queue(ring_buffer_t *buffer, char data) { + /* Is buffer full? */ + if(ring_buffer_is_full(buffer)) { + /* Is going to overwrite the oldest byte */ + /* Increase tail index */ + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + } + + /* Place data in buffer */ + buffer->buffer[buffer->head_index] = data; + buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer)); +} + +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) { + /* Add bytes; one by one */ + ring_buffer_size_t i; + for(i = 0; i < size; i++) { + ring_buffer_queue(buffer, data[i]); + } +} + +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + *data = buffer->buffer[buffer->tail_index]; + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + return 1; +} + +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + char *data_ptr = data; + ring_buffer_size_t cnt = 0; + while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) { + cnt++; + data_ptr++; + } + return cnt; +} + +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) { + if(index >= ring_buffer_num_items(buffer)) { + /* No items at index */ + return 0; + } + + /* Add index to pointer */ + ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer)); + *data = buffer->buffer[data_index]; + return 1; +} + +extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer); +extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer); +extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer); + diff --git a/packages/flserial/src/native_libs/src/serial.cpp b/packages/flserial/src/native_libs/src/serial.cpp new file mode 100644 index 00000000..06a15a99 --- /dev/null +++ b/packages/flserial/src/native_libs/src/serial.cpp @@ -0,0 +1,432 @@ +/* Copyright 2012 William Woodall and John Harrison */ +#include + +#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__) +# include +#endif + +#if defined (__MINGW32__) +# define alloca __builtin_alloca +#endif + +#include "../include/serial/serial.h" + +#ifdef _WIN32 +#include "serial/impl/win.h" +#else +#include "../include/serial/impl/unix.h" +#endif + +using std::invalid_argument; +using std::min; +using std::numeric_limits; +using std::vector; +using std::size_t; +using std::string; + +using serial::Serial; +using serial::SerialException; +using serial::IOException; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; + +class Serial::ScopedReadLock { +public: + ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->readLock(); + } + ~ScopedReadLock() { + this->pimpl_->readUnlock(); + } +private: + // Disable copy constructors + ScopedReadLock(const ScopedReadLock&); + const ScopedReadLock& operator=(ScopedReadLock); + + SerialImpl *pimpl_; +}; + +class Serial::ScopedWriteLock { +public: + ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->writeLock(); + } + ~ScopedWriteLock() { + this->pimpl_->writeUnlock(); + } +private: + // Disable copy constructors + ScopedWriteLock(const ScopedWriteLock&); + const ScopedWriteLock& operator=(ScopedWriteLock); + SerialImpl *pimpl_; +}; + +Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout, + bytesize_t bytesize, parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, + stopbits, flowcontrol)) +{ + pimpl_->setTimeout(timeout); +} + +Serial::~Serial () +{ + delete pimpl_; +} + +void +Serial::open () +{ + pimpl_->open (); +} + +void +Serial::close () +{ + pimpl_->close (); +} + +bool +Serial::isOpen () const +{ + return pimpl_->isOpen (); +} + +size_t +Serial::available () +{ + return pimpl_->available (); +} + +bool +Serial::waitReadable () +{ + serial::Timeout timeout(pimpl_->getTimeout ()); + return pimpl_->waitReadable(timeout.read_timeout_constant); +} + +void +Serial::waitByteTimes (size_t count) +{ + pimpl_->waitByteTimes(count); +} + +size_t +Serial::read_ (uint8_t *buffer, size_t size) +{ + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (uint8_t *buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (std::vector &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + + buffer.insert (buffer.end (), buffer_, buffer_+bytes_read); + delete[] buffer_; + return bytes_read; +} + +size_t +Serial::read (std::string &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + buffer.append (reinterpret_cast(buffer_), bytes_read); + delete[] buffer_; + return bytes_read; +} + +string +Serial::read (size_t size) +{ + std::string buffer; + this->read (buffer, size); + return buffer; +} + +size_t +Serial::readline (string &buffer, size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + while (true) + { + size_t bytes_read = this->read_ (buffer_ + read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + break; // EOL found + } + if (read_so_far == size) { + break; // Reached the maximum read length + } + } + buffer.append(reinterpret_cast (buffer_), read_so_far); + return read_so_far; +} + +string +Serial::readline (size_t size, string eol) +{ + std::string buffer; + this->readline (buffer, size, eol); + return buffer; +} + +vector +Serial::readlines (size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + std::vector lines; + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + size_t start_of_line = 0; + while (read_so_far < size) { + size_t bytes_read = this->read_ (buffer_+read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + if (start_of_line != read_so_far) { + lines.push_back ( + string (reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + // EOL found + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + start_of_line = read_so_far; + } + if (read_so_far == size) { + if (start_of_line != read_so_far) { + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Reached the maximum read length + } + } + return lines; +} + +size_t +Serial::write (const string &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (reinterpret_cast(data.c_str()), + data.length()); +} + +size_t +Serial::write (const std::vector &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (&data[0], data.size()); +} + +size_t +Serial::write (const uint8_t *data, size_t size) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_(data, size); +} + +size_t +Serial::write_ (const uint8_t *data, size_t length) +{ + return pimpl_->write (data, length); +} + +void +Serial::setPort (const string &port) +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + bool was_open = pimpl_->isOpen (); + if (was_open) close(); + pimpl_->setPort (port); + if (was_open) open (); +} + +string +Serial::getPort () const +{ + return pimpl_->getPort (); +} + +void +Serial::setTimeout (serial::Timeout &timeout) +{ + pimpl_->setTimeout (timeout); +} + +serial::Timeout +Serial::getTimeout () const { + return pimpl_->getTimeout (); +} + +void +Serial::setBaudrate (uint32_t baudrate) +{ + pimpl_->setBaudrate (baudrate); +} + +uint32_t +Serial::getBaudrate () const +{ + return uint32_t(pimpl_->getBaudrate ()); +} + +void +Serial::setBytesize (bytesize_t bytesize) +{ + pimpl_->setBytesize (bytesize); +} + +bytesize_t +Serial::getBytesize () const +{ + return pimpl_->getBytesize (); +} + +void +Serial::setParity (parity_t parity) +{ + pimpl_->setParity (parity); +} + +parity_t +Serial::getParity () const +{ + return pimpl_->getParity (); +} + +void +Serial::setStopbits (stopbits_t stopbits) +{ + pimpl_->setStopbits (stopbits); +} + +stopbits_t +Serial::getStopbits () const +{ + return pimpl_->getStopbits (); +} + +void +Serial::setFlowcontrol (flowcontrol_t flowcontrol) +{ + pimpl_->setFlowcontrol (flowcontrol); +} + +flowcontrol_t +Serial::getFlowcontrol () const +{ + return pimpl_->getFlowcontrol (); +} + +void Serial::flush () +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + pimpl_->flush (); +} + +void Serial::flushInput () +{ + ScopedReadLock lock(this->pimpl_); + pimpl_->flushInput (); +} + +void Serial::flushOutput () +{ + ScopedWriteLock lock(this->pimpl_); + pimpl_->flushOutput (); +} + +void Serial::sendBreak (int duration) +{ + pimpl_->sendBreak (duration); +} + +void Serial::setBreak (bool level) +{ + pimpl_->setBreak (level); +} + +void Serial::setRTS (bool level) +{ + pimpl_->setRTS (level); +} + +void Serial::setDTR (bool level) +{ + pimpl_->setDTR (level); +} + +bool Serial::waitForChange() +{ + return pimpl_->waitForChange(); +} + +bool Serial::getCTS () +{ + return pimpl_->getCTS (); +} + +bool Serial::getDSR () +{ + return pimpl_->getDSR (); +} + +bool Serial::getRI () +{ + return pimpl_->getRI (); +} + +bool Serial::getCD () +{ + return pimpl_->getCD (); +} diff --git a/packages/flserial/src/native_libs/src/tinycthread.c b/packages/flserial/src/native_libs/src/tinycthread.c new file mode 100644 index 00000000..182bbc38 --- /dev/null +++ b/packages/flserial/src/native_libs/src/tinycthread.c @@ -0,0 +1,931 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "../include/tinycthread.h" +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include + #include + #include + #include + #include +#elif defined(_TTHREAD_WIN32_) + #include + #include +#endif + +/* Standard, good-to-have defines */ +#ifndef NULL + #define NULL (void*)0 +#endif +#ifndef TRUE + #define TRUE 1 +#endif +#ifndef FALSE + #define FALSE 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +int mtx_init(mtx_t *mtx, int type) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + mtx->mRecursive = type & mtx_recursive; + mtx->mTimed = type & mtx_timed; + if (!mtx->mTimed) + { + InitializeCriticalSection(&(mtx->mHandle.cs)); + } + else + { + mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL); + if (mtx->mHandle.mut == NULL) + { + return thrd_error; + } + } + return thrd_success; +#else + int ret; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + if (type & mtx_recursive) + { + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + } + ret = pthread_mutex_init(mtx, &attr); + pthread_mutexattr_destroy(&attr); + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +void mtx_destroy(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + DeleteCriticalSection(&(mtx->mHandle.cs)); + } + else + { + CloseHandle(mtx->mHandle.mut); + } +#else + pthread_mutex_destroy(mtx); +#endif +} + +int mtx_lock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + EnterCriticalSection(&(mtx->mHandle.cs)); + } + else + { + switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE)) + { + case WAIT_OBJECT_0: + break; + case WAIT_ABANDONED: + default: + return thrd_error; + } + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + return thrd_success; +#else + return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec current_ts; + DWORD timeoutMs; + + if (!mtx->mTimed) + { + return thrd_error; + } + + timespec_get(¤t_ts, TIME_UTC); + + if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) + { + timeoutMs = 0; + } + else + { + timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; + timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; + timeoutMs += 1; + } + + /* TODO: the timeout for WaitForSingleObject doesn't include time + while the computer is asleep. */ + switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + return thrd_timedout; + case WAIT_ABANDONED: + default: + return thrd_error; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + + return thrd_success; +#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) + switch (pthread_mutex_timedlock(mtx, ts)) { + case 0: + return thrd_success; + case ETIMEDOUT: + return thrd_timedout; + default: + return thrd_error; + } +#else + int rc; + struct timespec cur, dur; + + /* Try to acquire the lock and, if we fail, sleep for 5ms. */ + while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { + timespec_get(&cur, TIME_UTC); + + if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) + { + break; + } + + dur.tv_sec = ts->tv_sec - cur.tv_sec; + dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; + if (dur.tv_nsec < 0) + { + dur.tv_sec--; + dur.tv_nsec += 1000000000; + } + + if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) + { + dur.tv_sec = 0; + dur.tv_nsec = 5000000; + } + + nanosleep(&dur, NULL); + } + + switch (rc) { + case 0: + return thrd_success; + case ETIMEDOUT: + case EBUSY: + return thrd_timedout; + default: + return thrd_error; + } +#endif +} + +int mtx_trylock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + int ret; + + if (!mtx->mTimed) + { + ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy; + } + else + { + ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy; + } + + if ((!mtx->mRecursive) && (ret == thrd_success)) + { + if (mtx->mAlreadyLocked) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + ret = thrd_busy; + } + else + { + mtx->mAlreadyLocked = TRUE; + } + } + return ret; +#else + return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; +#endif +} + +int mtx_unlock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + if (!mtx->mTimed) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + } + else + { + if (!ReleaseMutex(mtx->mHandle.mut)) + { + return thrd_error; + } + } + return thrd_success; +#else + return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; +#endif +} + +#if defined(_TTHREAD_WIN32_) +#define _CONDITION_EVENT_ONE 0 +#define _CONDITION_EVENT_ALL 1 +#endif + +int cnd_init(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + cond->mWaitersCount = 0; + + /* Init critical section */ + InitializeCriticalSection(&cond->mWaitersCountLock); + + /* Init events */ + cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) + { + cond->mEvents[_CONDITION_EVENT_ALL] = NULL; + return thrd_error; + } + cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + cond->mEvents[_CONDITION_EVENT_ONE] = NULL; + return thrd_error; + } + + return thrd_success; +#else + return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; +#endif +} + +void cnd_destroy(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + } + if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); + } + DeleteCriticalSection(&cond->mWaitersCountLock); +#else + pthread_cond_destroy(cond); +#endif +} + +int cnd_signal(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_broadcast(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) +{ + DWORD result; + int lastWaiter; + + /* Increment number of waiters */ + EnterCriticalSection(&cond->mWaitersCountLock); + ++ cond->mWaitersCount; + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* Release the mutex while waiting for the condition (will decrease + the number of waiters when done)... */ + mtx_unlock(mtx); + + /* Wait for either event to become signaled due to cnd_signal() or + cnd_broadcast() being called */ + result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); + if (result == WAIT_TIMEOUT) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_timedout; + } + else if (result == WAIT_FAILED) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + + /* Check if we are the last waiter */ + EnterCriticalSection(&cond->mWaitersCountLock); + -- cond->mWaitersCount; + lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && + (cond->mWaitersCount == 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we are the last waiter to be notified to stop waiting, reset the event */ + if (lastWaiter) + { + if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + } + + /* Re-acquire the mutex */ + mtx_lock(mtx); + + return thrd_success; +} +#endif + +int cnd_wait(cnd_t *cond, mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + return _cnd_timedwait_win32(cond, mtx, INFINITE); +#else + return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec now; + if (timespec_get(&now, TIME_UTC) == TIME_UTC) + { + unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; + unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; + DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? + (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; + return _cnd_timedwait_win32(cond, mtx, delta); + } + else + return thrd_error; +#else + int ret; + ret = pthread_cond_timedwait(cond, mtx, ts); + if (ret == ETIMEDOUT) + { + return thrd_timedout; + } + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +struct TinyCThreadTSSData { + void* value; + tss_t key; + struct TinyCThreadTSSData* next; +}; + +static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, }; + +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL; +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL; + +static void _tinycthread_tss_cleanup (void); + +static void _tinycthread_tss_cleanup (void) { + struct TinyCThreadTSSData* data; + int iteration; + unsigned int again = 1; + void* value; + + for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++) + { + again = 0; + for (data = _tinycthread_tss_head ; data != NULL ; data = data->next) + { + if (data->value != NULL) + { + value = data->value; + data->value = NULL; + + if (_tinycthread_tss_dtors[data->key] != NULL) + { + again = 1; + _tinycthread_tss_dtors[data->key](value); + } + } + } + } + + while (_tinycthread_tss_head != NULL) { + data = _tinycthread_tss_head->next; + free (_tinycthread_tss_head); + _tinycthread_tss_head = data; + } + _tinycthread_tss_head = NULL; + _tinycthread_tss_tail = NULL; +} + +static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv) +{ + (void)h; + (void)pv; + + if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)) + { + _tinycthread_tss_cleanup(); + } +} + +#if defined(_MSC_VER) + #ifdef _M_X64 + #pragma const_seg(".CRT$XLB") + #else + #pragma data_seg(".CRT$XLB") + #endif + PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback; + #ifdef _M_X64 + #pragma data_seg() + #else + #pragma const_seg() + #endif +#else + PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback; +#endif + +#endif /* defined(_TTHREAD_WIN32_) */ + +/** Information to pass to the new thread (what to run). */ +typedef struct { + thrd_start_t mFunction; /**< Pointer to the function to be executed. */ + void * mArg; /**< Function argument for the thread function. */ +} _thread_start_info; + +/* Thread wrapper function. */ +#if defined(_TTHREAD_WIN32_) +static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg) +#elif defined(_TTHREAD_POSIX_) +static void * _thrd_wrapper_function(void * aArg) +#endif +{ + thrd_start_t fun; + void *arg; + int res; + + /* Get thread startup information */ + _thread_start_info *ti = (_thread_start_info *) aArg; + fun = ti->mFunction; + arg = ti->mArg; + + /* The thread is responsible for freeing the startup information */ + free((void *)ti); + + /* Call the actual client thread function */ + res = fun(arg); + +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + return (DWORD)res; +#else + return (void*)(intptr_t)res; +#endif +} + +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) +{ + /* Fill out the thread startup information (passed to the thread wrapper, + which will eventually free it) */ + _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); + if (ti == NULL) + { + return thrd_nomem; + } + ti->mFunction = func; + ti->mArg = arg; + + /* Create the thread */ +#if defined(_TTHREAD_WIN32_) + *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL); +#elif defined(_TTHREAD_POSIX_) + if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) + { + *thr = 0; + } +#endif + + /* Did we fail to create the thread? */ + if(!*thr) + { + free(ti); + return thrd_error; + } + + return thrd_success; +} + +thrd_t thrd_current(void) +{ +#if defined(_TTHREAD_WIN32_) + return GetCurrentThread(); +#else + return pthread_self(); +#endif +} + +int thrd_detach(thrd_t thr) +{ +#if defined(_TTHREAD_WIN32_) + /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */ + return CloseHandle(thr) != 0 ? thrd_success : thrd_error; +#else + return pthread_detach(thr) == 0 ? thrd_success : thrd_error; +#endif +} + +int thrd_equal(thrd_t thr0, thrd_t thr1) +{ +#if defined(_TTHREAD_WIN32_) + return GetThreadId(thr0) == GetThreadId(thr1); +#else + return pthread_equal(thr0, thr1); +#endif +} + +void thrd_exit(int res) +{ +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + ExitThread((DWORD)res); +#else + pthread_exit((void*)(intptr_t)res); +#endif +} + +int thrd_join(thrd_t thr, int *res) +{ +#if defined(_TTHREAD_WIN32_) + DWORD dwRes; + + if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) + { + return thrd_error; + } + if (res != NULL) + { + if (GetExitCodeThread(thr, &dwRes) != 0) + { + *res = (int) dwRes; + } + else + { + return thrd_error; + } + } + CloseHandle(thr); +#elif defined(_TTHREAD_POSIX_) + void *pres; + if (pthread_join(thr, &pres) != 0) + { + return thrd_error; + } + if (res != NULL) + { + *res = (int)(intptr_t)pres; + } +#endif + return thrd_success; +} + +int thrd_sleep(const struct timespec *duration, struct timespec *remaining) +{ +#if !defined(_TTHREAD_WIN32_) + int res = nanosleep(duration, remaining); + if (res == 0) { + return 0; + } else if (errno == EINTR) { + return -1; + } else { + return -2; + } +#else + struct timespec start; + DWORD t; + + timespec_get(&start, TIME_UTC); + + t = SleepEx((DWORD)(duration->tv_sec * 1000 + + duration->tv_nsec / 1000000 + + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), + TRUE); + + if (t == 0) { + return 0; + } else { + if (remaining != NULL) { + timespec_get(remaining, TIME_UTC); + remaining->tv_sec -= start.tv_sec; + remaining->tv_nsec -= start.tv_nsec; + if (remaining->tv_nsec < 0) + { + remaining->tv_nsec += 1000000000; + remaining->tv_sec -= 1; + } + } + + return (t == WAIT_IO_COMPLETION) ? -1 : -2; + } +#endif +} + +void thrd_yield(void) +{ +#if defined(_TTHREAD_WIN32_) + Sleep(0); +#else + sched_yield(); +#endif +} + +int tss_create(tss_t *key, tss_dtor_t dtor) +{ +#if defined(_TTHREAD_WIN32_) + *key = TlsAlloc(); + if (*key == TLS_OUT_OF_INDEXES) + { + return thrd_error; + } + _tinycthread_tss_dtors[*key] = dtor; +#else + if (pthread_key_create(key, dtor) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +void tss_delete(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key); + struct TinyCThreadTSSData* prev = NULL; + if (data != NULL) + { + if (data == _tinycthread_tss_head) + { + _tinycthread_tss_head = data->next; + } + else + { + prev = _tinycthread_tss_head; + if (prev != NULL) + { + while (prev->next != data) + { + prev = prev->next; + } + } + } + + if (data == _tinycthread_tss_tail) + { + _tinycthread_tss_tail = prev; + } + + free (data); + } + _tinycthread_tss_dtors[key] = NULL; + TlsFree(key); +#else + pthread_key_delete(key); +#endif +} + +void *tss_get(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + return NULL; + } + return data->value; +#else + return pthread_getspecific(key); +#endif +} + +int tss_set(tss_t key, void *val) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData)); + if (data == NULL) + { + return thrd_error; + } + + data->value = NULL; + data->key = key; + data->next = NULL; + + if (_tinycthread_tss_tail != NULL) + { + _tinycthread_tss_tail->next = data; + } + else + { + _tinycthread_tss_tail = data; + } + + if (_tinycthread_tss_head == NULL) + { + _tinycthread_tss_head = data; + } + + if (!TlsSetValue(key, data)) + { + free (data); + return thrd_error; + } + } + data->value = val; +#else + if (pthread_setspecific(key, val) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_) +int _tthread_timespec_get(struct timespec *ts, int base) +{ +#if defined(_TTHREAD_WIN32_) + struct _timeb tb; +#elif !defined(CLOCK_REALTIME) + struct timeval tv; +#endif + + if (base != TIME_UTC) + { + return 0; + } + +#if defined(_TTHREAD_WIN32_) + _ftime_s(&tb); + ts->tv_sec = (time_t)tb.time; + ts->tv_nsec = 1000000L * (long)tb.millitm; +#elif defined(CLOCK_REALTIME) + base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0; +#else + gettimeofday(&tv, NULL); + ts->tv_sec = (time_t)tv.tv_sec; + ts->tv_nsec = 1000L * (long)tv.tv_usec; +#endif + + return base; +} +#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */ + +#if defined(_TTHREAD_WIN32_) +void call_once(once_flag *flag, void (*func)(void)) +{ + /* The idea here is that we use a spin lock (via the + InterlockedCompareExchange function) to restrict access to the + critical section until we have initialized it, then we use the + critical section to block until the callback has completed + execution. */ + while (flag->status < 3) + { + switch (flag->status) + { + case 0: + if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) { + InitializeCriticalSection(&(flag->lock)); + EnterCriticalSection(&(flag->lock)); + flag->status = 2; + func(); + flag->status = 3; + LeaveCriticalSection(&(flag->lock)); + return; + } + break; + case 1: + break; + case 2: + EnterCriticalSection(&(flag->lock)); + LeaveCriticalSection(&(flag->lock)); + break; + } + } +} +#endif /* defined(_TTHREAD_WIN32_) */ + +#ifdef __cplusplus +} +#endif diff --git a/packages/flserial/test/lib/flserial_test.dart b/packages/flserial/test/lib/flserial_test.dart new file mode 100644 index 00000000..b7e25b65 --- /dev/null +++ b/packages/flserial/test/lib/flserial_test.dart @@ -0,0 +1,33 @@ +import 'dart:ffi'; +import 'dart:io'; +import 'package:flserial/flserial_bindings_generated.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const String libName = 'flserial'; + + /// The dynamic library in which the symbols for [FlserialBindings] can be found. + final DynamicLibrary dylib = () { + if (Platform.isMacOS || Platform.isIOS) { + return DynamicLibrary.open('$libName.framework/$libName'); + } + if (Platform.isAndroid || Platform.isLinux) { + return DynamicLibrary.open('lib$libName.so'); + } + if (Platform.isWindows) { + return DynamicLibrary.open( + './build/windows/x64/runner/Release/$libName.dll'); + } + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); + }(); + + /// The bindings to the native functions in [_dylib]. + final FlserialBindings bindings = FlserialBindings(dylib); + //'/home/runner/work/flserial/flserial/build/linux/x64/release/shared/libflserial.so'); + + test('FLSerial status should be closed', () { + bindings.fl_init(10); + + bindings.fl_free(); + }); +} diff --git a/packages/flserial/windows/.gitignore b/packages/flserial/windows/.gitignore new file mode 100644 index 00000000..b3eb2be1 --- /dev/null +++ b/packages/flserial/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/flserial/windows/CMakeLists.txt b/packages/flserial/windows/CMakeLists.txt new file mode 100644 index 00000000..cd8d63b1 --- /dev/null +++ b/packages/flserial/windows/CMakeLists.txt @@ -0,0 +1,23 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "flserial") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(flserial_bundled_libraries + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + $ + PARENT_SCOPE +) diff --git a/packages/flutter_blue_plus_android/CHANGELOG.md b/packages/flutter_blue_plus_android/CHANGELOG.md new file mode 100644 index 00000000..e360bbbd --- /dev/null +++ b/packages/flutter_blue_plus_android/CHANGELOG.md @@ -0,0 +1,45 @@ +## 8.2.2 +* **[Release]** version bump for the flutter_blue_plus 2.2.2 release + +## 8.2.1 +* **[LICENSE]** clarifications to the development exemption + +## 8.2.0 +* **[LICENSE]** new tiers based on company size & development exemption + +## 8.1.0 +* **[LICENSE]** commercial license is now required for 15 or more employees + +## 8.0.1 +* Add License symlink + +## 8.0.0 +* Switch to FBP License + +## 4.0.5 +* Fixes to check for location services when plugin is called from a service + +## 4.0.3 +* Added option to disable Location Services check + +## 4.0.2 +* Fix compile error + +## 4.0.1 +* Fix compile error + +## 4.0.0 +* Use bytes instead of hex for platform communication (#1130) +* Check if Android location services are enabled when doing scan (#1167) + +## 3.0.0 +* Add option to provide pairing PIN to `createBond` (#1119) + +## 2.0.1 +* Add log color + +## 2.0.0 +* Replace void return types with bool return types + +## 1.35.0 +* Split from `flutter_blue_plus` as a federated implementation diff --git a/packages/flutter_blue_plus_android/LICENSE b/packages/flutter_blue_plus_android/LICENSE new file mode 100644 index 00000000..856f7d1f --- /dev/null +++ b/packages/flutter_blue_plus_android/LICENSE @@ -0,0 +1,77 @@ +FlutterBluePlus License +Version 1.4 + +Copyright (c) 2026 Chip Weinberger +All rights reserved. + +--- + +### Preamble (Non-Binding) + +The intent of this license is to make FlutterBluePlus ("The Software") as free and open as possible for personal users, researchers, nonprofits, educational institutions, and hobbyists. For these users, the terms are similar to the BSD license: broad freedom to use, modify, and share. + +For for-profit use and by for-profit organizations, a commercial license is required. + +The revenue from commercial licenses supports the long-term maintenance and development of FlutterBluePlus. +This approach allows hobbyists, nonprofits, and educators to benefit from free and open software, while ensuring that for-profit companies who rely on it help sustain its future. + +Please be aware that this project originated under the BSD-3 license, and some portions of the codebase remain under that license today. Compliance with those clauses is not required under the FlutterBluePlus License itself, but to remain fully compliant with the terms set by those contributors, it is advised that users continue to follow the BSD-3 conditions described in NOTICE.md. That relationship is between you and the BSD-licensed contributors. + +This preamble is provided for explanation only and does not form part of the binding legal terms of this license. + +--- + +### Section 1: Common Conditions (apply to all users) + +Permission is hereby granted to any individual or organization to use, copy, modify, and distribute the Software in source code or binary form, subject to the following conditions: + +**1. Source Code Redistributions.** Redistributions of source code must retain the above copyright notice and this entire license text without modification. + +**2. Relicensing Prohibition.** The Software may not be relicensed under different terms by any party. + +**3. Commercial Use Requirement.** Use of the Software by any for-profit organization requires a commercial license under Section 3, regardless of how the Software was obtained. + +**4. Nonprofit & Educational Exemption.** Registered nonprofit organizations and accredited educational institutions are exempt from this requirement and may use the Software under Section 2. + +--- + +### Section 2: Open Use Terms (for nonprofits, educational institutions, personal use) + +Use of the Software is free of charge for any registered nonprofit organization, accredited educational institution, or personal user, subject to the Common Conditions and the following additional terms: + +**1. Endorsement Restriction.** Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. + +--- + +### Section 3: Commercial Terms (for for-profit organizations) + +Any use of FlutterBluePlus by or for a for-profit company or corporation — including commercial use by individuals — requires the purchase of a commercial license, subject to the Common Conditions and the following additional terms: + +**1. License Fee.** Commercial licenses are offered in the following tiers, based on employee count **at the time of purchase**. The associated cost is listed on the official FlutterBluePlus payment portal. + +- **Starter:** 0–9 employees +- **Team:** 10–29 employees +- **Business:** 30–99 employees +- **Enterprise:** 100 or more employees + +**2. Perpetual Use.** The license grants perpetual rights to use the Software and to receive all current and future software updates made available by the licensor after purchase. + +**3. Development Clarification.** Use of the Software during development, testing, or evaluation by a for-profit organization is considered commercial use and requires a commercial license. + +**4. Official Payment Portal.** Payment must be made via the official payment portal: https://jamcorder.myshopify.com/products/flutterblueplus-commercial-license + +**5. Validity of Offer.** This Section constitutes an offer only while this license version is the current version published in the main branch of the official FlutterBluePlus repository. Once superseded, replaced, or withdrawn, this version shall no longer be considered an active offer, even if archived copies remain publicly visible. + + +A valid commercial license covers use of all current and future packages that +are part of the FlutterBluePlus project, including its federated packages +(e.g., flutter_blue_plus, flutter_blue_plus_darwin, flutter_blue_plus_android, +flutter_blue_plus_web, flutter_blue_plus_linux, flutter_blue_plus_platform_interface). +Only a single commercial license is required per organization, regardless of how many +FlutterBluePlus packages are used. + +--- + +### Section 4: Warranty Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_android/LICENSE.md b/packages/flutter_blue_plus_android/LICENSE.md new file mode 100644 index 00000000..08fd9343 --- /dev/null +++ b/packages/flutter_blue_plus_android/LICENSE.md @@ -0,0 +1,77 @@ +FlutterBluePlus License +Version 1.4 + +Copyright (c) 2026 Chip Weinberger +All rights reserved. + +--- + +### Preamble (Non-Binding) + +The intent of this license is to make FlutterBluePlus ("The Software") as free and open as possible for personal users, researchers, nonprofits, educational institutions, and hobbyists. For these users, the terms are similar to the BSD license: broad freedom to use, modify, and share. + +For for-profit use and by for-profit organizations, a commercial license is required. + +The revenue from commercial licenses supports the long-term maintenance and development of FlutterBluePlus. +This approach allows hobbyists, nonprofits, and educators to benefit from free and open software, while ensuring that for-profit companies who rely on it help sustain its future. + +Please be aware that this project originated under the BSD-3 license, and some portions of the codebase remain under that license today. Compliance with those clauses is not required under the FlutterBluePlus License itself, but to remain fully compliant with the terms set by those contributors, it is advised that users continue to follow the BSD-3 conditions described in NOTICE.md. That relationship is between you and the BSD-licensed contributors. + +This preamble is provided for explanation only and does not form part of the binding legal terms of this license. + +--- + +### Section 1: Common Conditions (apply to all users) + +Permission is hereby granted to any individual or organization to use, copy, modify, and distribute the Software in source code or binary form, subject to the following conditions: + +**1. Source Code Redistributions.** Redistributions of source code must retain the above copyright notice and this entire license text without modification. + +**2. Relicensing Prohibition.** The Software may not be relicensed under different terms by any party. + +**3. Commercial Use Requirement.** Use of the Software by any for-profit organization requires a commercial license under Section 3, regardless of how the Software was obtained. + +**4. Nonprofit & Educational Exemption.** Registered nonprofit organizations and accredited educational institutions are exempt from this requirement and may use the Software under Section 2. + +--- + +### Section 2: Open Use Terms (for nonprofits, educational institutions, personal use) + +Use of the Software is free of charge for any registered nonprofit organization, accredited educational institution, or personal user, subject to the Common Conditions and the following additional terms: + +**1. Endorsement Restriction.** Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. + +--- + +### Section 3: Commercial Terms (for for-profit organizations) + +Any use of FlutterBluePlus by or for a for-profit company or corporation — including commercial use by individuals — requires the purchase of a commercial license, subject to the Common Conditions and the following additional terms: + +**1. License Fee.** Commercial licenses are offered in the following tiers, based on employee count **at the time of purchase**. The associated cost is listed on the official FlutterBluePlus payment portal. + +- **Starter:** 0–9 employees +- **Team:** 10–29 employees +- **Business:** 30–99 employees +- **Enterprise:** 100 or more employees + +**2. Perpetual Use.** The license grants perpetual rights to use the Software and to receive all current and future software updates made available by the licensor after purchase. + +**3. Development Clarification.** Use of the Software during development, testing, or evaluation by a for-profit organization is considered commercial use and requires a commercial license. + +**4. Official Payment Portal.** Payment must be made via the official payment portal: https://jamcorder.myshopify.com/products/flutterblueplus-commercial-license + +**5. Validity of Offer.** This Section constitutes an offer only while this license version is the current version published in the main branch of the official FlutterBluePlus repository. Once superseded, replaced, or withdrawn, this version shall no longer be considered an active offer, even if archived copies remain publicly visible. + + +A valid commercial license covers use of all current and future packages that +are part of the FlutterBluePlus project, including its federated packages +(e.g., flutter_blue_plus, flutter_blue_plus_darwin, flutter_blue_plus_android, +flutter_blue_plus_web, flutter_blue_plus_linux, flutter_blue_plus_platform_interface). +Only a single commercial license is required per organization, regardless of how many +FlutterBluePlus packages are used. + +--- + +### Section 4: Warranty Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_android/NOTICE.md b/packages/flutter_blue_plus_android/NOTICE.md new file mode 100644 index 00000000..e9869a1e --- /dev/null +++ b/packages/flutter_blue_plus_android/NOTICE.md @@ -0,0 +1,39 @@ +To comply with the requirements of the original BSD-style license, +the full text of that license is reproduced below. It applies to all +releases of this project up to and including version 1.36.8, published +before October 2025. Those releases remain available under the terms +below, which are irrevocable. + +All releases beginning with version 2.0.0, published in October 2025 +and onward, are licensed under the FlutterBluePlus License. + +------ + +Copyright 2017-2024, Paul DeMarco, Bosko Popovic, Charles Weinberger, Thomas Clark. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Buffalo PC Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_android/README.md b/packages/flutter_blue_plus_android/README.md new file mode 100644 index 00000000..dc692c17 --- /dev/null +++ b/packages/flutter_blue_plus_android/README.md @@ -0,0 +1,15 @@ +# flutter_blue_plus_android + +The Android implementation of [`flutter_blue_plus`][1]. + +## Usage + +This package is [endorsed][2], which means you can simply use `flutter_blue_plus` +normally. This package will be automatically included in your app when you do, +so you do not need to add it to your `pubspec.yaml`. + +However, if you `import` this package to use any of its APIs directly, you +should add it to your `pubspec.yaml` as usual. + +[1]: https://pub.dev/packages/flutter_blue_plus +[2]: https://flutter.dev/to/endorsed-federated-plugin diff --git a/packages/flutter_blue_plus_android/analysis_options.yaml b/packages/flutter_blue_plus_android/analysis_options.yaml new file mode 100644 index 00000000..1e432d55 --- /dev/null +++ b/packages/flutter_blue_plus_android/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/tools/linter-rules. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/tools/analysis diff --git a/packages/flutter_blue_plus_android/android/build.gradle b/packages/flutter_blue_plus_android/android/build.gradle new file mode 100644 index 00000000..28f805bb --- /dev/null +++ b/packages/flutter_blue_plus_android/android/build.gradle @@ -0,0 +1,33 @@ +group 'com.lib.flutter_blue_plus' +version '1.0' + +apply plugin: 'com.android.library' + +android { + compileSdkVersion = flutter.compileSdkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + + lintOptions { + abortOnError false + } + + defaultConfig { + minSdkVersion 21 + } + + gradle.projectsEvaluated { + tasks.withType(JavaCompile) { + options.compilerArgs << "-Xlint:deprecation" + options.compilerArgs << "-Xlint:unchecked" + } + } + + // Conditional for compatibility with AGP <4.2. + if (project.android.hasProperty("namespace")) { + namespace 'com.lib.flutter_blue_plus' + } +} diff --git a/packages/flutter_blue_plus_android/android/settings.gradle b/packages/flutter_blue_plus_android/android/settings.gradle new file mode 100644 index 00000000..943eabda --- /dev/null +++ b/packages/flutter_blue_plus_android/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'flutter_blue_plus' diff --git a/packages/flutter_blue_plus_android/android/src/main/AndroidManifest.xml b/packages/flutter_blue_plus_android/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..c82f58b0 --- /dev/null +++ b/packages/flutter_blue_plus_android/android/src/main/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + diff --git a/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java b/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java new file mode 100644 index 00000000..2e9d7814 --- /dev/null +++ b/packages/flutter_blue_plus_android/android/src/main/java/com/lib/flutter_blue_plus/FlutterBluePlusPlugin.java @@ -0,0 +1,3149 @@ +// Copyright 2017-2023, Charles Weinberger & Paul DeMarco. +// All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +package com.lib.flutter_blue_plus; + +import android.Manifest; +import android.annotation.TargetApi; +import android.app.Activity; +import android.app.Application; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCallback; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.bluetooth.BluetoothGattService; +import android.bluetooth.BluetoothStatusCodes; +import android.bluetooth.BluetoothManager; +import android.bluetooth.BluetoothProfile; +import android.bluetooth.le.BluetoothLeScanner; +import android.bluetooth.le.ScanCallback; +import android.bluetooth.le.ScanFilter; +import android.bluetooth.le.ScanResult; +import android.bluetooth.le.ScanRecord; +import android.bluetooth.le.ScanSettings; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.location.LocationManager; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.os.ParcelUuid; +import android.provider.Settings; +import android.util.Log; +import android.util.SparseArray; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; +import java.io.StringWriter; +import java.io.PrintWriter; +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + +import java.lang.reflect.Method; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; + +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.EventChannel; +import io.flutter.plugin.common.EventChannel.EventSink; +import io.flutter.plugin.common.EventChannel.StreamHandler; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.MethodChannel.MethodCallHandler; +import io.flutter.plugin.common.MethodChannel.Result; +import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener; +import io.flutter.plugin.common.PluginRegistry.ActivityResultListener; + +public class FlutterBluePlusPlugin implements + FlutterPlugin, + MethodCallHandler, + RequestPermissionsResultListener, + ActivityResultListener, + ActivityAware +{ + private static final String TAG = "[FBP-Android]"; + + private LogLevel logLevel = LogLevel.DEBUG; + + private Context context; + private MethodChannel methodChannel; + private static final String NAMESPACE = "flutter_blue_plus"; + + private BluetoothManager mBluetoothManager; + private BluetoothAdapter mBluetoothAdapter; + private boolean mIsScanning = false; + + private FlutterPluginBinding pluginBinding; + private ActivityPluginBinding activityBinding; + + static final private String CCCD = "2902"; + + private final Semaphore mMethodCallMutex = new Semaphore(1); + private final Map mConnectedDevices = new ConcurrentHashMap<>(); + private final Map mCurrentlyConnectingDevices = new ConcurrentHashMap<>(); + private final Map mBondingDevices = new ConcurrentHashMap<>(); + private final Map mBondingPins = new ConcurrentHashMap<>(); + private final Map mMtu = new ConcurrentHashMap<>(); + private final Map mAutoConnected = new ConcurrentHashMap<>(); + private final Map mWriteChr = new ConcurrentHashMap<>(); + private final Map mWriteDesc = new ConcurrentHashMap<>(); + private final Map mAdvSeen = new ConcurrentHashMap<>(); + private final Map mScanCounts = new ConcurrentHashMap<>(); + private HashMap mScanFilters = new HashMap(); + + private final Map operationsOnPermission = new HashMap<>(); + private int lastEventId = 1452; + + private final int enableBluetoothRequestCode = 13106; + + private interface OperationOnPermission { + void op(boolean granted, String permission); + } + + public FlutterBluePlusPlugin() {} + + // returns 128-bit representation + public String uuid128(Object uuid) + { + if (!(uuid instanceof UUID) && !(uuid instanceof String)) { + throw new IllegalArgumentException("input must be UUID or String"); + } + + String s = uuid.toString(); + + if (s.length() == 4) + { + // 16-bit uuid + return String.format("0000%s-0000-1000-8000-00805f9b34fb", s).toLowerCase(); + } + else if (s.length() == 8) + { + // 32-bit uuid + return String.format("%s-0000-1000-8000-00805f9b34fb", s).toLowerCase(); + } + else + { + // 128-bit uuid + return s.toLowerCase(); + } + } + + // returns shortest representation + public String uuidStr(Object uuid) + { + String s = uuid128(uuid); + boolean starts = s.startsWith("0000"); + boolean ends = s.endsWith("-0000-1000-8000-00805f9b34fb"); + if (starts && ends) + { + // 16-bit + return s.substring(4,8); + } + else if (ends) + { + // 32-bit + return s.substring(0,8); + } + else + { + // 128-bit + return s; + } + } + + private void acquireMutex(@NonNull Semaphore mutex) + { + boolean mutexAcquired = false; + while (mutexAcquired == false) { + try { + mutex.acquire(); + mutexAcquired = true; + } catch (InterruptedException e) { + log(LogLevel.ERROR, "failed to acquire mutex, retrying"); + } + } + } + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) + { + log(LogLevel.DEBUG, "onAttachedToEngine"); + + pluginBinding = flutterPluginBinding; + + this.context = (Application) pluginBinding.getApplicationContext(); + + methodChannel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), NAMESPACE + "/methods"); + methodChannel.setMethodCallHandler(this); + + IntentFilter filterAdapter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); + this.context.registerReceiver(mBluetoothAdapterStateReceiver, filterAdapter); + + IntentFilter filterPair = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST); + this.context.registerReceiver(mBluetoothPairRequestReceiver, filterPair); + + IntentFilter filterBond = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + this.context.registerReceiver(mBluetoothBondStateReceiver, filterBond); + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) + { + log(LogLevel.DEBUG, "onDetachedFromEngine"); + + invokeMethodUIThread("OnDetachedFromEngine", new HashMap<>()); + + pluginBinding = null; + + // stop scanning + if (mBluetoothAdapter != null && mIsScanning) { + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if (scanner != null) { + log(LogLevel.DEBUG, "calling stopScan (OnDetachedFromEngine)"); + scanner.stopScan(getScanCallback()); + mIsScanning = false; + } + } + + disconnectAllDevices("onDetachedFromEngine"); + + context.unregisterReceiver(mBluetoothBondStateReceiver); + context.unregisterReceiver(mBluetoothPairRequestReceiver); + context.unregisterReceiver(mBluetoothAdapterStateReceiver); + context = null; + + methodChannel.setMethodCallHandler(null); + methodChannel = null; + + mBluetoothAdapter = null; + mBluetoothManager = null; + } + + @Override + public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) + { + log(LogLevel.DEBUG, "onAttachedToActivity"); + activityBinding = binding; + activityBinding.addRequestPermissionsResultListener(this); + activityBinding.addActivityResultListener(this); + } + + @Override + public void onDetachedFromActivityForConfigChanges() + { + log(LogLevel.DEBUG, "onDetachedFromActivityForConfigChanges"); + onDetachedFromActivity(); + } + + @Override + public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) + { + log(LogLevel.DEBUG, "onReattachedToActivityForConfigChanges"); + onAttachedToActivity(binding); + } + + @Override + public void onDetachedFromActivity() + { + log(LogLevel.DEBUG, "onDetachedFromActivity"); + activityBinding.removeRequestPermissionsResultListener(this); + activityBinding = null; + } + + //////////////////////////////////////////////////////////// + // ███ ███ ███████ ████████ ██ ██ ██████ ██████ + // ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ████ ██ █████ ██ ███████ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ██ ██ ██ ██████ ██████ + // + // ██████ █████ ██ ██ + // ██ ██ ██ ██ ██ + // ██ ███████ ██ ██ + // ██ ██ ██ ██ ██ + // ██████ ██ ██ ███████ ███████ + + @Override + @SuppressWarnings({"deprecation", "unchecked"}) // needed for compatibility, type safety uses bluetooth_msgs.dart + public void onMethodCall(@NonNull MethodCall call, + @NonNull Result result) + { + try { + acquireMutex(mMethodCallMutex); + + log(LogLevel.DEBUG, "onMethodCall: " + call.method); + + // initialize adapter + if (mBluetoothAdapter == null) { + log(LogLevel.DEBUG, "initializing BluetoothAdapter"); + mBluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE); + mBluetoothAdapter = mBluetoothManager != null ? mBluetoothManager.getAdapter() : null; + } + + // check that we have an adapter, except for + // the functions that do not need it + if(mBluetoothAdapter == null && + "flutterRestart".equals(call.method) == false && + "connectedCount".equals(call.method) == false && + "setLogLevel".equals(call.method) == false && + "isSupported".equals(call.method) == false && + "getAdapterName".equals(call.method) == false && + "getAdapterState".equals(call.method) == false) { + result.error("bluetoothUnavailable", "the device does not support bluetooth", null); + return; + } + + switch (call.method) { + + case "flutterRestart": + { + // no adapter? + if (mBluetoothAdapter == null) { + result.success(0); // no work to do + break; + } + + // stop scanning + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if(scanner != null && mIsScanning) { + log(LogLevel.DEBUG, "calling stopScan (flutterRestart)"); + scanner.stopScan(getScanCallback()); + mIsScanning = false; + } + + // all dart state is reset after flutter restart + // (i.e. Hot Restart) so also reset native state + disconnectAllDevices("flutterRestart"); + + log(LogLevel.DEBUG, "connectedPeripherals: " + mConnectedDevices.size()); + + result.success(mConnectedDevices.size()); + break; + } + + case "setOptions": + { + // Currently ignored on Android + result.success(true); + break; + } + + case "connectedCount": + { + log(LogLevel.DEBUG, "connectedPeripherals: " + mConnectedDevices.size()); + if (mConnectedDevices.size() == 0) { + log(LogLevel.DEBUG, "Hot Restart: complete"); + } + result.success(mConnectedDevices.size()); + break; + } + + case "setLogLevel": + { + int idx = (int)call.arguments; + + // set global var + logLevel = LogLevel.values()[idx]; + + result.success(true); + break; + } + + case "isSupported": + { + result.success(mBluetoothAdapter != null); + break; + } + + case "getAdapterName": + { + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + if (Build.VERSION.SDK_INT <= 30) { // Android 11 (September 2020) + permissions.add(Manifest.permission.BLUETOOTH); + } + + ensurePermissions(permissions, (granted, perm) -> { + + String adapterName = mBluetoothAdapter != null ? mBluetoothAdapter.getName() : "N/A"; + result.success(adapterName != null ? adapterName : ""); + + }); + break; + } + + case "getAdapterState": + { + // get adapterState, if we have permission + int adapterState = -1; // unknown + try { + adapterState = mBluetoothAdapter.getState(); + } catch (Exception e) {} + + // see: BmBluetoothAdapterState + HashMap map = new HashMap<>(); + map.put("adapter_state", bmAdapterStateEnum(adapterState)); + + result.success(map); + break; + } + + case "turnOn": + { + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + if (Build.VERSION.SDK_INT <= 30) { // Android 11 (September 2020) + permissions.add(Manifest.permission.BLUETOOTH); + } + + ensurePermissions(permissions, (granted, perm) -> { + + if (granted == false) { + result.error("turnOn", + String.format("Permission %s required to turn Bluetooth on", perm), null); + return; + } + + if (mBluetoothAdapter.isEnabled()) { + result.success(false); // no work to do + return; + } + + Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + + activityBinding.getActivity().startActivityForResult(enableBtIntent, enableBluetoothRequestCode); + + result.success(true); + return; + }); + break; + } + + case "turnOff": + { + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + if (Build.VERSION.SDK_INT <= 30) { // Android 11 (September 2020) + permissions.add(Manifest.permission.BLUETOOTH); + } + + ensurePermissions(permissions, (granted, perm) -> { + + if (granted == false) { + result.error("turnOff", + String.format("Permission %s required to turn Bluetooth off", perm), null); + return; + } + + if (mBluetoothAdapter.isEnabled() == false) { + result.success(true); // no work to do + return; + } + + // this is deprecated in API level 33. + boolean disabled = mBluetoothAdapter.disable(); + + result.success(disabled); + return; + }); + break; + } + + case "startScan": + { + // see: BmScanSettings + HashMap data = call.arguments(); + List withServices = (List) data.get("with_services"); + List withRemoteIds = (List) data.get("with_remote_ids"); + List withNames = (List) data.get("with_names"); + List withKeywords = (List) data.get("with_keywords"); + List withMsd = (List) data.get("with_msd"); + List withServiceData = (List) data.get("with_service_data"); + boolean continuousUpdates = (boolean) data.get("continuous_updates"); + boolean androidLegacy = (boolean) data.get("android_legacy"); + int androidScanMode = (int) data.get("android_scan_mode"); + boolean androidUsesFineLocation = (boolean) data.get("android_uses_fine_location"); + boolean androidCheckLocationServices = (boolean) data.get("android_check_location_services"); + + if (androidCheckLocationServices && !isLocationEnabled()) { + result.error("startScan", "Location services are required for Bluetooth scan", null); + return; + } + + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_SCAN); + if (androidUsesFineLocation) { + permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + // it is unclear why this is needed, but some phones throw a + // SecurityException AdapterService getRemoteName, without it + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + if (Build.VERSION.SDK_INT <= 30) { // Android 11 (September 2020) + permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); + } + + ensurePermissions(permissions, (granted, perm) -> { + + if (granted == false) { + result.error("startScan", + String.format("Permission %s required to scan devices", perm), null); + return; + } + + // check adapter + if (isAdapterOn() == false) { + result.error("startScan", "Bluetooth must be turned on", null); + return; + } + + // get scanner + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if (scanner == null) { + result.error("startScan", "getBluetoothLeScanner() is null. Is the Adapter on?", null); + return; + } + + // build scan settings + ScanSettings.Builder builder = new ScanSettings.Builder(); + builder.setScanMode(androidScanMode); + if (Build.VERSION.SDK_INT >= 26) { // Android 8.0 (August 2017) + builder.setPhy(ScanSettings.PHY_LE_ALL_SUPPORTED); + builder.setLegacy(androidLegacy); + } + ScanSettings settings = builder.build(); + + // set filters + List filters = new ArrayList<>(); + + // services + for (int i = 0; i < withServices.size(); i++) { + ParcelUuid s = ParcelUuid.fromString(uuid128(withServices.get(i))); + ScanFilter f = new ScanFilter.Builder().setServiceUuid(s).build(); + filters.add(f); + } + + // remoteIds + for (int i = 0; i < withRemoteIds.size(); i++) { + String address = withRemoteIds.get(i); + ScanFilter f = new ScanFilter.Builder().setDeviceAddress(address).build(); + filters.add(f); + } + + // names + for (int i = 0; i < withNames.size(); i++) { + String name = withNames.get(i); + ScanFilter f = new ScanFilter.Builder().setDeviceName(name).build(); + filters.add(f); + } + + // keywords + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + if (withKeywords.size() > 0) { + // device must advertise a name + int a1 = ScanRecord.DATA_TYPE_LOCAL_NAME_SHORT; + int a2 = ScanRecord.DATA_TYPE_LOCAL_NAME_COMPLETE; + ScanFilter f1 = new ScanFilter.Builder().setAdvertisingDataType(a1).build(); + ScanFilter f2 = new ScanFilter.Builder().setAdvertisingDataType(a2).build(); + filters.add(f1); + filters.add(f2); + } + } + + // msd + for (int i = 0; i < withMsd.size(); i++) { + HashMap m = (HashMap) withMsd.get(i); + int id = (int) m.get("manufacturer_id"); + byte[] mdata = (byte[]) m.get("data"); + byte[] mask = (byte[]) m.get("mask"); + ScanFilter f = null; + if (mask.length == 0) { + f = new ScanFilter.Builder().setManufacturerData(id, mdata).build(); + } else { + f = new ScanFilter.Builder().setManufacturerData(id, mdata, mask).build(); + } + filters.add(f); + } + + // service data + for (int i = 0; i < withServiceData.size(); i++) { + HashMap m = (HashMap) withServiceData.get(i); + ParcelUuid s = ParcelUuid.fromString(uuid128((String) m.get("service"))); + byte[] mdata = (byte[]) m.get("data"); + byte[] mask = (byte[]) m.get("mask"); + ScanFilter f = null; + if (mask.length == 0) { + f = new ScanFilter.Builder().setServiceData(s, mdata).build(); + } else { + f = new ScanFilter.Builder().setServiceData(s, mdata, mask).build(); + } + filters.add(f); + } + + // remember for later + mScanFilters = data; + + // clear seen devices + mAdvSeen.clear(); + mScanCounts.clear(); + + scanner.startScan(filters, settings, getScanCallback()); + + mIsScanning = true; + + result.success(true); + }); + break; + } + + case "stopScan": + { + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + + if (scanner != null) { + scanner.stopScan(getScanCallback()); + mIsScanning = false; + } + + result.success(true); + break; + } + + case "getSystemDevices": + { + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + ensurePermissions(permissions, (granted, perm) -> { + + if (granted == false) { + result.error("getSystemDevices", + String.format("Permission %s required to get system devices", perm), null); + return; + } + + // this includes devices connected by other apps + List devices = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT); + + List> devList = new ArrayList>(); + for (BluetoothDevice d : devices) { + devList.add(bmBluetoothDevice(d)); + } + + // See: BmDevicesList + HashMap response = new HashMap<>(); + response.put("devices", devList); + + result.success(response); + }); + break; + } + + case "connect": + { + // see: BmConnectRequest + HashMap args = call.arguments(); + String remoteId = (String) args.get("remote_id"); + boolean autoConnect = ((int) args.get("auto_connect")) != 0; + + ArrayList permissions = new ArrayList<>(); + + if (Build.VERSION.SDK_INT >= 31) { // Android 12 (October 2021) + permissions.add(Manifest.permission.BLUETOOTH_CONNECT); + } + + ensurePermissions(permissions, (granted, perm) -> { + + if (granted == false) { + result.error("connect", + String.format("Permission %s required for new connection", perm), null); + return; + } + + // check adapter + if (isAdapterOn() == false) { + result.error("connect", "Bluetooth must be turned on", null); + return; + } + + // already connecting? + if (mCurrentlyConnectingDevices.get(remoteId) != null) { + log(LogLevel.DEBUG, "already connecting"); + result.success(true); // still work to do + return; + } + + // already connected? + if (mConnectedDevices.get(remoteId) != null) { + log(LogLevel.DEBUG, "already connected"); + result.success(false); // no work to do + return; + } + + // connect + BluetoothGatt gatt = null; + BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(remoteId); + if (Build.VERSION.SDK_INT >= 23) { // Android 6.0 (October 2015) + gatt = device.connectGatt(context, autoConnect, mGattCallback, BluetoothDevice.TRANSPORT_LE); + } else { + try { + // From Android LOLLIPOP (21) the transport types exists, but it is private + // have to use reflection to call it for TRANSPORT_LE + Method connectGattMethod = device.getClass() + .getDeclaredMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class); + connectGattMethod.setAccessible(true); + gatt = (BluetoothGatt) connectGattMethod.invoke(device, context, autoConnect, mGattCallback, 2 /* TRANSPORT_LE */); + } catch (Exception ex) { + // fall back to default method if reflection fails + gatt = device.connectGatt(context, autoConnect, mGattCallback); + } + } + + // error check + if (gatt == null) { + result.error("connect", "device.connectGatt returned null", null); + return; + } + + // add to currently connecting peripherals + mCurrentlyConnectingDevices.put(remoteId, gatt); + + // remember autoconnect + if (autoConnect) { + mAutoConnected.put(remoteId, gatt); + } else { + mAutoConnected.remove(remoteId); + } + + result.success(true); + }); + break; + } + + case "disconnect": + { + String remoteId = (String) call.arguments; + + // already disconnected? + BluetoothGatt gatt = null; + if (gatt == null) { + gatt = mCurrentlyConnectingDevices.get(remoteId); + if (gatt != null) { + log(LogLevel.DEBUG, "disconnect: cancelling connection in progress"); + } + } + if (gatt == null) { + gatt = mConnectedDevices.get(remoteId); + } + if (gatt == null) { + gatt = mAutoConnected.get(remoteId); + if (gatt != null) { + log(LogLevel.DEBUG, "already disconnected. disabling autoconnect"); + mAutoConnected.remove(remoteId); + gatt.disconnect(); + gatt.close(); + result.success(false); // no work to do + return; + } + } + if (gatt == null) { + // Offband #694: WARN, not DEBUG. This no-op means the Dart + // layer's disconnect resolves instantly with nothing done, + // which is invisible in exported logs at DEBUG level and is + // exactly the fingerprint of an orphaned-handle latch. + log(LogLevel.WARNING, "disconnect: no tracked gatt handle for " + remoteId + " (no work done)"); + result.success(false); // no work to do + return; + } + + // calling disconnect explicitly turns off autoconnect. + // this allows gatt resources to be reclaimed + mAutoConnected.remove(remoteId); + + // disconnect + gatt.disconnect(); + + // Offband #694: if Android never delivers the DISCONNECTED + // callback, gatt.close() (which normally runs in + // onConnectionStateChange) never happens and this process holds + // the link until it dies. Backstop: if this exact handle is + // still tracked as connected after 5s, force-close it and + // synthesize the disconnect event, mirroring what the + // cancel-while-connecting path below already does. + if (mConnectedDevices.get(remoteId) == gatt) { + final BluetoothGatt disconnectingGatt = gatt; + final String backstopRemoteId = remoteId; + final Handler backstopHandler = new Handler(Looper.getMainLooper()); + backstopHandler.postDelayed(new Runnable() { + @Override + public void run() { + // Never block the main thread on the mutex (ANR + // risk, pre-PR review): if a callback holds it, + // re-check shortly instead of waiting. + if (!mMethodCallMutex.tryAcquire()) { + backstopHandler.postDelayed(this, 250); + return; + } + boolean stillTracked; + try { + stillTracked = mConnectedDevices.get(backstopRemoteId) == disconnectingGatt; + if (stillTracked) { + log(LogLevel.WARNING, "disconnect not confirmed after 5s, force-closing: " + backstopRemoteId); + mConnectedDevices.remove(backstopRemoteId); + mCurrentlyConnectingDevices.remove(backstopRemoteId); + try { disconnectingGatt.close(); } catch (Exception e) { /* best effort */ } + } + } finally { + mMethodCallMutex.release(); + } + if (stillTracked) { + // random number defined by this fork, alongside + // flutter blue plus's own 23789258 cancel code. + int bmForceClosedErrorCode = 23789259; + + // see: BmConnectionStateResponse + HashMap backstopResponse = new HashMap<>(); + backstopResponse.put("remote_id", backstopRemoteId); + backstopResponse.put("connection_state", bmConnectionStateEnum(BluetoothProfile.STATE_DISCONNECTED)); + backstopResponse.put("disconnect_reason_code", bmForceClosedErrorCode); + backstopResponse.put("disconnect_reason_string", "disconnect not confirmed, force-closed"); + + invokeMethodUIThread("OnConnectionStateChanged", backstopResponse); + } + } + }, 5000); + } + + // was connecting? + if (mCurrentlyConnectingDevices.get(remoteId) != null) { + + // remove + mCurrentlyConnectingDevices.remove(remoteId); + + // cleanup + gatt.close(); + + // random number defined by flutter blue plus. + int bmUserCanceledErrorCode = 23789258; + + // see: BmConnectionStateResponse + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + response.put("connection_state", bmConnectionStateEnum(BluetoothProfile.STATE_DISCONNECTED)); + response.put("disconnect_reason_code", bmUserCanceledErrorCode); + response.put("disconnect_reason_string", "connection canceled"); + + invokeMethodUIThread("OnConnectionStateChanged", response); + } + + result.success(true); + break; + } + + case "discoverServices": + { + String remoteId = (String) call.arguments; + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("discoverServices", "device is disconnected", null); + break; + } + + // discover services + if(gatt.discoverServices() == false) { + result.error("discoverServices", "gatt.discoverServices() returned false", null); + break; + } + + result.success(true); + break; + } + + case "readCharacteristic": + { + // see: BmReadCharacteristicRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + String primaryServiceUuid = (String) data.get("primary_service_uuid"); + String serviceUuid = (String) data.get("service_uuid"); + String characteristicUuid = (String) data.get("characteristic_uuid"); + Integer instanceId = (Integer) data.get("instance_id"); + + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("readCharacteristic", "device is disconnected", null); + break; + } + + // find characteristic + ChrFound found = locateCharacteristic(gatt, primaryServiceUuid, serviceUuid, characteristicUuid, instanceId); + if (found.error != null) { + result.error("readCharacteristic", found.error, null); + break; + } + + BluetoothGattCharacteristic characteristic = found.characteristic; + + // check readable + if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) == 0) { + result.error("readCharacteristic", + "The READ property is not supported by this BLE characteristic", null); + break; + } + + // read + if(gatt.readCharacteristic(characteristic) == false) { + result.error("readCharacteristic", + "gatt.readCharacteristic() returned false", null); + break; + } + + result.success(true); + break; + } + + case "writeCharacteristic": + { + // see: BmWriteCharacteristicRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + String primaryServiceUuid = (String) data.get("primary_service_uuid"); + String serviceUuid = (String) data.get("service_uuid"); + String characteristicUuid = (String) data.get("characteristic_uuid"); + Integer instanceId = (Integer) data.get("instance_id"); + byte[] value = (byte[]) data.get("value"); + int writeTypeInt = (int) data.get("write_type"); + boolean allowLongWrite = ((int) data.get("allow_long_write")) != 0; + + int writeType = writeTypeInt == 0 ? + BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT : + BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE; + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("writeCharacteristic", "device is disconnected", null); + break; + } + + // find characteristic + ChrFound found = locateCharacteristic(gatt, primaryServiceUuid, serviceUuid, characteristicUuid, instanceId); + if (found.error != null) { + result.error("writeCharacteristic", found.error, null); + break; + } + + BluetoothGattCharacteristic characteristic = found.characteristic; + + // check writeable + if(writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) { + if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) { + result.error("writeCharacteristic", + "The WRITE_NO_RESPONSE property is not supported by this BLE characteristic", null); + break; + } + } else { + if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0) { + result.error("writeCharacteristic", + "The WRITE property is not supported by this BLE characteristic", null); + break; + } + } + + // check maximum payload + int maxLen = getMaxPayload(remoteId, writeType, allowLongWrite); + int dataLen = value.length; + if (dataLen > maxLen) { + String a = writeTypeInt == 0 ? "withResponse" : "withoutResponse"; + String b = writeTypeInt == 0 ? (allowLongWrite ? ", allowLongWrite" : ", noLongWrite") : ""; + String str = "data longer than allowed. dataLen: " + dataLen + " > max: " + maxLen + " (" + a + b +")"; + result.error("writeCharacteristic", str, null); + break; + } + + // remember the data we are writing + if (primaryServiceUuid == null) {primaryServiceUuid = "";} + String key = remoteId + ":" + primaryServiceUuid + ":" + serviceUuid + ":" + + characteristicUuid + ":" + instanceId; + mWriteChr.put(key, value); + + // write characteristic + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + + int rv = gatt.writeCharacteristic(characteristic, value, writeType); + + if (rv != BluetoothStatusCodes.SUCCESS) { + String s = "gatt.writeCharacteristic() returned " + rv + " : " + bluetoothStatusString(rv); + result.error("writeCharacteristic", s, null); + return; + } + + } else { + // set value + if(!characteristic.setValue(value)) { + result.error("writeCharacteristic", "characteristic.setValue() returned false", null); + break; + } + + // Write type + characteristic.setWriteType(writeType); + + // Write Char + if(!gatt.writeCharacteristic(characteristic)){ + result.error("writeCharacteristic", "gatt.writeCharacteristic() returned false", null); + break; + } + } + + result.success(true); + break; + } + + case "readDescriptor": + { + // see: BmReadDescriptorRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + String primaryServiceUuid = (String) data.get("primary_service_uuid"); + String serviceUuid = (String) data.get("service_uuid"); + String characteristicUuid = (String) data.get("characteristic_uuid"); + Integer instanceId = (Integer) data.get("instance_id"); + String descriptorUuid = (String) data.get("descriptor_uuid"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("readDescriptor", "device is disconnected", null); + break; + } + + // find characteristic + ChrFound found = locateCharacteristic(gatt, primaryServiceUuid, serviceUuid, characteristicUuid, instanceId); + if (found.error != null) { + result.error("readDescriptor", found.error, null); + break; + } + + BluetoothGattCharacteristic characteristic = found.characteristic; + + + // find descriptor + BluetoothGattDescriptor descriptor = getDescriptorFromArray(descriptorUuid, characteristic.getDescriptors()); + if(descriptor == null) { + String s = "descriptor not found on characteristic. (desc: " + descriptorUuid + " chr: " + characteristicUuid + ")"; + result.error("writeDescriptor", s, null); + break; + } + + // read descriptor + if(gatt.readDescriptor(descriptor) == false) { + result.error("readDescriptor", "gatt.readDescriptor() returned false", null); + break; + } + + result.success(true); + break; + } + + case "writeDescriptor": + { + // see: BmWriteDescriptorRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + String primaryServiceUuid = (String) data.get("primary_service_uuid"); + String serviceUuid = (String) data.get("service_uuid"); + String characteristicUuid = (String) data.get("characteristic_uuid"); + Integer instanceId = (Integer) data.get("instance_id"); + String descriptorUuid = (String) data.get("descriptor_uuid"); + byte[] value = (byte[]) data.get("value"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("writeDescriptor", "device is disconnected", null); + break; + } + + // find characteristic + ChrFound found = locateCharacteristic(gatt, primaryServiceUuid, serviceUuid, characteristicUuid, instanceId); + if (found.error != null) { + result.error("writeDescriptor", found.error, null); + break; + } + + BluetoothGattCharacteristic characteristic = found.characteristic; + + // find descriptor + BluetoothGattDescriptor descriptor = getDescriptorFromArray(descriptorUuid, characteristic.getDescriptors()); + if(descriptor == null) { + String s = "descriptor not found on characteristic. (desc: " + descriptorUuid + " chr: " + characteristicUuid + ")"; + result.error("writeDescriptor", s, null); + break; + } + + // check mtu + int mtu = mMtu.get(remoteId); + if ((mtu-3) < value.length) { + String s = "data longer than mtu allows. dataLength: " + value.length + "> max: " + (mtu-3); + result.error("writeDescriptor", s, null); + break; + } + + // remember the data we are writing + if (primaryServiceUuid == null) {primaryServiceUuid = "";} + String key = remoteId + ":" + primaryServiceUuid + ":" + serviceUuid + ":" + + characteristicUuid + ":" + instanceId + ":" + descriptorUuid; + mWriteDesc.put(key, value); + + // write descriptor + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + + int rv = gatt.writeDescriptor(descriptor, value); + if (rv != BluetoothStatusCodes.SUCCESS) { + String s = "gatt.writeDescriptor() returned " + rv + " : " + bluetoothStatusString(rv); + result.error("writeDescriptor", s, null); + return; + } + + } else { + + // Set descriptor + if(!descriptor.setValue(value)){ + result.error("writeDescriptor", "descriptor.setValue() returned false", null); + break; + } + + // Write descriptor + if(!gatt.writeDescriptor(descriptor)){ + result.error("writeDescriptor", "gatt.writeDescriptor() returned false", null); + break; + } + } + + result.success(true); + break; + } + + case "setNotifyValue": + { + // see: BmSetNotifyValueRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + String primaryServiceUuid = (String) data.get("primary_service_uuid"); + String serviceUuid = (String) data.get("service_uuid"); + String characteristicUuid = (String) data.get("characteristic_uuid"); + Integer instanceId = (Integer) data.get("instance_id"); + boolean forceIndications = (boolean) data.get("force_indications"); + boolean enable = (boolean) data.get("enable"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("setNotifyValue", "device is disconnected", null); + break; + } + + // find characteristic + ChrFound found = locateCharacteristic(gatt, primaryServiceUuid, serviceUuid, characteristicUuid, instanceId); + if (found.error != null) { + result.error("setNotifyValue", found.error, null); + break; + } + + BluetoothGattCharacteristic characteristic = found.characteristic; + + // configure local Android device to listen for characteristic changes + if(!gatt.setCharacteristicNotification(characteristic, enable)){ + result.error("setNotifyValue", + "gatt.setCharacteristicNotification(" + enable + ") returned false", null); + break; + } + + // find cccd descriptor + BluetoothGattDescriptor cccd = getDescriptorFromArray(CCCD, characteristic.getDescriptors()); + if(cccd == null) { + // Some ble devices do not actually need their CCCD updated. + // thus setCharacteristicNotification() is all that is required to enable notifications. + // The arduino "bluno" devices are an example. + String uuid = uuidStr(characteristic.getUuid()); + log(LogLevel.WARNING, "CCCD descriptor for characteristic not found: " + uuid); + result.success(false); + return; + } + + byte[] descriptorValue = null; + + // determine value to write + if(enable) { + + boolean canNotify = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0; + boolean canIndicate = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0; + + if(!canIndicate && !canNotify) { + result.error("setNotifyValue", + "neither NOTIFY nor INDICATE properties are supported by this BLE characteristic", null); + break; + } + + if (forceIndications && !canIndicate) { + result.error("setNotifyValue","INDICATE not supported by this BLE characteristic", null); + break; + } + + // If a characteristic supports both notifications and indications, + // we use notifications. This matches how CoreBluetooth works on iOS. + // Except of course, if forceIndications is enabled. + if(canIndicate) {descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;} + if(canNotify) {descriptorValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;} + if(forceIndications) {descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;} + + } else { + descriptorValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; + } + + // remember the data we are writing + if (primaryServiceUuid == null) {primaryServiceUuid = "";} + String key = remoteId + ":" + primaryServiceUuid + ":" + serviceUuid + ":" + + characteristicUuid + ":" + instanceId + ":" + CCCD; + mWriteDesc.put(key, descriptorValue); + + // write descriptor + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + + int rv = gatt.writeDescriptor(cccd, descriptorValue); + if (rv != BluetoothStatusCodes.SUCCESS) { + String s = "gatt.writeDescriptor() returned " + rv + " : " + bluetoothStatusString(rv); + result.error("setNotifyValue", s, null); + break; + } + + } else { + + // set new value + if (!cccd.setValue(descriptorValue)) { + result.error("setNotifyValue", "cccd.setValue() returned false", null); + break; + } + + // update notifications on remote BLE device + if (!gatt.writeDescriptor(cccd)) { + result.error("setNotifyValue", "gatt.writeDescriptor() returned false", null); + break; + } + } + + result.success(true); + break; + } + + case "requestMtu": + { + // see: BmMtuChangeRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + int mtu = (int) data.get("mtu"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("requestMtu", "device is disconnected", null); + break; + } + + // request mtu + if(gatt.requestMtu(mtu) == false) { + result.error("requestMtu", "gatt.requestMtu() returned false", null); + break; + } + + result.success(true); + break; + } + + case "readRssi": + { + String remoteId = (String) call.arguments; + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("readRssi", "device is disconnected", null); + break; + } + + // read rssi + if(gatt.readRemoteRssi() == false) { + result.error("readRssi", "gatt.readRemoteRssi() returned false", null); + break; + } + + result.success(true); + break; + } + + case "requestConnectionPriority": + { + // see: BmConnectionPriorityRequest + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + int connectionPriority = (int) data.get("connection_priority"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("requestConnectionPriority", "device is disconnected", null); + break; + } + + int cpInteger = bmConnectionPriorityParse(connectionPriority); + + // request priority + if(gatt.requestConnectionPriority(cpInteger) == false) { + result.error("requestConnectionPriority", "gatt.requestConnectionPriority() returned false", null); + break; + } + + result.success(true); + break; + } + + case "getPhySupport": + { + if(Build.VERSION.SDK_INT < 26) { // Android 8.0 (August 2017) + result.error("getPhySupport", + "Only supported on devices >= API 26. This device == " + + Build.VERSION.SDK_INT, null); + break; + } + + // see: PhySupport + HashMap map = new HashMap<>(); + map.put("le_2M", mBluetoothAdapter.isLe2MPhySupported()); + map.put("le_coded", mBluetoothAdapter.isLeCodedPhySupported()); + + result.success(map); + break; + } + + case "setPreferredPhy": + { + if(Build.VERSION.SDK_INT < 26) { // Android 8.0 (August 2017) + result.error("setPreferredPhy", + "Only supported on devices >= API 26. This device == " + + Build.VERSION.SDK_INT, null); + break; + } + + // see: BmPreferredPhy + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + int txPhy = (int) data.get("tx_phy"); + int rxPhy = (int) data.get("rx_phy"); + int phyOptions = (int) data.get("phy_options"); + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("setPreferredPhy", "device is disconnected", null); + break; + } + + // set preferred phy + gatt.setPreferredPhy(txPhy, rxPhy, phyOptions); + + result.success(true); + break; + } + + case "getBondedDevices": + { + final Set bondedDevices = mBluetoothAdapter.getBondedDevices(); + + List> devList = new ArrayList>(); + for (BluetoothDevice d : bondedDevices) { + devList.add(bmBluetoothDevice(d)); + } + + HashMap response = new HashMap(); + response.put("devices", devList); + + result.success(response); + break; + } + + case "getBondState": + { + String remoteId = (String) call.arguments; + + // get bond state + BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(remoteId); + + // see: BmBondStateResponse + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + response.put("bond_state", bmBondStateEnum(device.getBondState())); + response.put("prev_state", null); + + result.success(response); + break; + } + + case "createBond": + { + HashMap data = call.arguments(); + String remoteId = (String) data.get("remote_id"); + if (data.get("pin") != null) { + mBondingPins.put(remoteId, (byte[]) data.get("pin")); + } + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("createBond", "device is disconnected", null); + break; + } + + BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(remoteId); + + // already bonded? + if (device.getBondState() == BluetoothDevice.BOND_BONDED) { + log(LogLevel.WARNING, "already bonded"); + result.success(false); // no work to do + break; + } + + // bonding already in progress? + if (device.getBondState() == BluetoothDevice.BOND_BONDING) { + log(LogLevel.WARNING, "bonding already in progress"); + result.success(true); // caller must wait for bond completion + break; + } + + // bond + if(device.createBond() == false) { + result.error("createBond", "device.createBond() returned false", null); + break; + } + + result.success(true); + break; + } + + case "removeBond": + { + String remoteId = (String) call.arguments; + + BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(remoteId); + + // already removed? + if (device.getBondState() == BluetoothDevice.BOND_NONE) { + log(LogLevel.WARNING, "already not bonded"); + result.success(false); // no work to do + break; + } + + Method removeBondMethod = device.getClass().getMethod("removeBond"); + boolean rv = (boolean) removeBondMethod.invoke(device); + if(rv == false) { + result.error("removeBond", "device.removeBond() returned false", null); + break; + } + + result.success(true); + break; + } + + case "clearGattCache": + { + String remoteId = (String) call.arguments; + + // check connection + BluetoothGatt gatt = mConnectedDevices.get(remoteId); + if(gatt == null) { + result.error("clearGattCache", "device is disconnected", null); + break; + } + + final Method refreshMethod = gatt.getClass().getMethod("refresh"); + if (refreshMethod == null) { + result.error("clearGattCache", "unsupported on this android version", null); + break; + } + + refreshMethod.invoke(gatt); + + result.success(true); + break; + } + + default: + { + result.notImplemented(); + break; + } + } + } catch (Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + String stackTrace = sw.toString(); + result.error("androidException", e.toString(), stackTrace); + return; + } finally { + mMethodCallMutex.release(); + } + } + + ////////////////////////////////////////////////////////////////////// + // █████ ██████ ████████ ██ ██ ██ ██ ████████ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ███████ ██ ██ ██ ██ ██ ██ ██ ████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ██████ ██ ██ ████ ██ ██ ██ + // + // ██████ ███████ ███████ ██ ██ ██ ████████ + // ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ █████ ███████ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ███████ ██████ ███████ ██ + + @Override + public boolean onActivityResult(int requestCode, int resultCode, Intent data) + { + if (requestCode == enableBluetoothRequestCode) { + + // see: BmTurnOnResponse + HashMap map = new HashMap<>(); + map.put("user_accepted", resultCode == Activity.RESULT_OK); + + invokeMethodUIThread("OnTurnOnResponse", map); + + return true; + } + + return false; // did not handle anything + } + + ////////////////////////////////////////////////////////////////////////////////////// + // ██████ ███████ ██████ ███ ███ ██ ███████ ███████ ██ ██████ ███ ██ + // ██ ██ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ████ ██ + // ██████ █████ ██████ ██ ████ ██ ██ ███████ ███████ ██ ██ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ███████ ██ ██ ██ ██ ██ ███████ ███████ ██ ██████ ██ ████ + + @Override + public boolean onRequestPermissionsResult(int requestCode, + String[] permissions, + int[] grantResults) { + OperationOnPermission operation = operationsOnPermission.get(requestCode); + operationsOnPermission.remove(requestCode); // Clean up to prevent memory leaks + + if (operation != null && grantResults.length > 0) { + for (int i = 0; i < grantResults.length; i++) { + if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { + operation.op(false, permissions[i]); // permission denied + return true; + } + } + operation.op(true, null); // permission granted + return true; + } else { + return false; + } + } + + private void ensurePermissions(List permissions, OperationOnPermission operation) { + // check that we have a context + if (context == null) { + operation.op(false, "Application Context is null"); + return; + } + + // Filter out permissions that are already granted + List permissionsNeeded = new ArrayList<>(); + for (String permission : permissions) { + if (permission != null && ContextCompat.checkSelfPermission(context, permission) + != PackageManager.PERMISSION_GRANTED) { + permissionsNeeded.add(permission); + } + } + + // If all permissions are granted, proceed with the operation + if (permissionsNeeded.isEmpty()) { + operation.op(true, null); + return; + } + + askPermission(permissionsNeeded, operation); + } + + private void askPermission(List permissionsNeeded, OperationOnPermission operation) { + if (permissionsNeeded.isEmpty()) { + operation.op(true, null); + return; + } + + // Store the operation with the current request code + operationsOnPermission.put(lastEventId, operation); + + ActivityCompat.requestPermissions( + activityBinding.getActivity(), + permissionsNeeded.toArray(new String[0]), + lastEventId); + + lastEventId++; + } + + // Check if Android location services are enabled + @SuppressWarnings("deprecation") + private boolean isLocationEnabled() { + if (Build.VERSION.SDK_INT >= 31) { + // Android 12 (October 2021) - location services are not required for BLE scanning + return true; + } + + Context context = pluginBinding.getApplicationContext(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + // This is a new method provided in API 28 / Android 9 August 2018 + LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + return lm != null && lm.isLocationEnabled(); + } else { + // This was deprecated in API 28 + int mode = Settings.Secure.getInt(context.getContentResolver(), + Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF); + return mode != Settings.Secure.LOCATION_MODE_OFF; + } + } + + ////////////////////////////////////////////// + // ██████ ██ ███████ + // ██ ██ ██ ██ + // ██████ ██ █████ + // ██ ██ ██ ██ + // ██████ ███████ ███████ + // + // ██ ██ ████████ ██ ██ ███████ + // ██ ██ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ███████ + // ██ ██ ██ ██ ██ ██ + // ██████ ██ ██ ███████ ███████ + + class ChrFound { + public BluetoothGattCharacteristic characteristic; + public String error; + + public ChrFound(BluetoothGattCharacteristic characteristic, String error) { + this.characteristic = characteristic; + this.error = error; + } + } + + private static int getInstanceId(BluetoothGattCharacteristic target) { + BluetoothGattService svc = target.getService(); + if (svc == null) return 0; + + UUID needle = target.getUuid(); + List list = svc.getCharacteristics(); + + int sameUuidCount = 0; + Integer sysIdForTarget = null; + + for (BluetoothGattCharacteristic c : list) { + if (needle.equals(c.getUuid())) { + sameUuidCount++; + if (c == target) { + // System-provided instance id + // (stable for the life of the discovery result) + sysIdForTarget = c.getInstanceId(); + } + } + } + + // Only use system instanceId to *disambiguate* when duplicates exist + return (sameUuidCount > 1) ? (sysIdForTarget != null ? sysIdForTarget : 0) : 0; + } + + + private ChrFound locateCharacteristic(BluetoothGatt gatt, + String primaryServiceUuid, + String serviceUuid, + String characteristicUuid, + Integer instanceId) + { + // remember this + boolean isSecondaryService = primaryServiceUuid != null; + + // primary service + if (primaryServiceUuid == null) { + primaryServiceUuid = serviceUuid; + } + + // primary + BluetoothGattService primaryService = getServiceFromArray(primaryServiceUuid, gatt.getServices()); + if(primaryService == null) { + return new ChrFound(null, "primary service not found '" + primaryServiceUuid + "'"); + } + + // secondary + BluetoothGattService secondaryService = null; + if(isSecondaryService) { + secondaryService = getServiceFromArray(serviceUuid, primaryService.getIncludedServices()); + if(secondaryService == null) { + return new ChrFound(null, "secondary service not found '" + serviceUuid + "' (primary service '" + primaryServiceUuid + "')"); + } + } + + // which service? + BluetoothGattService service = (secondaryService != null) ? secondaryService : primaryService; + + // characteristic + BluetoothGattCharacteristic characteristic = getCharacteristicFromArray(characteristicUuid, service.getCharacteristics(), instanceId); + if(characteristic == null) { + return new ChrFound(null, "characteristic not found in service " + + "(chr: '" + characteristicUuid + "' svc: '" + serviceUuid + "')"); + } + + return new ChrFound(characteristic, null); + } + + private BluetoothGattService getServiceFromArray(String uuid, List array) + { + for (BluetoothGattService s : array) { + if (uuid128(s.getUuid()).equals(uuid128(uuid))) { + return s; + } + } + return null; + } + + private BluetoothGattCharacteristic getCharacteristicFromArray(String uuid, List array, Integer instanceId) + { + for (BluetoothGattCharacteristic c : array) { + if (uuid128(c.getUuid()).equals(uuid128(uuid))) { + if (getInstanceId(c) == instanceId) { + return c; + } + } + } + return null; + } + + private BluetoothGattDescriptor getDescriptorFromArray(String uuid, List array) + { + for (BluetoothGattDescriptor d : array) { + if (uuid128(d.getUuid()).equals(uuid128(uuid))) { + return d; + } + } + return null; + } + + private boolean filterKeywords(List keywords, String target) { + if (keywords.isEmpty()) { + return true; + } + if (target == null) { + return false; + } + for (String k : keywords) { + if (target.contains(k)) { + return true; + } + } + return false; + } + + private int getMaxPayload(String remoteId, int writeType, boolean allowLongWrite) + { + // 512 this comes from the BLE spec. Characteritics should not + // be longer than 512. Android also enforces this as the maximum in internal code. + int maxAttrLen = 512; + + // if no response, or allowLongWrite is not allowed, we can only write up to MTU-3. + // This is the same limitation as iOS, and ensures transfer reliability. + if (writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE || allowLongWrite == false) { + + // get mtu + Integer mtu = mMtu.get(remoteId); + if (mtu == null) { + mtu = 23; // 23 is the minumum MTU, as per the BLE spec + } + + return Math.min(mtu - 3, maxAttrLen); + + } else { + // if withResponse and allowLongWrite is allowed, + // android will auto split up to the maxAttrLen. + return maxAttrLen; + } + } + + private void disconnectAllDevices(String func) + { + log(LogLevel.DEBUG, "disconnectAllDevices("+func+")"); + + // merge connected & autoconnected + Map allDevices = new HashMap<>(); + allDevices.putAll(mConnectedDevices); + allDevices.putAll(mAutoConnected); + + // request disconnections + for (BluetoothGatt gatt : allDevices.values()) { + + if (func == "adapterTurnOff") { + + // Note: + // - calling `disconnect` and `close` after the adapter + // is turned off is not necessary. It is implied. + // Calling them leads to a `DeadObjectException`. + // - But, we must make sure the disconnect callback is called. + // It's surprising but android does not invoke this callback itself. + mGattCallback.onConnectionStateChange(gatt, 0, BluetoothProfile.STATE_DISCONNECTED); + + } else { + + String remoteId = gatt.getDevice().getAddress(); + + // disconnect + log(LogLevel.DEBUG, "calling disconnect: " + remoteId); + gatt.disconnect(); + + // it is important to close after disconnection, otherwise we will + // quickly run out of bluetooth resources, preventing new connections + log(LogLevel.DEBUG, "calling close: " + remoteId); + gatt.close(); + } + } + + mConnectedDevices.clear(); + mCurrentlyConnectingDevices.clear(); + mBondingDevices.clear(); + mBondingPins.clear(); + mMtu.clear(); + mWriteChr.clear(); + mWriteDesc.clear(); + mAutoConnected.clear(); + } + + int getAppearanceFromScanRecord(ScanRecord adv) { + + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + Map map = adv.getAdvertisingDataMap(); + if (map.containsKey(ScanRecord.DATA_TYPE_APPEARANCE)) { + byte[] bytes = map.get(ScanRecord.DATA_TYPE_APPEARANCE); + if (bytes.length == 2) { + int loByte = bytes[0] & 0xFF; + int hiByte = bytes[1] & 0xFF; + return hiByte * 256 + loByte; + } + } + return 0; + } + + // For API Level 21+ + byte[] bytes = adv.getBytes(); + + int n = 0; + + while (n < bytes.length) { + int fieldLen = bytes[n] & 0xFF; + + // no more or malformed data + if (fieldLen <= 0) { + break; + } + + // Ensuring we don't go past the bytes array + if (n + fieldLen >= bytes.length) { + break; + } + + int dataType = bytes[n + 1] & 0xFF; + + // no more data + if (dataType == 0) { + break; + } + + // appearance type byte + if (dataType == 0x19 && fieldLen == 3) { + int high = (bytes[n + 3] & 0xFF) << 8; + int low = (bytes[n + 2] & 0xFF); + return high | low; + } + + n += fieldLen + 1; + } + + return 0; + } + + // The original android implementation has a bug - it does not + // concatenate handle multiple MSD in the same advertisement. + byte[] getManufacturerSpecificData(ScanRecord adv) { + byte[] bytes = adv.getBytes(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + int n = 0; + while (n < bytes.length) { + + // layout: + // n[0] = fieldlen + // n[1] = datatype (MSD) + // n[2] = manufacturerId (low) + // n[3] = manufacturerId (high) + // n[4] = data... + int fieldLen = bytes[n] & 0xFF; + + // no more or malformed data + if (fieldLen <= 0) { + break; + } + + // Ensuring we don't go past the bytes array + if (n + fieldLen >= bytes.length) { + break; + } + + int dataType = bytes[n + 1] & 0xFF; + + // Check for Manufacturer Specific Data type (0xFF) + // and that the field is large enough (at least 2 bytes: type + at least 1 data byte) + if (dataType == 0xFF && fieldLen >= 2) { + output.write(bytes, n + 2, fieldLen - 1); + } + + n += fieldLen + 1; + } + return output.toByteArray(); + } + + + ///////////////////////////////////////////////////////////////////////////////////// + // █████ ██████ █████ ██████ ████████ ███████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ███████ ██ ██ ███████ ██████ ██ █████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ██████ ██ ██ ██ ██ ███████ ██ ██ + // + // ██████ ███████ ██████ ███████ ██ ██ ██ ███████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ █████ ██ █████ ██ ██ ██ █████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ██████ ███████ ██ ████ ███████ ██ ██ + + private final BroadcastReceiver mBluetoothAdapterStateReceiver = new BroadcastReceiver() + { + @Override + public void onReceive(Context context, Intent intent) + { + final String action = intent.getAction(); + + // no change? + if (action == null || BluetoothAdapter.ACTION_STATE_CHANGED.equals(action) == false) { + return; + } + + final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); + + log(LogLevel.DEBUG, "OnAdapterStateChanged: " + adapterStateString(adapterState)); + + // stop scanning when adapter is turned back on. + // Otherwise, scanning automatically resumes when the adapter is + // turned back on. I don't think most users expect that. + if (adapterState == BluetoothAdapter.STATE_ON) { + if (mBluetoothAdapter != null && mIsScanning) { + BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); + if (scanner != null) { + log(LogLevel.DEBUG, "calling stopScan (Bluetooth Restarted)"); + scanner.stopScan(getScanCallback()); + mIsScanning = false; + } + } + } + + // see: BmBluetoothAdapterState + HashMap map = new HashMap<>(); + map.put("adapter_state", bmAdapterStateEnum(adapterState)); + + invokeMethodUIThread("OnAdapterStateChanged", map); + + // disconnect all devices + if (adapterState == BluetoothAdapter.STATE_TURNING_OFF || + adapterState == BluetoothAdapter.STATE_OFF) { + disconnectAllDevices("adapterTurnOff"); + } + } + }; + + ///////////////////////////////////////////////////////////////////////////////////// + // ██████ ██████ ███ ██ ██████ + // ██ ██ ██ ██ ████ ██ ██ ██ + // ██████ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ ██████ ██ ████ ██████ + // + // ██████ ███████ ██████ ███████ ██ ██ ██ ███████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ █████ ██ █████ ██ ██ ██ █████ ██████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ██████ ███████ ██ ████ ███████ ██ ██ + + + private final BroadcastReceiver mBluetoothPairRequestReceiver = new BroadcastReceiver() { + @Override + @SuppressWarnings("deprecation") // need for compatability + public void onReceive(Context context, Intent intent) { + final String action = intent.getAction(); + if (action == null || action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST) == false) { + return; + } + + // BluetoothDevice + final BluetoothDevice device; + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice.class); + } else { + device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + } + + String remoteId = device.getAddress(); + if (mBondingPins.containsKey(remoteId)) { + byte[] pin = mBondingPins.get(remoteId); + log(LogLevel.DEBUG, "Setting PIN code for " + remoteId + ": " + bytesToHex(pin)); + // min. API level 19 + if (device.setPin(pin) == false) { + log(LogLevel.ERROR, "setPin() failed on " + remoteId); + } + mBondingPins.remove(remoteId); + } + } + }; + + private final BroadcastReceiver mBluetoothBondStateReceiver = new BroadcastReceiver() + { + @Override + @SuppressWarnings("deprecation") // need for compatability + public void onReceive(Context context, Intent intent) + { + final String action = intent.getAction(); + + // no change? + if (action == null || action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED) == false) { + return; + } + + // BluetoothDevice + final BluetoothDevice device; + if (Build.VERSION.SDK_INT >= 33) { // Android 13 (August 2022) + device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice.class); + } else { + device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + } + + final int cur = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); + final int prev = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1); + + log(LogLevel.DEBUG, "OnBondStateChanged: " + bondStateString(cur) + " prev: " + bondStateString(prev)); + + String remoteId = device.getAddress(); + + // remember which devices are currently bonding + if (cur == BluetoothDevice.BOND_BONDING) { + mBondingDevices.put(remoteId, device); + } else { + mBondingDevices.remove(remoteId); + } + + // see: BmBondStateResponse + HashMap map = new HashMap<>(); + map.put("remote_id", remoteId); + map.put("bond_state", bmBondStateEnum(cur)); + map.put("prev_state", bmBondStateEnum(prev)); + + invokeMethodUIThread("OnBondStateChanged", map); + } + }; + + ///////////////////////////////////////////////////////////////////////////// + // ███████ ██████ █████ ███ ██ + // ██ ██ ██ ██ ████ ██ + // ███████ ██ ███████ ██ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ + // ███████ ██████ ██ ██ ██ ████ + // + // ██████ █████ ██ ██ ██████ █████ ██████ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ███████ ██ ██ ██████ ███████ ██ █████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ ██ ██ ███████ ███████ ██████ ██ ██ ██████ ██ ██ + + private ScanCallback scanCallback; + + private int scanCountIncrement(String remoteId) { + if (mScanCounts.get(remoteId) == null) {mScanCounts.put(remoteId, 0);} + int count = mScanCounts.get(remoteId); + mScanCounts.put(remoteId, count+1); + return count; + } + + private ScanCallback getScanCallback() + { + if(scanCallback == null) { + + scanCallback = new ScanCallback() + { + @Override + @SuppressWarnings("unchecked") // type safety uses bluetooth_msgs.dart + public void onScanResult(int callbackType, ScanResult result) + { + log(LogLevel.VERBOSE, "onScanResult"); + + super.onScanResult(callbackType, result); + + BluetoothDevice device = result.getDevice(); + String remoteId = device.getAddress(); + ScanRecord scanRecord = result.getScanRecord(); + String advHex = scanRecord != null ? bytesToHex(scanRecord.getBytes()) : ""; + + // filter duplicates + if (((boolean) mScanFilters.get("continuous_updates")) == false) { + boolean isDuplicate = mAdvSeen.containsKey(remoteId) && mAdvSeen.get(remoteId).equals(advHex); + mAdvSeen.put(remoteId, advHex); // remember + if (isDuplicate) { + return; + } + } + + // filter keywords + String name = scanRecord != null ? scanRecord.getDeviceName() : ""; + List keywords = (List) mScanFilters.get("with_keywords"); + if (filterKeywords(keywords, name) == false) { + return; + } + + // filter divisor + if (((boolean) mScanFilters.get("continuous_updates")) != false) { + int count = scanCountIncrement(remoteId); + int divisor = (int) mScanFilters.get("continuous_divisor"); + if ((count % divisor) != 0) { + return; + } + } + + // see BmScanResponse + HashMap response = new HashMap<>(); + response.put("advertisements", Arrays.asList(bmScanAdvertisement(device, result))); + + invokeMethodUIThread("OnScanResponse", response); + } + + @Override + public void onBatchScanResults(List results) + { + super.onBatchScanResults(results); + } + + @Override + public void onScanFailed(int errorCode) + { + log(LogLevel.ERROR, "onScanFailed: " + scanFailedString(errorCode)); + + super.onScanFailed(errorCode); + + // see BmScanResponse + HashMap response = new HashMap<>(); + response.put("advertisements", new ArrayList<>()); + response.put("success", 0); + response.put("error_code", errorCode); + response.put("error_string", scanFailedString(errorCode)); + + invokeMethodUIThread("OnScanResponse", response); + } + }; + } + return scanCallback; + } + + ///////////////////////////////////////////////////////////////////////////// + // ██████ █████ ████████ ████████ + // ██ ██ ██ ██ ██ + // ██ ███ ███████ ██ ██ + // ██ ██ ██ ██ ██ ██ + // ██████ ██ ██ ██ ██ + // + // ██████ █████ ██ ██ ██████ █████ ██████ ██ ██ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ███████ ██ ██ ██████ ███████ ██ █████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██████ ██ ██ ███████ ███████ ██████ ██ ██ ██████ ██ ██ + + private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() + { + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) + { + try { + // Prevent callback thread & method call thread from writing to + // mConnectedDevices & mCurrentlyConnectingDevices concurrently. + acquireMutex(mMethodCallMutex); + + log(LogLevel.DEBUG, "onConnectionStateChange:" + connectionStateString(newState)); + log(LogLevel.DEBUG, " status: " + hciStatusString(status)); + + // android never uses this callback with enums values of CONNECTING or DISCONNECTING, + // (theyre only used for gatt.getConnectionState()), but just to be + // future proof, explicitly ignore anything else. iOS & macOS is the same way. + if(newState != BluetoothProfile.STATE_CONNECTED && + newState != BluetoothProfile.STATE_DISCONNECTED) { + return; + } + + String remoteId = gatt.getDevice().getAddress(); + + // edge case. see function for details + if (handleUnexpectedConnectionEvents(gatt, newState, remoteId)) { + return; + } + + // connected? + if(newState == BluetoothProfile.STATE_CONNECTED) { + // add to connected devices + BluetoothGatt replaced = mConnectedDevices.put(remoteId, gatt); + + // Offband #694: an overwrite here orphans the replaced handle. + // Nothing else holds a reference, so it can never be closed and + // it keeps the link (and a GATT client slot) until the process + // dies. Close it before it is lost. + if (replaced != null && replaced != gatt) { + log(LogLevel.WARNING, "closing replaced gatt handle: " + remoteId); + try { replaced.close(); } catch (Exception e) { /* best effort */ } + } + + // remove from currently connecting devices + mCurrentlyConnectingDevices.remove(remoteId); + + // default minimum mtu + mMtu.put(remoteId, 23); + } + + // disconnected? + if(newState == BluetoothProfile.STATE_DISCONNECTED) { + + // remove from connected devices + mConnectedDevices.remove(remoteId); + + // remove from currently connecting devices + mCurrentlyConnectingDevices.remove(remoteId); + + // remove from currently bonding devices + mBondingDevices.remove(remoteId); + + // remove from cached PINs + mBondingPins.remove(remoteId); + + // we cannot call 'close' for autoconnected devices + // because it prevents autoconnect from working + if (mAutoConnected.containsKey(remoteId)) { + log(LogLevel.DEBUG, "autoconnect is true. skipping gatt.close()"); + } else { + // it is important to close after disconnection, otherwise we will + // quickly run out of bluetooth resources, preventing new connections + gatt.close(); + } + } + + // see: BmConnectionStateResponse + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + response.put("connection_state", bmConnectionStateEnum(newState)); + response.put("disconnect_reason_code", status); + response.put("disconnect_reason_string", hciStatusString(status)); + + invokeMethodUIThread("OnConnectionStateChanged", response); + } finally { + mMethodCallMutex.release(); + } + } + + // Android has an annoying edge case. If disconnect is called right as the connection is being + // established, Android sometimes ignores the request to disconnect and completes the connection + // anyway. To handle this case, we make sure the device is still in our currently connecting + // devices map, otherwise kill the connection since the user was not expecting it to connect. + private boolean handleUnexpectedConnectionEvents(BluetoothGatt gatt, int newState, String remoteId) + { + boolean unexpectedEvent = false; + if (newState == BluetoothProfile.STATE_CONNECTED) { + if (mCurrentlyConnectingDevices.get(remoteId) == null && mAutoConnected.get(remoteId) == null) { + log(LogLevel.DEBUG, "[unexpected connection] disconnecting now"); + + // this is an unexpected connection + unexpectedEvent = true; + + // remove from connected devices + mConnectedDevices.remove(remoteId); + + // remove from currently bonding devices + mBondingDevices.remove(remoteId); + + // remove from cached PINs + mBondingPins.remove(remoteId); + + // disconnect and close the connection straight away + gatt.disconnect(); + gatt.close(); + } + + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + + if (mCurrentlyConnectingDevices.get(remoteId) == null && + mConnectedDevices.get(remoteId) == null && + mAutoConnected.get(remoteId) == null) { + + log(LogLevel.DEBUG, "[unexpected connection] disconnect complete"); + + // we have no record of this device, mark this is an unexpected event + unexpectedEvent = true; + + // remove from currently bonding devices + mBondingDevices.remove(remoteId); + + // remove from cached PINs + mBondingPins.remove(remoteId); + + // close the connection + gatt.close(); + } + } + return unexpectedEvent; + } + + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onServicesDiscovered:"); + log(level, " count: " + gatt.getServices().size()); + log(level, " status: " + status + gattErrorString(status)); + + List services = new ArrayList(); + for(BluetoothGattService s : gatt.getServices()) { + services.add(bmBluetoothService(gatt.getDevice(), s, null, gatt)); + for(BluetoothGattService s2 : s.getIncludedServices()) { + services.add(bmBluetoothService(gatt.getDevice(), s2, s, gatt)); + } + } + + // see: BmDiscoverServicesResult + HashMap response = new HashMap<>(); + response.put("remote_id", gatt.getDevice().getAddress()); + response.put("services", services); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnDiscoveredServices", response); + } + + // called for both notifications & reads + public void onCharacteristicReceived(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status) + { + // https://www.bluetooth.com/wp-content/uploads/Files/Specification/Assigned_Numbers.html + + // Generic Attribute service 0x1801 + if (uuidStr(characteristic.getService().getUuid()).equals("1801")) { + + // Service Changed 0x2A05 + if (uuidStr(characteristic.getUuid()).toUpperCase().equals("2A05")) { + HashMap response = bmBluetoothDevice(gatt.getDevice()); + invokeMethodUIThread("OnServicesReset", response); + } + } + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, characteristic); + + // see: BmCharacteristicData + HashMap response = new HashMap<>(); + response.put("remote_id", gatt.getDevice().getAddress()); + if (primaryService != null) { + response.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + response.put("service_uuid", uuidStr(characteristic.getService().getUuid())); + response.put("characteristic_uuid", uuidStr(characteristic.getUuid())); + response.put("instance_id", getInstanceId(characteristic)); + response.put("value", value); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnCharacteristicReceived", response); + } + + @Override + @TargetApi(33) // newer function with byte[] value argument + public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) + { + // this callback is only for notifications & indications + LogLevel level = LogLevel.DEBUG; + log(level, "onCharacteristicChanged:"); + log(level, " chr: " + uuidStr(characteristic.getUuid())); + onCharacteristicReceived(gatt, characteristic, value, BluetoothGatt.GATT_SUCCESS); + } + + @Override + @TargetApi(33) // newer function with byte[] value argument + public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status) + { + // this callback is only for explicit characteristic reads + LogLevel level = status == BluetoothGatt.GATT_SUCCESS ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onCharacteristicRead:"); + log(level, " chr: " + uuidStr(characteristic.getUuid())); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + log(level, " instanceId: " + getInstanceId(characteristic)); + onCharacteristicReceived(gatt, characteristic, value, status); + } + + @Override + public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) + { + LogLevel level = status == BluetoothGatt.GATT_SUCCESS ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onCharacteristicWrite:"); + log(level, " chr: " + uuidStr(characteristic.getUuid())); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + + // For "writeWithResponse", onCharacteristicWrite is called after the remote sends back a write response. + // For "writeWithoutResponse", onCharacteristicWrite is called as long as there is still space left + // in android's internal buffer. When the buffer is full, it delays calling onCharacteristicWrite + // until there is at least ~50% free space again. + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, characteristic); + + // for convenience + String remoteId = gatt.getDevice().getAddress(); + String primaryServiceUuid = primaryService != null ? uuidStr(primaryService.getUuid()) : ""; + String serviceUuid = uuidStr(characteristic.getService().getUuid()); + String characteristicUuid = uuidStr(characteristic.getUuid()); + Integer instanceId = getInstanceId(characteristic); + + // what data did we write? + String key = remoteId + ":" + primaryServiceUuid + ":" + serviceUuid + ":" + + characteristicUuid + ":" + instanceId; + byte[] value = mWriteChr.remove(key); + if (value == null) value = new byte[0]; + + // see: BmCharacteristicData + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + if (primaryService != null) { + response.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + response.put("service_uuid", serviceUuid); + response.put("characteristic_uuid", characteristicUuid); + response.put("instance_id", instanceId); + response.put("value", value); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnCharacteristicWritten", response); + } + + @Override + @TargetApi(33) // newer function, passes byte[] value + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status, byte[] value) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onDescriptorRead:"); + log(level, " chr: " + uuidStr(descriptor.getCharacteristic().getUuid())); + log(level, " desc: " + uuidStr(descriptor.getUuid())); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, descriptor.getCharacteristic()); + + // see: BmDescriptorData + HashMap response = new HashMap<>(); + response.put("remote_id", gatt.getDevice().getAddress()); + if (primaryService != null) { + response.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + response.put("service_uuid", uuidStr(descriptor.getCharacteristic().getService().getUuid())); + response.put("characteristic_uuid", uuidStr(descriptor.getCharacteristic().getUuid())); + response.put("descriptor_uuid", uuidStr(descriptor.getUuid())); + response.put("instance_id", getInstanceId(descriptor.getCharacteristic())); + response.put("value", value); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnDescriptorRead", response); + } + + @Override + public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onDescriptorWrite:"); + log(level, " chr: " + uuidStr(descriptor.getCharacteristic().getUuid())); + log(level, " desc: " + uuidStr(descriptor.getUuid())); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, descriptor.getCharacteristic()); + + // for convenience + String remoteId = gatt.getDevice().getAddress(); + String primaryServiceUuid = primaryService != null ? uuidStr(primaryService.getUuid()) : ""; + String serviceUuid = uuidStr(descriptor.getCharacteristic().getService().getUuid()); + String characteristicUuid = uuidStr(descriptor.getCharacteristic().getUuid()); + Integer instanceId = getInstanceId(descriptor.getCharacteristic()); + String descriptorUuid = uuidStr(descriptor.getUuid()); + + // what data did we write? + String key = remoteId + ":" + primaryServiceUuid + ":" + serviceUuid + ":" + + characteristicUuid + ":" + instanceId + ":" + descriptorUuid; + byte[] value = mWriteDesc.remove(key); + if (value == null) value = new byte[0]; + + // see: BmDescriptorData + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + if (primaryService != null) { + response.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + response.put("service_uuid", serviceUuid); + response.put("characteristic_uuid", characteristicUuid); + response.put("descriptor_uuid", descriptorUuid); + response.put("instance_id", getInstanceId(descriptor.getCharacteristic())); + response.put("value", value); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnDescriptorWritten", response); + } + + @Override + public void onReliableWriteCompleted(BluetoothGatt gatt, int status) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onReliableWriteCompleted:"); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + } + + @Override + public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onReadRemoteRssi:"); + log(level, " rssi: " + rssi); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + + // see: BmReadRssiResult + HashMap response = new HashMap<>(); + response.put("remote_id", gatt.getDevice().getAddress()); + response.put("rssi", rssi); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnReadRssi", response); + } + + @Override + public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) + { + LogLevel level = status == 0 ? LogLevel.DEBUG : LogLevel.ERROR; + log(level, "onMtuChanged:"); + log(level, " mtu: " + mtu ); + log(level, " status: " + gattErrorString(status) + " (" + status + ")"); + + String remoteId = gatt.getDevice().getAddress(); + + // remember mtu + mMtu.put(remoteId, mtu); + + // see: BmMtuChangedResponse + HashMap response = new HashMap<>(); + response.put("remote_id", remoteId); + response.put("mtu", mtu); + response.put("success", status == BluetoothGatt.GATT_SUCCESS ? 1 : 0); + response.put("error_code", status); + response.put("error_string", gattErrorString(status)); + + invokeMethodUIThread("OnMtuChanged", response); + } + + @Override + @SuppressWarnings("deprecation") // needed for android 12 & lower compatability + public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) + { + // getValue() was deprecated in API level 33 because the function makes it look like + // you could always call getValue on a characteristic. But in reality, getValue() + // only works after a *read* has been made, not a *write*. + this.onCharacteristicChanged(gatt, characteristic, characteristic.getValue()); + } + + @Override + @SuppressWarnings("deprecation") // needed for android 12 & lower compatability + public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) + { + // getValue() was deprecated in API level 33 because the function makes it look like + // you could always call getValue on a characteristic. But in reality, getValue() + // only works after a *read* has been made, not a *write*. + this.onCharacteristicRead(gatt, characteristic, characteristic.getValue(), status); + } + + @Override + @SuppressWarnings("deprecation") // needed for android 12 & lower compatability + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) + { + // getValue() was deprecated in API level 33 because the api makes it look like + // you could always call getValue on a descriptor. But in reality, getValue() + // only works after a *read* has been made, not a *write*. + this.onDescriptorRead(gatt, descriptor, status, descriptor.getValue()); + } + + }; // BluetoothGattCallback + + ////////////////////////////////////////////////////////////////////// + // ███ ███ ███████ ██████ + // ████ ████ ██ ██ + // ██ ████ ██ ███████ ██ ███ + // ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ██████ + // + // ██ ██ ███████ ██ ██████ ███████ ██████ ███████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ███████ █████ ██ ██████ █████ ██████ ███████ + // ██ ██ ██ ██ ██ ██ ██ ██ ██ + // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████ + + HashMap bmScanAdvertisement(BluetoothDevice device, ScanResult result) { + + int min = Integer.MIN_VALUE; + + ScanRecord adv = result.getScanRecord(); + + boolean connectable; + if (Build.VERSION.SDK_INT >= 26) { // Android 8.0, August 2017 + connectable = result.isConnectable(); + } else { + // Prior to Android 8.0, it is not possible to get if connectable. + // Previously, we used to check `adv.getAdvertiseFlags() & 0x2` but that + // returns if the device wants to be *discoverable*, which is not the same thing. + connectable = true; + } + + String advName = adv != null ? adv.getDeviceName() : null; + int txPower = adv != null ? adv.getTxPowerLevel() : min; + int appearance = adv != null ? getAppearanceFromScanRecord(adv) : 0; + byte[] rawMsd = adv != null ? getManufacturerSpecificData(adv) : null; + List serviceUuids = adv != null ? adv.getServiceUuids() : null; + Map serviceData = adv != null ? adv.getServiceData() : null; + + // Manufacturer Specific Data + HashMap manufDataB = new HashMap<>(); + if (rawMsd != null && rawMsd.length >= 2) { + // manufacturer ID uses little-endian order. + int manufacturerId = (rawMsd[0] & 0xFF) | ((rawMsd[1] & 0xFF) << 8); + + // payload + int payloadLen = rawMsd.length - 2; + byte[] payload = new byte[payloadLen]; + System.arraycopy(rawMsd, 2, payload, 0, payloadLen); + + // add to array + manufDataB.put(manufacturerId, payload); + } + + // Service Data + HashMap serviceDataB = new HashMap<>(); + if (serviceData != null) { + for (Map.Entry entry : serviceData.entrySet()) { + ParcelUuid key = entry.getKey(); + byte[] value = entry.getValue(); + serviceDataB.put(uuidStr(key.getUuid()), value); + } + } + + // Service UUIDs + List serviceUuidsB = new ArrayList<>(); + if (serviceUuids != null) { + for (ParcelUuid s : serviceUuids) { + serviceUuidsB.add(uuidStr(s.getUuid())); + } + } + + // See: BmScanAdvertisement + // perf: only add keys if they exists + HashMap map = new HashMap<>(); + if (device.getAddress() != null) {map.put("remote_id", device.getAddress());}; + if (device.getName() != null) {map.put("platform_name", device.getName());} + if (connectable) {map.put("connectable", 1);} + if (advName != null) {map.put("adv_name", advName);} + if (txPower != min) {map.put("tx_power_level", txPower);} + if (appearance != 0) {map.put("appearance", appearance);} + if (manufDataB.size() != 0) {map.put("manufacturer_data", manufDataB);} + if (serviceData != null) {map.put("service_data", serviceDataB);} + if (serviceUuids != null) {map.put("service_uuids", serviceUuidsB);} + if (result.getRssi() != 0) {map.put("rssi", result.getRssi());}; + return map; + } + + // See: BmBluetoothDevice + HashMap bmBluetoothDevice(BluetoothDevice device) { + HashMap map = new HashMap<>(); + map.put("remote_id", device.getAddress()); + map.put("platform_name", device.getName()); + return map; + } + + HashMap bmBluetoothService( + BluetoothDevice device, + BluetoothGattService service, + BluetoothGattService primaryService, + BluetoothGatt gatt) + { + + List characteristics = new ArrayList(); + for(BluetoothGattCharacteristic c : service.getCharacteristics()) { + characteristics.add(bmBluetoothCharacteristic(device, c, gatt)); + } + + // See: BmBluetoothService + HashMap map = new HashMap<>(); + map.put("remote_id", device.getAddress()); + if (primaryService != null) { + map.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + map.put("service_uuid", uuidStr(service.getUuid())); + map.put("characteristics", characteristics); + return map; + } + + HashMap bmBluetoothCharacteristic(BluetoothDevice device, BluetoothGattCharacteristic characteristic, BluetoothGatt gatt) { + + List descriptors = new ArrayList(); + for(BluetoothGattDescriptor d : characteristic.getDescriptors()) { + descriptors.add(bmBluetoothDescriptor(device, d, gatt)); + } + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, characteristic); + + // See: BmBluetoothCharacteristic + HashMap map = new HashMap<>(); + map.put("remote_id", device.getAddress()); + if (primaryService != null) { + map.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + map.put("service_uuid", uuidStr(characteristic.getService().getUuid())); + map.put("characteristic_uuid", uuidStr(characteristic.getUuid())); + map.put("instance_id", getInstanceId(characteristic)); + map.put("descriptors", descriptors); + map.put("properties", bmCharacteristicProperties(characteristic.getProperties())); + return map; + } + + // See: BmBluetoothDescriptor + HashMap bmBluetoothDescriptor(BluetoothDevice device, BluetoothGattDescriptor descriptor, BluetoothGatt gatt) { + + // has associated primary service? + BluetoothGattService primaryService = getPrimaryService(gatt, descriptor.getCharacteristic()); + + HashMap map = new HashMap<>(); + map.put("remote_id", device.getAddress()); + if (primaryService != null) { + map.put("primary_service_uuid", uuidStr(primaryService.getUuid())); + } + map.put("service_uuid", uuidStr(descriptor.getCharacteristic().getService().getUuid())); + map.put("descriptor_uuid", uuidStr(descriptor.getUuid())); + map.put("characteristic_uuid", uuidStr(descriptor.getCharacteristic().getUuid())); + map.put("instance_id", getInstanceId(descriptor.getCharacteristic())); + return map; + } + + // See: BmCharacteristicProperties + HashMap bmCharacteristicProperties(int properties) { + HashMap props = new HashMap<>(); + props.put("broadcast", (properties & 1) != 0 ? 1 : 0); + props.put("read", (properties & 2) != 0 ? 1 : 0); + props.put("write_without_response", (properties & 4) != 0 ? 1 : 0); + props.put("write", (properties & 8) != 0 ? 1 : 0); + props.put("notify", (properties & 16) != 0 ? 1 : 0); + props.put("indicate", (properties & 32) != 0 ? 1 : 0); + props.put("authenticated_signed_writes", (properties & 64) != 0 ? 1 : 0); + props.put("extended_properties", (properties & 128) != 0 ? 1 : 0); + props.put("notify_encryption_required", (properties & 256) != 0 ? 1 : 0); + props.put("indicate_encryption_required", (properties & 512) != 0 ? 1 : 0); + return props; + } + + // See: BmConnectionStateEnum + static int bmConnectionStateEnum(int cs) { + switch (cs) { + case BluetoothProfile.STATE_DISCONNECTED: return 0; + case BluetoothProfile.STATE_CONNECTED: return 1; + default: return 0; + } + } + + // See: BmAdapterStateEnum + static int bmAdapterStateEnum(int as) { + switch (as) { + case BluetoothAdapter.STATE_OFF: return 6; + case BluetoothAdapter.STATE_ON: return 4; + case BluetoothAdapter.STATE_TURNING_OFF: return 5; + case BluetoothAdapter.STATE_TURNING_ON: return 3; + default: return 0; + } + } + + // See: BmBondStateEnum + static int bmBondStateEnum(int bs) { + switch (bs) { + case BluetoothDevice.BOND_NONE: return 0; + case BluetoothDevice.BOND_BONDING: return 1; + case BluetoothDevice.BOND_BONDED: return 2; + default: return 0; + } + } + + // See: BmConnectionPriority + static int bmConnectionPriorityParse(int value) { + switch(value) { + case 0: return BluetoothGatt.CONNECTION_PRIORITY_BALANCED; + case 1: return BluetoothGatt.CONNECTION_PRIORITY_HIGH; + case 2: return BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER; + default: return BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER; + } + } + + static BluetoothGattService getPrimaryService(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { + + BluetoothGattService service = characteristic.getService(); + + // is this *already* a primary service? + if(service.getType() == BluetoothGattService.SERVICE_TYPE_PRIMARY) { + return null; + } + + // Otherwise, iterate included services until we find the primary service + for(BluetoothGattService primary : gatt.getServices()) { + for(BluetoothGattService secondary : primary.getIncludedServices()) { + if(secondary.getUuid().equals(service.getUuid())) { + return primary; + } + } + } + + return null; + } + + ////////////////////////////////////////// + // ██ ██ ████████ ██ ██ ███████ + // ██ ██ ██ ██ ██ ██ + // ██ ██ ██ ██ ██ ███████ + // ██ ██ ██ ██ ██ ██ + // ██████ ██ ██ ███████ ███████ + + private void log(LogLevel level, String message) + { + if(level.ordinal() > logLevel.ordinal()) { + return; + } + switch(level) { + case DEBUG: + Log.d(TAG, "[FBP] " + message); + break; + case WARNING: + Log.w(TAG, "[FBP] " + message); + break; + case ERROR: + Log.e(TAG, "[FBP] " + message); + break; + default: + Log.d(TAG, "[FBP] " + message); + break; + } + } + + private void invokeMethodUIThread(final String method, HashMap data) + { + new Handler(Looper.getMainLooper()).post(() -> { + //Could already be teared down at this moment + if (methodChannel != null) { + methodChannel.invokeMethod(method, data); + } else { + log(LogLevel.WARNING, "invokeMethodUIThread: tried to call method on closed channel: " + method); + } + }); + } + + private boolean isAdapterOn() + { + // get adapterState, if we have permission + try { + return mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON; + } catch (Exception e) { + return false; + } + } + + private static String bytesToHex(byte[] bytes) { + if (bytes == null) { + return ""; + } + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } + + private static String connectionStateString(int cs) { + switch (cs) { + case BluetoothProfile.STATE_DISCONNECTED: return "disconnected"; + case BluetoothProfile.STATE_CONNECTING: return "connecting"; + case BluetoothProfile.STATE_CONNECTED: return "connected"; + case BluetoothProfile.STATE_DISCONNECTING: return "disconnecting"; + default: return "UNKNOWN_CONNECTION_STATE (" + cs + ")"; + } + } + + private static String adapterStateString(int as) { + switch (as) { + case BluetoothAdapter.STATE_OFF: return "off"; + case BluetoothAdapter.STATE_ON: return "on"; + case BluetoothAdapter.STATE_TURNING_OFF: return "turningOff"; + case BluetoothAdapter.STATE_TURNING_ON: return "turningOn"; + default: return "UNKNOWN_ADAPTER_STATE (" + as + ")"; + } + } + + private static String bondStateString(int bs) { + switch (bs) { + case BluetoothDevice.BOND_BONDING: return "bonding"; + case BluetoothDevice.BOND_BONDED: return "bonded"; + case BluetoothDevice.BOND_NONE: return "bond-none"; + default: return "UNKNOWN_BOND_STATE (" + bs + ")"; + } + } + + // Defined in the Bluetooth Standard + private static String gattErrorString(int value) { + switch(value) { + case BluetoothGatt.GATT_SUCCESS : return "GATT_SUCCESS"; // 0 + case 0x01 : return "GATT_INVALID_HANDLE"; // 1 + case BluetoothGatt.GATT_READ_NOT_PERMITTED : return "GATT_READ_NOT_PERMITTED"; // 2 + case BluetoothGatt.GATT_WRITE_NOT_PERMITTED : return "GATT_WRITE_NOT_PERMITTED"; // 3 + case 0x04 : return "GATT_INVALID_PDU"; // 4 + case BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION : return "GATT_INSUFFICIENT_AUTHENTICATION"; // 5 + case BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED : return "GATT_REQUEST_NOT_SUPPORTED"; // 6 + case BluetoothGatt.GATT_INVALID_OFFSET : return "GATT_INVALID_OFFSET"; // 7 + case BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION : return "GATT_INSUFFICIENT_AUTHORIZATION"; // 8 + case 0x09 : return "GATT_PREPARE_QUEUE_FULL"; // 9 + case 0x0a : return "GATT_ATTR_NOT_FOUND"; // 10 + case 0x0b : return "GATT_ATTR_NOT_LONG"; // 11 + case 0x0c : return "GATT_INSUFFICIENT_KEY_SIZE"; // 12 + case BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH : return "GATT_INVALID_ATTRIBUTE_LENGTH"; // 13 + case 0x0e : return "GATT_UNLIKELY"; // 14 + case BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION : return "GATT_INSUFFICIENT_ENCRYPTION"; // 15 + case 0x10 : return "GATT_UNSUPPORTED_GROUP"; // 16 + case 0x11 : return "GATT_INSUFFICIENT_RESOURCES"; // 17 + case 0x80 : return "GATT_NO_RESOURCES"; // 128 + case 0x81 : return "GATT_INTERNAL_ERROR"; // 129 + case 0x82 : return "GATT_WRONG_STATE"; // 130 + case 0x83 : return "GATT_DB_FULL"; // 131 + case 0x84 : return "GATT_BUSY"; // 132 + case 0x85 : return "GATT_ERROR"; // 133 + case 0x86 : return "GATT_CMD_STARTED"; // 134 + case 0x87 : return "GATT_ILLEGAL_PARAMETER"; // 135 + case 0x88 : return "GATT_PENDING"; // 136 + case 0x89 : return "GATT_AUTH_FAIL"; // 137 + case 0x8a : return "GATT_MORE"; // 138 + case 0x8b : return "GATT_INVALID_CFG"; // 139 + case 0x8c : return "GATT_SERVICE_STARTED"; // 140 + case 0x8d : return "GATT_ENCRYPTED_NO_MITM"; // 141 + case 0x8e : return "GATT_NOT_ENCRYPTED"; // 142 + case BluetoothGatt.GATT_CONNECTION_CONGESTED : return "GATT_CONNECTION_CONGESTED"; // 143 + case BluetoothGatt.GATT_FAILURE : return "GATT_FAILURE"; // 257 + default: return "UNKNOWN_GATT_ERROR (" + value + ")"; + } + } + + private static String bluetoothStatusString(int value) { + switch(value) { + case BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ALLOWED : return "ERROR_BLUETOOTH_NOT_ALLOWED"; + case BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED : return "ERROR_BLUETOOTH_NOT_ENABLED"; + case BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED : return "ERROR_DEVICE_NOT_BONDED"; + case BluetoothStatusCodes.ERROR_GATT_WRITE_NOT_ALLOWED : return "ERROR_GATT_WRITE_NOT_ALLOWED"; + case BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY : return "ERROR_GATT_WRITE_REQUEST_BUSY"; + case BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION : return "ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION"; + case BluetoothStatusCodes.ERROR_PROFILE_SERVICE_NOT_BOUND : return "ERROR_PROFILE_SERVICE_NOT_BOUND"; + case BluetoothStatusCodes.ERROR_UNKNOWN : return "ERROR_UNKNOWN"; + //case BluetoothStatusCodes.FEATURE_NOT_CONFIGURED : return "FEATURE_NOT_CONFIGURED"; + case BluetoothStatusCodes.FEATURE_NOT_SUPPORTED : return "FEATURE_NOT_SUPPORTED"; + case BluetoothStatusCodes.FEATURE_SUPPORTED : return "FEATURE_SUPPORTED"; + case BluetoothStatusCodes.SUCCESS : return "SUCCESS"; + default: return "UNKNOWN_BLE_ERROR (" + value + ")"; + } + } + + private static String scanFailedString(int value) { + switch(value) { + case ScanCallback.SCAN_FAILED_ALREADY_STARTED : return "SCAN_FAILED_ALREADY_STARTED"; + case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED: return "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"; + case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED : return "SCAN_FAILED_FEATURE_UNSUPPORTED"; + case ScanCallback.SCAN_FAILED_INTERNAL_ERROR : return "SCAN_FAILED_INTERNAL_ERROR"; + case ScanCallback.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES : return "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES"; + case ScanCallback.SCAN_FAILED_SCANNING_TOO_FREQUENTLY : return "SCAN_FAILED_SCANNING_TOO_FREQUENTLY"; + default: return "UNKNOWN_SCAN_ERROR (" + value + ")"; + } + } + + + // Defined in the Bluetooth Standard, Volume 1, Part F, 1.3 HCI Error Code, pages 364-377. + // See https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=478726, + // For Android specific errors, see https://developer.android.com/reference/android/bluetooth/BluetoothGatt#constants_1 + private static String hciStatusString(int value) { + switch(value) { + case 0x00: return "SUCCESS"; + case 0x01: return "UNKNOWN_COMMAND"; // The controller does not understand the HCI Command Packet OpCode that the Host sent. + case 0x02: return "UNKNOWN_CONNECTION_IDENTIFIER"; // The connection identifier used is unknown + case 0x03: return "HARDWARE_FAILURE"; // A hardware failure has occurred + case 0x04: return "PAGE_TIMEOUT"; // a page timed out because of the Page Timeout configuration parameter. + case 0x05: return "AUTHENTICATION_FAILURE"; // Pairing or authentication failed. This could be due to an incorrect PIN or Link Key. + case 0x06: return "PIN_OR_KEY_MISSING"; // Pairing failed because of a missing PIN + case 0x07: return "MEMORY_FULL"; // The Controller has run out of memory to store new parameters. + case 0x08: return "LINK_SUPERVISION_TIMEOUT"; // The link supervision timeout has expired for a given connection. + case 0x09: return "CONNECTION_LIMIT_EXCEEDED"; // The Controller is already at its limit of the number of connections it can support. + case 0x0A: return "MAX_NUM_OF_CONNECTIONS_EXCEEDED"; // The Controller has reached the limit of connections + case 0x0B: return "CONNECTION_ALREADY_EXISTS"; // A connection to this device already exists + case 0x0C: return "COMMAND_DISALLOWED"; // The command requested cannot be executed by the Controller at this time. + case 0x0D: return "CONNECTION_REJECTED_LIMITED_RESOURCES"; // A connection was rejected due to limited resources. + case 0x0E: return "CONNECTION_REJECTED_SECURITY_REASONS"; // A connection was rejected due to security, e.g. aauth or pairing. + case 0x0F: return "CONNECTION_REJECTED_UNACCEPTABLE_MAC_ADDRESS"; // connection rejected, this device does not accept the BD_ADDR + case 0x10: return "CONNECTION_ACCEPT_TIMEOUT_EXCEEDED"; // Connection Accept Timeout exceeded for this connection attempt. + case 0x11: return "UNSUPPORTED_PARAMETER_VALUE"; // A feature or parameter value in the HCI command is not supported. + case 0x12: return "INVALID_COMMAND_PARAMETERS"; // At least one of the HCI command parameters is invalid. + case 0x13: return "REMOTE_USER_TERMINATED_CONNECTION"; // The user on the remote device terminated the connection. + case 0x14: return "REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES"; // remote device terminated connection due to low resources. + case 0x15: return "REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF"; // The remote device terminated the connection due to power off + case 0x16: return "CONNECTION_TERMINATED_BY_LOCAL_HOST"; // The local device terminated the connection. + case 0x17: return "REPEATED_ATTEMPTS"; // The Controller is disallowing auth because of too quick attempts. + case 0x18: return "PAIRING_NOT_ALLOWED"; // The device does not allow pairing + case 0x19: return "UNKNOWN_LMP_PDU"; // The Controller has received an unknown LMP OpCode. + case 0x1A: return "UNSUPPORTED_REMOTE_FEATURE"; // The remote device does not support feature for the issued command or LMP PDU. + case 0x1B: return "SCO_OFFSET_REJECTED"; // The offset requested in the LMP_SCO_link_req PDU has been rejected. + case 0x1C: return "SCO_INTERVAL_REJECTED"; // The interval requested in the LMP_SCO_link_req PDU has been rejected. + case 0x1D: return "SCO_AIR_MODE_REJECTED"; // The air mode requested in the LMP_SCO_link_req PDU has been rejected. + case 0x1E: return "INVALID_LMP_OR_LL_PARAMETERS"; // Some LMP PDU / LL Control PDU parameters were invalid. + case 0x1F: return "UNSPECIFIED"; // No other error code specified is appropriate to use + case 0x20: return "UNSUPPORTED_LMP_OR_LL_PARAMETER_VALUE"; // An LMP PDU or an LL Control PDU contains a value that is not supported + case 0x21: return "ROLE_CHANGE_NOT_ALLOWED"; // a Controller will not allow a role change at this time. + case 0x22: return "LMP_OR_LL_RESPONSE_TIMEOUT"; // An LMP transaction failed to respond within the LMP response timeout + case 0x23: return "LMP_OR_LL_ERROR_TRANS_COLLISION"; // An LMP transaction or LL procedure has collided with the same transaction + case 0x24: return "LMP_PDU_NOT_ALLOWED"; // A Controller sent an LMP PDU with an OpCode that was not allowed. + case 0x25: return "ENCRYPTION_MODE_NOT_ACCEPTABLE"; // The requested encryption mode is not acceptable at this time. + case 0x26: return "LINK_KEY_CANNOT_BE_EXCHANGED"; // A link key cannot be changed because a fixed unit key is being used. + case 0x27: return "REQUESTED_QOS_NOT_SUPPORTED"; // The requested Quality of Service is not supported. + case 0x28: return "INSTANT_PASSED"; // The LMP PDU or LL PDU instant has already passed + case 0x29: return "PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED"; // It was not possible to pair as a unit key is not supported. + case 0x2A: return "DIFFERENT_TRANSACTION_COLLISION"; // An LMP transaction or LL Procedure collides with an ongoing transaction. + case 0x2B: return "UNDEFINED_0x2B"; // Undefined error code + case 0x2C: return "QOS_UNACCEPTABLE_PARAMETER"; // The quality of service parameters could not be accepted at this time. + case 0x2D: return "QOS_REJECTED"; // The specified quality of service parameters cannot be accepted. negotiation should be terminated + case 0x2E: return "CHANNEL_CLASSIFICATION_NOT_SUPPORTED"; // The Controller cannot perform channel assessment. not supported. + case 0x2F: return "INSUFFICIENT_SECURITY"; // The HCI command or LMP PDU sent is only possible on an encrypted link. + case 0x30: return "PARAMETER_OUT_OF_RANGE"; // A parameter in the HCI command is outside of valid range + case 0x31: return "UNDEFINED_0x31"; // Undefined error + case 0x32: return "ROLE_SWITCH_PENDING"; // A Role Switch is pending, sothe HCI command or LMP PDU is rejected + case 0x33: return "UNDEFINED_0x33"; // Undefined error + case 0x34: return "RESERVED_SLOT_VIOLATION"; // Synchronous negotiation terminated with negotiation state set to Reserved Slot Violation. + case 0x35: return "ROLE_SWITCH_FAILED"; // A role switch was attempted but it failed and the original piconet structure is restored. + case 0x36: return "INQUIRY_RESPONSE_TOO_LARGE"; // The extended inquiry response is too large to fit in packet supported by Controller. + case 0x37: return "SECURE_SIMPLE_PAIRING_NOT_SUPPORTED"; // Host does not support Secure Simple Pairing, but receiving Link Manager does. + case 0x38: return "HOST_BUSY_PAIRING"; // The Host is busy with another pairing operation. The receiving device should retry later. + case 0x39: return "CONNECTION_REJECTED_NO_SUITABLE_CHANNEL"; // Controller could not calculate an appropriate value for Channel selection. + case 0x3A: return "CONTROLLER_BUSY"; // The Controller was busy and unable to process the request. + case 0x3B: return "UNACCEPTABLE_CONNECTION_PARAMETERS"; // The remote device terminated connection, unacceptable connection parameters. + case 0x3C: return "ADVERTISING_TIMEOUT"; // Advertising completed. Or for directed advertising, no connection was created. + case 0x3D: return "CONNECTION_TERMINATED_MIC_FAILURE"; // Connection terminated because Message Integrity Check failed on received packet. + case 0x3E: return "CONNECTION_FAILED_ESTABLISHMENT"; // The LL initiated a connection but the connection has failed to be established. + case 0x3F: return "MAC_CONNECTION_FAILED"; // The MAC of the 802.11 AMP was requested to connect to a peer, but the connection failed. + case 0x40: return "COARSE_CLOCK_ADJUSTMENT_REJECTED"; // The master is unable to make a coarse adjustment to the piconet clock. + case 0x41: return "TYPE0_SUBMAP_NOT_DEFINED"; // The LMP PDU is rejected because the Type 0 submap is not currently defined. + case 0x42: return "UNKNOWN_ADVERTISING_IDENTIFIER"; // A command was sent from the Host but the Advertising or Sync handle does not exist. + case 0x43: return "LIMIT_REACHED"; // The number of operations requested has been reached and has indicated the completion of the activity + case 0x44: return "OPERATION_CANCELLED_BY_HOST"; // A request to the Controller issued by the Host and still pending was successfully canceled. + case 0x45: return "PACKET_TOO_LONG"; // An attempt was made to send or receive a packet that exceeds the maximum allowed packet length. + case 0x85: return "ANDROID_SPECIFIC_ERROR"; // Additional Android specific errors + case 0x8f: return "GATT_CONNECTION_CONGESTED"; // A remote device connection is congested. + case 0x93: return "GATT_CONNECTION_TIMEOUT"; // GATT connection timed out, likely due to the remote device being out of range or not advertising as connectable. + case 0x101: return "FAILURE_REGISTERING_CLIENT"; // max of 30 clients has been reached. + default: return "UNKNOWN_HCI_ERROR (" + value + ")"; + } + } + + + enum LogLevel + { + NONE, // 0 + ERROR, // 1 + WARNING, // 2 + INFO, // 3 + DEBUG, // 4 + VERBOSE // 5 + } +} diff --git a/packages/flutter_blue_plus_android/lib/flutter_blue_plus_android.dart b/packages/flutter_blue_plus_android/lib/flutter_blue_plus_android.dart new file mode 100644 index 00000000..07cdae31 --- /dev/null +++ b/packages/flutter_blue_plus_android/lib/flutter_blue_plus_android.dart @@ -0,0 +1,596 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart'; + +final class FlutterBluePlusAndroid extends FlutterBluePlusPlatform { + @visibleForTesting + final methodChannel = const MethodChannel('flutter_blue_plus/methods'); + + var _didRestart = false; + var _logLevel = LogLevel.none; + var _logColor = true; + + final _onAdapterStateChangedController = + StreamController.broadcast(); + final _onBondStateChangedController = + StreamController.broadcast(); + final _onCharacteristicReceivedController = + StreamController.broadcast(); + final _onCharacteristicWrittenController = + StreamController.broadcast(); + final _onConnectionStateChangedController = + StreamController.broadcast(); + final _onDescriptorReadController = + StreamController.broadcast(); + final _onDescriptorWrittenController = + StreamController.broadcast(); + final _onDetachedFromEngineController = + StreamController.broadcast(); + final _onDiscoveredServicesController = + StreamController.broadcast(); + final _onMtuChangedController = + StreamController.broadcast(); + final _onNameChangedController = StreamController.broadcast(); + final _onReadRssiController = StreamController.broadcast(); + final _onScanResponseController = + StreamController.broadcast(); + final _onServicesResetController = + StreamController.broadcast(); + final _onTurnOnResponseController = + StreamController.broadcast(); + + @override + Stream get onAdapterStateChanged { + return _onAdapterStateChangedController.stream; + } + + @override + Stream get onBondStateChanged { + return _onBondStateChangedController.stream; + } + + @override + Stream get onCharacteristicReceived { + return _onCharacteristicReceivedController.stream; + } + + @override + Stream get onCharacteristicWritten { + return _onCharacteristicWrittenController.stream; + } + + @override + Stream get onConnectionStateChanged { + return _onConnectionStateChangedController.stream; + } + + @override + Stream get onDescriptorRead { + return _onDescriptorReadController.stream; + } + + @override + Stream get onDescriptorWritten { + return _onDescriptorWrittenController.stream; + } + + @override + Stream get onDetachedFromEngine { + return _onDetachedFromEngineController.stream; + } + + @override + Stream get onDiscoveredServices { + return _onDiscoveredServicesController.stream; + } + + @override + Stream get onMtuChanged { + return _onMtuChangedController.stream; + } + + @override + Stream get onNameChanged { + return _onNameChangedController.stream; + } + + @override + Stream get onReadRssi { + return _onReadRssiController.stream; + } + + @override + Stream get onScanResponse { + return _onScanResponseController.stream; + } + + @override + Stream get onServicesReset { + return _onServicesResetController.stream; + } + + @override + Stream get onTurnOnResponse { + return _onTurnOnResponseController.stream; + } + + static void registerWith() { + FlutterBluePlusPlatform.instance = FlutterBluePlusAndroid(); + } + + @override + Future clearGattCache( + BmClearGattCacheRequest request, + ) async { + return await _callAndroidMethod( + 'clearGattCache', + request.remoteId.str, + ) == + true; + } + + @override + Future connect( + BmConnectRequest request, + ) async { + return await _callAndroidMethod( + 'connect', + request.toMap(), + ) == + true; + } + + @override + Future createBond( + BmCreateBondRequest request, + ) async { + return await _callAndroidMethod( + 'createBond', + request.toMap(), + ) == + true; + } + + @override + Future disconnect( + BmDisconnectRequest request, + ) async { + return await _callAndroidMethod( + 'disconnect', + request.remoteId.str, + ) == + true; + } + + @override + Future discoverServices( + BmDiscoverServicesRequest request, + ) async { + return await _callAndroidMethod( + 'discoverServices', + request.remoteId.str, + ) == + true; + } + + @override + Future getAdapterName( + BmBluetoothAdapterNameRequest request, + ) async { + return BmBluetoothAdapterName( + adapterName: await _callAndroidMethod( + 'getAdapterName', + ), + ); + } + + @override + Future getAdapterState( + BmBluetoothAdapterStateRequest request, + ) async { + return BmBluetoothAdapterState.fromMap( + await _callAndroidMethod( + 'getAdapterState', + ), + ); + } + + @override + Future getBondState( + BmBondStateRequest request, + ) async { + return BmBondStateResponse.fromMap( + await _callAndroidMethod( + 'getBondState', + request.remoteId.str, + ), + ); + } + + @override + Future getBondedDevices( + BmBondedDevicesRequest request, + ) async { + return BmDevicesList.fromMap( + await _callAndroidMethod( + 'getBondedDevices', + ), + ); + } + + @override + Future getPhySupport( + PhySupportRequest request, + ) async { + return PhySupport.fromMap( + await _callAndroidMethod( + 'getPhySupport', + ), + ); + } + + @override + Future getSystemDevices( + BmSystemDevicesRequest request, + ) async { + return BmDevicesList.fromMap( + await _callAndroidMethod( + 'getSystemDevices', + ), + ); + } + + @override + Future isSupported( + BmIsSupportedRequest request, + ) async { + return await _callAndroidMethod( + 'isSupported', + ) == + true; + } + + @override + Future readCharacteristic( + BmReadCharacteristicRequest request, + ) async { + return await _callAndroidMethod( + 'readCharacteristic', + request.toMap(), + ) == + true; + } + + @override + Future readDescriptor( + BmReadDescriptorRequest request, + ) async { + return await _callAndroidMethod( + 'readDescriptor', + request.toMap(), + ) == + true; + } + + @override + Future readRssi( + BmReadRssiRequest request, + ) async { + return await _callAndroidMethod( + 'readRssi', + request.remoteId.str, + ) == + true; + } + + @override + Future removeBond( + BmRemoveBondRequest request, + ) async { + return await _callAndroidMethod( + 'removeBond', + request.remoteId.str, + ) == + true; + } + + @override + Future requestConnectionPriority( + BmConnectionPriorityRequest request, + ) async { + return await _callAndroidMethod( + 'requestConnectionPriority', + request.toMap(), + ) == + true; + } + + @override + Future requestMtu( + BmMtuChangeRequest request, + ) async { + return await _callAndroidMethod( + 'requestMtu', + request.toMap(), + ) == + true; + } + + @override + Future setLogLevel( + BmSetLogLevelRequest request, + ) async { + _logLevel = request.logLevel; + _logColor = request.logColor; + + return await _callAndroidMethod( + 'setLogLevel', + request.logLevel.index, + ) == + true; + } + + @override + Future setNotifyValue( + BmSetNotifyValueRequest request, + ) async { + return await _callAndroidMethod( + 'setNotifyValue', + request.toMap(), + ) == + true; + } + + @override + Future setOptions( + BmSetOptionsRequest request, + ) async { + return await _callAndroidMethod( + 'setOptions', + request.toMap(), + ) == + true; + } + + @override + Future setPreferredPhy( + BmPreferredPhy request, + ) async { + return await _callAndroidMethod( + 'setPreferredPhy', + request.toMap(), + ) == + true; + } + + @override + Future startScan( + BmScanSettings request, + ) async { + return await _callAndroidMethod( + 'startScan', + request.toMap(), + ) == + true; + } + + @override + Future stopScan( + BmStopScanRequest request, + ) async { + return await _callAndroidMethod( + 'stopScan', + ) == + true; + } + + @override + Future turnOff( + BmTurnOffRequest request, + ) async { + return await _callAndroidMethod( + 'turnOff', + ) == + true; + } + + @override + Future turnOn( + BmTurnOnRequest request, + ) async { + return await _callAndroidMethod( + 'turnOn', + ) == + true; + } + + @override + Future writeCharacteristic( + BmWriteCharacteristicRequest request, + ) async { + return await _callAndroidMethod( + 'writeCharacteristic', + request.toMap(), + ) == + true; + } + + @override + Future writeDescriptor( + BmWriteDescriptorRequest request, + ) async { + return await _callAndroidMethod( + 'writeDescriptor', + request.toMap(), + ) == + true; + } + + Future _callAndroidMethod( + String method, [ + dynamic arguments, + ]) async { + // restart platform + if (!_didRestart && method != "setLogLevel") { + await _flutterRestart(); + } + + // set platform method handler + methodChannel.setMethodCallHandler(_methodCallHandler); + + // log args + if (_logLevel == LogLevel.verbose) { + var func = '<$method>'; + var args = arguments.toString(); + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + args = _logColor ? '\x1B[1;35m$args\x1B[0m' : args; + FlutterBluePlusPlatform.log('[FBP] $func args: $args'); + } + + // invoke + final out = await methodChannel.invokeMethod(method, arguments); + + // log result + if (_logLevel == LogLevel.verbose) { + var func = '($method)'; + var result = out.toString(); + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result; + FlutterBluePlusPlatform.log('[FBP] $func result: $result'); + } + + return out; + } + + Future _flutterRestart() async { + // wait for all devices to disconnect + if ((await methodChannel.invokeMethod('flutterRestart')) != 0) { + await Future.delayed(Duration(milliseconds: 50)); + while ((await methodChannel.invokeMethod('connectedCount')) != 0) { + await Future.delayed(Duration(milliseconds: 50)); + } + } + _didRestart = true; + } + + Future _methodCallHandler( + MethodCall call, + ) async { + // log result + if (_logLevel == LogLevel.verbose) { + var func = '[[ ${call.method} ]]'; + var result = switch (call.method) { + 'OnDiscoveredServices' => _prettyPrint(call.arguments), + _ => call.arguments.toString(), + }; + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result; + FlutterBluePlusPlatform.log('[FBP] $func result: $result'); + } + + // handle method call + switch (call.method) { + case 'OnAdapterStateChanged': + return _onAdapterStateChangedController.add( + BmBluetoothAdapterState.fromMap( + call.arguments, + ), + ); + case 'OnBondStateChanged': + return _onBondStateChangedController.add( + BmBondStateResponse.fromMap( + call.arguments, + ), + ); + case 'OnCharacteristicReceived': + return _onCharacteristicReceivedController.add( + BmCharacteristicData.fromMap( + call.arguments, + ), + ); + case 'OnCharacteristicWritten': + return _onCharacteristicWrittenController.add( + BmCharacteristicData.fromMap( + call.arguments, + ), + ); + case 'OnConnectionStateChanged': + return _onConnectionStateChangedController.add( + BmConnectionStateResponse.fromMap( + call.arguments, + ), + ); + case 'OnDescriptorRead': + return _onDescriptorReadController.add( + BmDescriptorData.fromMap( + call.arguments, + ), + ); + case 'OnDescriptorWritten': + return _onDescriptorWrittenController.add( + BmDescriptorData.fromMap( + call.arguments, + ), + ); + case 'OnDetachedFromEngine': + return _onDetachedFromEngineController.add( + BmDetachedFromEngineResponse(), + ); + case 'OnDiscoveredServices': + return _onDiscoveredServicesController.add( + BmDiscoverServicesResult.fromMap( + call.arguments, + ), + ); + case 'OnMtuChanged': + return _onMtuChangedController.add( + BmMtuChangedResponse.fromMap( + call.arguments, + ), + ); + case 'OnNameChanged': + return _onNameChangedController.add( + BmNameChanged.fromMap( + call.arguments, + ), + ); + case 'OnReadRssi': + return _onReadRssiController.add( + BmReadRssiResult.fromMap( + call.arguments, + ), + ); + case 'OnScanResponse': + return _onScanResponseController.add( + BmScanResponse.fromMap( + call.arguments, + ), + ); + case 'OnServicesReset': + return _onServicesResetController.add( + BmBluetoothDevice.fromMap( + call.arguments, + ), + ); + case 'OnTurnOnResponse': + return _onTurnOnResponseController.add( + BmTurnOnResponse.fromMap( + call.arguments, + ), + ); + } + } + + String _prettyPrint( + dynamic data, + ) { + if (data is Map || data is List) { + return JsonEncoder.withIndent(' ').convert(data); + } else { + return data.toString(); + } + } +} diff --git a/packages/flutter_blue_plus_android/pubspec.yaml b/packages/flutter_blue_plus_android/pubspec.yaml new file mode 100644 index 00000000..570615b4 --- /dev/null +++ b/packages/flutter_blue_plus_android/pubspec.yaml @@ -0,0 +1,27 @@ +name: flutter_blue_plus_android +description: Android implementation of the flutter_blue_plus plugin. +version: 8.2.2+offband.1 +homepage: https://github.com/chipweinberger/flutter_blue_plus + +environment: + sdk: ^3.0.0 + flutter: '>=3.7.0' + +dependencies: + flutter: + sdk: flutter + flutter_blue_plus_platform_interface: 8.2.2 + +dev_dependencies: + flutter_lints: ^5.0.0 + flutter_test: + sdk: flutter + +flutter: + plugin: + implements: flutter_blue_plus + platforms: + android: + package: com.lib.flutter_blue_plus + pluginClass: FlutterBluePlusPlugin + dartPluginClass: FlutterBluePlusAndroid diff --git a/packages/flutter_blue_plus_linux/CHANGELOG.md b/packages/flutter_blue_plus_linux/CHANGELOG.md new file mode 100644 index 00000000..e20fdea3 --- /dev/null +++ b/packages/flutter_blue_plus_linux/CHANGELOG.md @@ -0,0 +1,37 @@ +## 8.2.2 +* **[Release]** version bump for the flutter_blue_plus 2.2.2 release + +## 8.2.1 +* **[LICENSE]** clarifications to the development exemption + +## 8.2.0 +* **[LICENSE]** new tiers based on company size & development exemption + +## 8.1.0 +* **[LICENSE]** commercial license is now required for 15 or more employees + +## 8.0.1 +* Add License symlink + +## 8.0.0 +* Switch to FBP License + +## 3.0.2 +* Return unknown state if adaptors list empty (#1190) +* Return empty name if adaptors list empty (#1191) +* Return start scan false if adaptors list empty (#1193) +* Return stop scan false if adaptors list empty (#1194) +* Return turn off false if adaptors list empty (#1195) +* Return turn on false if adaptors list empty (#1196) + +## 3.0.1 +* Implement on turn on response stream (#1174) + +## 3.0.0 +* Update platform interface version to 3.0.0 + +## 2.0.0 +* Replace void return types with bool return types + +## 1.0.0 +* Initial release diff --git a/packages/flutter_blue_plus_linux/LICENSE b/packages/flutter_blue_plus_linux/LICENSE new file mode 100644 index 00000000..08fd9343 --- /dev/null +++ b/packages/flutter_blue_plus_linux/LICENSE @@ -0,0 +1,77 @@ +FlutterBluePlus License +Version 1.4 + +Copyright (c) 2026 Chip Weinberger +All rights reserved. + +--- + +### Preamble (Non-Binding) + +The intent of this license is to make FlutterBluePlus ("The Software") as free and open as possible for personal users, researchers, nonprofits, educational institutions, and hobbyists. For these users, the terms are similar to the BSD license: broad freedom to use, modify, and share. + +For for-profit use and by for-profit organizations, a commercial license is required. + +The revenue from commercial licenses supports the long-term maintenance and development of FlutterBluePlus. +This approach allows hobbyists, nonprofits, and educators to benefit from free and open software, while ensuring that for-profit companies who rely on it help sustain its future. + +Please be aware that this project originated under the BSD-3 license, and some portions of the codebase remain under that license today. Compliance with those clauses is not required under the FlutterBluePlus License itself, but to remain fully compliant with the terms set by those contributors, it is advised that users continue to follow the BSD-3 conditions described in NOTICE.md. That relationship is between you and the BSD-licensed contributors. + +This preamble is provided for explanation only and does not form part of the binding legal terms of this license. + +--- + +### Section 1: Common Conditions (apply to all users) + +Permission is hereby granted to any individual or organization to use, copy, modify, and distribute the Software in source code or binary form, subject to the following conditions: + +**1. Source Code Redistributions.** Redistributions of source code must retain the above copyright notice and this entire license text without modification. + +**2. Relicensing Prohibition.** The Software may not be relicensed under different terms by any party. + +**3. Commercial Use Requirement.** Use of the Software by any for-profit organization requires a commercial license under Section 3, regardless of how the Software was obtained. + +**4. Nonprofit & Educational Exemption.** Registered nonprofit organizations and accredited educational institutions are exempt from this requirement and may use the Software under Section 2. + +--- + +### Section 2: Open Use Terms (for nonprofits, educational institutions, personal use) + +Use of the Software is free of charge for any registered nonprofit organization, accredited educational institution, or personal user, subject to the Common Conditions and the following additional terms: + +**1. Endorsement Restriction.** Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. + +--- + +### Section 3: Commercial Terms (for for-profit organizations) + +Any use of FlutterBluePlus by or for a for-profit company or corporation — including commercial use by individuals — requires the purchase of a commercial license, subject to the Common Conditions and the following additional terms: + +**1. License Fee.** Commercial licenses are offered in the following tiers, based on employee count **at the time of purchase**. The associated cost is listed on the official FlutterBluePlus payment portal. + +- **Starter:** 0–9 employees +- **Team:** 10–29 employees +- **Business:** 30–99 employees +- **Enterprise:** 100 or more employees + +**2. Perpetual Use.** The license grants perpetual rights to use the Software and to receive all current and future software updates made available by the licensor after purchase. + +**3. Development Clarification.** Use of the Software during development, testing, or evaluation by a for-profit organization is considered commercial use and requires a commercial license. + +**4. Official Payment Portal.** Payment must be made via the official payment portal: https://jamcorder.myshopify.com/products/flutterblueplus-commercial-license + +**5. Validity of Offer.** This Section constitutes an offer only while this license version is the current version published in the main branch of the official FlutterBluePlus repository. Once superseded, replaced, or withdrawn, this version shall no longer be considered an active offer, even if archived copies remain publicly visible. + + +A valid commercial license covers use of all current and future packages that +are part of the FlutterBluePlus project, including its federated packages +(e.g., flutter_blue_plus, flutter_blue_plus_darwin, flutter_blue_plus_android, +flutter_blue_plus_web, flutter_blue_plus_linux, flutter_blue_plus_platform_interface). +Only a single commercial license is required per organization, regardless of how many +FlutterBluePlus packages are used. + +--- + +### Section 4: Warranty Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_linux/LICENSE.md b/packages/flutter_blue_plus_linux/LICENSE.md new file mode 100644 index 00000000..08fd9343 --- /dev/null +++ b/packages/flutter_blue_plus_linux/LICENSE.md @@ -0,0 +1,77 @@ +FlutterBluePlus License +Version 1.4 + +Copyright (c) 2026 Chip Weinberger +All rights reserved. + +--- + +### Preamble (Non-Binding) + +The intent of this license is to make FlutterBluePlus ("The Software") as free and open as possible for personal users, researchers, nonprofits, educational institutions, and hobbyists. For these users, the terms are similar to the BSD license: broad freedom to use, modify, and share. + +For for-profit use and by for-profit organizations, a commercial license is required. + +The revenue from commercial licenses supports the long-term maintenance and development of FlutterBluePlus. +This approach allows hobbyists, nonprofits, and educators to benefit from free and open software, while ensuring that for-profit companies who rely on it help sustain its future. + +Please be aware that this project originated under the BSD-3 license, and some portions of the codebase remain under that license today. Compliance with those clauses is not required under the FlutterBluePlus License itself, but to remain fully compliant with the terms set by those contributors, it is advised that users continue to follow the BSD-3 conditions described in NOTICE.md. That relationship is between you and the BSD-licensed contributors. + +This preamble is provided for explanation only and does not form part of the binding legal terms of this license. + +--- + +### Section 1: Common Conditions (apply to all users) + +Permission is hereby granted to any individual or organization to use, copy, modify, and distribute the Software in source code or binary form, subject to the following conditions: + +**1. Source Code Redistributions.** Redistributions of source code must retain the above copyright notice and this entire license text without modification. + +**2. Relicensing Prohibition.** The Software may not be relicensed under different terms by any party. + +**3. Commercial Use Requirement.** Use of the Software by any for-profit organization requires a commercial license under Section 3, regardless of how the Software was obtained. + +**4. Nonprofit & Educational Exemption.** Registered nonprofit organizations and accredited educational institutions are exempt from this requirement and may use the Software under Section 2. + +--- + +### Section 2: Open Use Terms (for nonprofits, educational institutions, personal use) + +Use of the Software is free of charge for any registered nonprofit organization, accredited educational institution, or personal user, subject to the Common Conditions and the following additional terms: + +**1. Endorsement Restriction.** Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission. + +--- + +### Section 3: Commercial Terms (for for-profit organizations) + +Any use of FlutterBluePlus by or for a for-profit company or corporation — including commercial use by individuals — requires the purchase of a commercial license, subject to the Common Conditions and the following additional terms: + +**1. License Fee.** Commercial licenses are offered in the following tiers, based on employee count **at the time of purchase**. The associated cost is listed on the official FlutterBluePlus payment portal. + +- **Starter:** 0–9 employees +- **Team:** 10–29 employees +- **Business:** 30–99 employees +- **Enterprise:** 100 or more employees + +**2. Perpetual Use.** The license grants perpetual rights to use the Software and to receive all current and future software updates made available by the licensor after purchase. + +**3. Development Clarification.** Use of the Software during development, testing, or evaluation by a for-profit organization is considered commercial use and requires a commercial license. + +**4. Official Payment Portal.** Payment must be made via the official payment portal: https://jamcorder.myshopify.com/products/flutterblueplus-commercial-license + +**5. Validity of Offer.** This Section constitutes an offer only while this license version is the current version published in the main branch of the official FlutterBluePlus repository. Once superseded, replaced, or withdrawn, this version shall no longer be considered an active offer, even if archived copies remain publicly visible. + + +A valid commercial license covers use of all current and future packages that +are part of the FlutterBluePlus project, including its federated packages +(e.g., flutter_blue_plus, flutter_blue_plus_darwin, flutter_blue_plus_android, +flutter_blue_plus_web, flutter_blue_plus_linux, flutter_blue_plus_platform_interface). +Only a single commercial license is required per organization, regardless of how many +FlutterBluePlus packages are used. + +--- + +### Section 4: Warranty Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_linux/NOTICE.md b/packages/flutter_blue_plus_linux/NOTICE.md new file mode 100644 index 00000000..e9869a1e --- /dev/null +++ b/packages/flutter_blue_plus_linux/NOTICE.md @@ -0,0 +1,39 @@ +To comply with the requirements of the original BSD-style license, +the full text of that license is reproduced below. It applies to all +releases of this project up to and including version 1.36.8, published +before October 2025. Those releases remain available under the terms +below, which are irrevocable. + +All releases beginning with version 2.0.0, published in October 2025 +and onward, are licensed under the FlutterBluePlus License. + +------ + +Copyright 2017-2024, Paul DeMarco, Bosko Popovic, Charles Weinberger, Thomas Clark. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Buffalo PC Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/flutter_blue_plus_linux/README.md b/packages/flutter_blue_plus_linux/README.md new file mode 100644 index 00000000..83795a79 --- /dev/null +++ b/packages/flutter_blue_plus_linux/README.md @@ -0,0 +1,15 @@ +# flutter_blue_plus_linux + +The Linux implementation of [`flutter_blue_plus`][1]. + +## Usage + +This package is [endorsed][2], which means you can simply use `flutter_blue_plus` +normally. This package will be automatically included in your app when you do, +so you do not need to add it to your `pubspec.yaml`. + +However, if you `import` this package to use any of its APIs directly, you +should add it to your `pubspec.yaml` as usual. + +[1]: https://pub.dev/packages/flutter_blue_plus +[2]: https://flutter.dev/to/endorsed-federated-plugin diff --git a/packages/flutter_blue_plus_linux/analysis_options.yaml b/packages/flutter_blue_plus_linux/analysis_options.yaml new file mode 100644 index 00000000..1e432d55 --- /dev/null +++ b/packages/flutter_blue_plus_linux/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/tools/linter-rules. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/tools/analysis diff --git a/packages/flutter_blue_plus_linux/lib/flutter_blue_plus_linux.dart b/packages/flutter_blue_plus_linux/lib/flutter_blue_plus_linux.dart new file mode 100644 index 00000000..b25a399b --- /dev/null +++ b/packages/flutter_blue_plus_linux/lib/flutter_blue_plus_linux.dart @@ -0,0 +1,1229 @@ +import 'dart:async'; + +import 'package:bluez/bluez.dart'; +import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart'; +import 'package:rxdart/rxdart.dart'; + +extension on BlueZDevice { + DeviceIdentifier get remoteId { + return DeviceIdentifier(address); + } +} + +extension on BlueZGattCharacteristic { + int instanceId(BlueZGattService service) { + final target = Guid.fromBytes(uuid.value); + var idx = 0; + for (final c in service.characteristics) { + if (Guid.fromBytes(c.uuid.value) == target) { + if (identical(c, this)) return idx; + idx++; + } + } + return 0; + } +} + +final class FlutterBluePlusLinux extends FlutterBluePlusPlatform { + final _client = BlueZClient(); + + var _initialized = false; + var _logLevel = LogLevel.none; + + final _onCharacteristicReadController = + StreamController.broadcast(); + final _onCharacteristicWrittenController = + StreamController.broadcast(); + final _onDescriptorReadController = + StreamController.broadcast(); + final _onDescriptorWrittenController = + StreamController.broadcast(); + final _onDiscoveredServicesController = + StreamController.broadcast(); + final _onReadRssiController = StreamController.broadcast(); + final _onTurnOnResponseController = + StreamController.broadcast(); + + @override + Stream get onAdapterStateChanged { + return _client.adaptersChanged.where( + (adapters) { + return adapters.isNotEmpty; + }, + ).switchMap( + (adapters) { + return adapters.first.propertiesChanged.where( + (properties) { + return properties.contains('Powered'); + }, + ).map( + (properties) { + return BmBluetoothAdapterState( + adapterState: adapters.first.powered + ? BmAdapterStateEnum.on + : BmAdapterStateEnum.off, + ); + }, + ); + }, + ); + } + + @override + Stream get onBondStateChanged { + return _client.devicesChanged.switchMap( + (devices) { + return MergeStream( + devices.map( + (device) { + return device.propertiesChanged.where( + (properties) { + return properties.contains('Paired'); + }, + ).map( + (properties) { + return BmBondStateResponse( + remoteId: device.remoteId, + bondState: device.paired + ? BmBondStateEnum.bonded + : BmBondStateEnum.none, + prevState: null, + ); + }, + ); + }, + ), + ); + }, + ); + } + + @override + Stream get onCharacteristicReceived { + return _onCharacteristicReadController.stream.mergeWith([ + _client.devicesChanged.switchMap( + (devices) { + final streams = >[]; + + for (final device in devices) { + for (final service in device.gattServices) { + for (final characteristic in service.characteristics) { + streams.add( + characteristic.propertiesChanged.where( + (properties) { + return properties.contains('Value'); + }, + ).map( + (properties) { + return BmCharacteristicData( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + value: characteristic.value, + success: true, + errorCode: 0, + errorString: '', + ); + }, + ), + ); + } + } + } + + return MergeStream(streams); + }, + ), + ]); + } + + @override + Stream get onCharacteristicWritten { + return _onCharacteristicWrittenController.stream; + } + + @override + Stream get onConnectionStateChanged { + return _client.devicesChanged.switchMap( + (devices) { + return MergeStream( + devices.map( + (device) { + return device.propertiesChanged.where( + (properties) { + return properties.contains('Connected'); + }, + ).map( + (properties) { + return BmConnectionStateResponse( + remoteId: device.remoteId, + connectionState: device.connected + ? BmConnectionStateEnum.connected + : BmConnectionStateEnum.disconnected, + disconnectReasonCode: null, + disconnectReasonString: null, + ); + }, + ); + }, + ), + ); + }, + ); + } + + @override + Stream get onDescriptorRead { + return _onDescriptorReadController.stream; + } + + @override + Stream get onDescriptorWritten { + return _onDescriptorWrittenController.stream; + } + + @override + Stream get onDiscoveredServices { + return _onDiscoveredServicesController.stream; + } + + // OFFBAND PATCH (#717). Upstream returns Stream.empty() here, so no MTU ever + // reaches the Dart layer on Linux, FlutterBluePlus._mtuValues is never + // populated, and mtuNow stays on its 23-byte ATT default for the whole + // session. Anything sizing a write off the MTU is then permanently capped at + // the minimum, which locked this app's message composer at 0 bytes (#592). + // + // BlueZ does expose the negotiated ATT MTU: it is a property on + // org.bluez.GattCharacteristic1, surfaced by the bluez package this plugin + // already depends on as BlueZGattCharacteristic.mtu. The value was always one + // layer down, just never read. + // + // Emits the largest MTU reported across a device's characteristics. They + // describe one ATT link so they should agree; taking the max stops a + // characteristic that has not been exercised yet, and so reports nothing, + // from dragging the figure back down. + @override + Stream get onMtuChanged { + return _client.devicesChanged + .switchMap((devices) { + return MergeStream( + devices.map((device) { + // Rebuild the per-characteristic subscriptions whenever the + // device's own properties change, NOT just when the device list + // does. devicesChanged only fires on deviceAdded/deviceRemoved, + // and at the moment a device is added BlueZ has not finished + // service discovery, so gattServices is still empty: this plugin + // waits on `while (!device.servicesResolved)` elsewhere for + // exactly that reason. Subscribing only on the device-list event + // would therefore attach to nothing and miss every later MTU for + // that device, permanently. ServicesResolved flipping true is a + // device property change, so this re-runs once characteristics + // actually exist. Same nested shape _initFlutterBluePlus uses. + return device.propertiesChanged + .startWith(const []).switchMap((_) { + final streams = >[]; + + for (final service in device.gattServices) { + for (final characteristic in service.characteristics) { + streams.add( + characteristic.propertiesChanged + .where((properties) => properties.contains('MTU')) + .map((properties) => device), + ); + } + } + + // Emit once on every rebuild so an MTU already negotiated + // before we were listening is reported, instead of waiting + // for a change that may never come. Harmless when unknown: + // the 0 is filtered out downstream. + return MergeStream(streams).startWith(device); + }); + }), + ); + }) + .map((device) { + var best = 0; + + for (final service in device.gattServices) { + for (final characteristic in service.characteristics) { + final mtu = characteristic.mtu; + if (mtu != null && mtu > best) { + best = mtu; + } + } + } + + return BmMtuChangedResponse( + remoteId: device.remoteId, + mtu: best, + success: true, + errorCode: 0, + errorString: '', + ); + }) + // Never report 0: FlutterBluePlus would cache it and mtuNow would then + // hand callers a worse answer than its own 23-byte default. + .where((response) => response.mtu > 0) + .distinct( + (previous, next) => + previous.remoteId == next.remoteId && previous.mtu == next.mtu, + ); + } + + @override + Stream get onNameChanged { + return _client.devicesChanged.switchMap( + (devices) { + return MergeStream( + devices.map( + (device) { + return device.propertiesChanged.where( + (properties) { + return properties.contains('Name'); + }, + ).map( + (properties) { + return BmNameChanged( + remoteId: device.remoteId, + name: device.name, + ); + }, + ); + }, + ), + ); + }, + ); + } + + @override + Stream get onReadRssi { + return _onReadRssiController.stream; + } + + @override + Stream get onScanResponse { + return _client.deviceAdded.map( + (device) { + return BmScanResponse( + advertisements: [ + BmScanAdvertisement( + remoteId: device.remoteId, + platformName: device.name, + advName: null, + connectable: true, + txPowerLevel: device.txPower, + appearance: device.appearance, + manufacturerData: device.manufacturerData.map( + (id, value) { + return MapEntry(id.id, value); + }, + ), + serviceData: device.serviceData.map( + (uuid, value) { + return MapEntry(Guid.fromBytes(uuid.value), value); + }, + ), + serviceUuids: device.uuids.map( + (uuid) { + return Guid.fromBytes(uuid.value); + }, + ).toList(), + rssi: device.rssi, + ), + ], + success: true, + errorCode: 0, + errorString: '', + ); + }, + ); + } + + @override + Stream get onServicesReset { + return _client.devicesChanged.switchMap( + (devices) { + return MergeStream( + devices.map( + (device) { + return device.propertiesChanged.where( + (properties) { + return properties.contains('UUIDs'); + }, + ).map( + (properties) { + return BmBluetoothDevice( + remoteId: device.remoteId, + platformName: device.name, + ); + }, + ); + }, + ), + ); + }, + ); + } + + @override + Stream get onTurnOnResponse { + return _onTurnOnResponseController.stream; + } + + @override + Future connect( + BmConnectRequest request, + ) async { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + await device.connect(); + + return true; + } + + @override + Future createBond( + BmCreateBondRequest request, + ) async { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + await device.pair(); + + return true; + } + + @override + Future disconnect( + BmDisconnectRequest request, + ) async { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + await device.disconnect(); + + return true; + } + + @override + Future discoverServices( + BmDiscoverServicesRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + // Ensure BlueZ has completed service discovery before returning results + while (!device.servicesResolved) { + await Future.delayed(const Duration(milliseconds: 100)); + } + + _onDiscoveredServicesController.add( + BmDiscoverServicesResult( + remoteId: device.remoteId, + services: device.gattServices.map( + (service) { + return BmBluetoothService( + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + remoteId: device.remoteId, + characteristics: service.characteristics.map( + (characteristic) { + return BmBluetoothCharacteristic( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + descriptors: characteristic.descriptors.map( + (descriptor) { + return BmBluetoothDescriptor( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + descriptorUuid: Guid.fromBytes( + descriptor.uuid.value, + ), + ); + }, + ).toList(), + properties: BmCharacteristicProperties( + broadcast: characteristic.flags.contains( + BlueZGattCharacteristicFlag.broadcast, + ), + read: characteristic.flags.contains( + BlueZGattCharacteristicFlag.read, + ), + writeWithoutResponse: characteristic.flags.contains( + BlueZGattCharacteristicFlag.writeWithoutResponse, + ), + write: characteristic.flags.contains( + BlueZGattCharacteristicFlag.write, + ), + notify: characteristic.flags.contains( + BlueZGattCharacteristicFlag.notify, + ), + indicate: characteristic.flags.contains( + BlueZGattCharacteristicFlag.indicate, + ), + authenticatedSignedWrites: + characteristic.flags.contains( + BlueZGattCharacteristicFlag.authenticatedSignedWrites, + ), + extendedProperties: characteristic.flags.contains( + BlueZGattCharacteristicFlag.extendedProperties, + ), + notifyEncryptionRequired: false, + indicateEncryptionRequired: false, + ), + ); + }, + ).toList(), + ); + }, + ).toList(), + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onDiscoveredServicesController.add( + BmDiscoverServicesResult( + remoteId: request.remoteId, + services: [], + success: false, + errorCode: 0, + errorString: '', + ), + ); + + return false; + } + } + + @override + Future getAdapterName( + BmBluetoothAdapterNameRequest request, + ) async { + await _initFlutterBluePlus(); + + return BmBluetoothAdapterName( + adapterName: _client.adapters.firstOrNull?.name ?? '', + ); + } + + @override + Future getAdapterState( + BmBluetoothAdapterStateRequest request, + ) async { + await _initFlutterBluePlus(); + + return BmBluetoothAdapterState( + adapterState: switch (_client.adapters.firstOrNull?.powered) { + true => BmAdapterStateEnum.on, + false => BmAdapterStateEnum.off, + _ => BmAdapterStateEnum.unknown, + }, + ); + } + + @override + Future getBondState( + BmBondStateRequest request, + ) async { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + return BmBondStateResponse( + remoteId: device.remoteId, + bondState: device.paired ? BmBondStateEnum.bonded : BmBondStateEnum.none, + prevState: null, + ); + } + + @override + Future getBondedDevices( + BmBondedDevicesRequest request, + ) async { + await _initFlutterBluePlus(); + + return BmDevicesList( + devices: _client.devices.where( + (device) { + return device.paired; + }, + ).map( + (device) { + return BmBluetoothDevice( + remoteId: device.remoteId, + platformName: device.name, + ); + }, + ).toList(), + ); + } + + @override + Future getSystemDevices( + BmSystemDevicesRequest request, + ) async { + await _initFlutterBluePlus(); + + return BmDevicesList( + devices: _client.devices.map( + (device) { + return BmBluetoothDevice( + remoteId: device.remoteId, + platformName: device.name, + ); + }, + ).toList(), + ); + } + + @override + Future isSupported( + BmIsSupportedRequest request, + ) async { + await _initFlutterBluePlus(); + + return _client.adapters.isNotEmpty; + } + + @override + Future readCharacteristic( + BmReadCharacteristicRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + final service = device.gattServices.singleWhere( + (service) { + final uuid = Guid.fromBytes( + service.uuid.value, + ); + + return uuid == request.serviceUuid; + }, + ); + + final characteristic = service.characteristics.singleWhere( + (characteristic) { + final uuid = Guid.fromBytes( + characteristic.uuid.value, + ); + + return uuid == request.characteristicUuid && + (characteristic.instanceId(service) == request.instanceId); + }, + ); + + final value = await characteristic.readValue(); + + _onCharacteristicReadController.add( + BmCharacteristicData( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + value: value, + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onCharacteristicReadController.add( + BmCharacteristicData( + remoteId: request.remoteId, + primaryServiceUuid: null, + serviceUuid: request.serviceUuid, + characteristicUuid: request.characteristicUuid, + instanceId: request.instanceId, + value: [], + success: false, + errorCode: 0, + errorString: e.toString(), + ), + ); + + return false; + } + } + + @override + Future readDescriptor( + BmReadDescriptorRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + final service = device.gattServices.singleWhere( + (service) { + final uuid = Guid.fromBytes( + service.uuid.value, + ); + + return uuid == request.serviceUuid; + }, + ); + + final characteristic = service.characteristics.singleWhere( + (characteristic) { + final uuid = Guid.fromBytes( + characteristic.uuid.value, + ); + + return uuid == request.characteristicUuid && + (characteristic.instanceId(service) == request.instanceId); + }, + ); + + final descriptor = characteristic.descriptors.singleWhere( + (descriptor) { + final uuid = Guid.fromBytes( + descriptor.uuid.value, + ); + + return uuid == request.descriptorUuid; + }, + ); + + final value = await descriptor.readValue(); + + _onDescriptorReadController.add( + BmDescriptorData( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + descriptorUuid: Guid.fromBytes( + descriptor.uuid.value, + ), + value: value, + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onDescriptorReadController.add( + BmDescriptorData( + remoteId: request.remoteId, + primaryServiceUuid: null, + serviceUuid: request.serviceUuid, + characteristicUuid: request.characteristicUuid, + instanceId: request.instanceId, + descriptorUuid: request.descriptorUuid, + value: [], + success: false, + errorCode: 0, + errorString: e.toString(), + ), + ); + + return false; + } + } + + @override + Future readRssi( + BmReadRssiRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + _onReadRssiController.add( + BmReadRssiResult( + remoteId: device.remoteId, + rssi: device.rssi, + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onReadRssiController.add( + BmReadRssiResult( + remoteId: request.remoteId, + rssi: 0, + success: false, + errorCode: 0, + errorString: e.toString(), + ), + ); + + return false; + } + } + + @override + Future setLogLevel( + BmSetLogLevelRequest request, + ) async { + await _initFlutterBluePlus(); + + _logLevel = request.logLevel; + + return true; + } + + @override + Future setNotifyValue( + BmSetNotifyValueRequest request, + ) async { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + final service = device.gattServices.singleWhere( + (service) { + final uuid = Guid.fromBytes( + service.uuid.value, + ); + + return uuid == request.serviceUuid; + }, + ); + + final characteristic = service.characteristics.singleWhere( + (characteristic) { + final uuid = Guid.fromBytes( + characteristic.uuid.value, + ); + + return uuid == request.characteristicUuid && + (characteristic.instanceId(service) == request.instanceId); + }, + ); + + if (request.enable) { + await characteristic.startNotify(); + } else { + await characteristic.stopNotify(); + } + + // No CCCD write on Linux; no separate response event expected + return false; + } + + @override + Future startScan( + BmScanSettings request, + ) async { + await _initFlutterBluePlus(); + + final adapter = _client.adapters.firstOrNull; + + if (adapter == null) { + return false; + } + + await adapter.setDiscoveryFilter( + uuids: request.withServices.map( + (uuid) { + return uuid.str128; + }, + ).toList(), + ); + + await adapter.startDiscovery(); + + return true; + } + + @override + Future stopScan( + BmStopScanRequest request, + ) async { + await _initFlutterBluePlus(); + + final adapter = _client.adapters.firstOrNull; + + if (adapter == null) { + return false; + } + + await adapter.stopDiscovery(); + + return true; + } + + @override + Future turnOff( + BmTurnOffRequest request, + ) async { + await _initFlutterBluePlus(); + + final adapter = _client.adapters.firstOrNull; + + if (adapter == null || adapter.powered == false) { + return false; + } + + await adapter.setPowered(false); + + return true; + } + + @override + Future turnOn( + BmTurnOnRequest request, + ) async { + await _initFlutterBluePlus(); + + final adapter = _client.adapters.firstOrNull; + + if (adapter == null || adapter.powered == true) { + return false; + } + + await adapter.setPowered(true); + + _onTurnOnResponseController.add( + BmTurnOnResponse( + userAccepted: true, + ), + ); + + return true; + } + + @override + Future writeCharacteristic( + BmWriteCharacteristicRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + final service = device.gattServices.singleWhere( + (service) { + final uuid = Guid.fromBytes( + service.uuid.value, + ); + + return uuid == request.serviceUuid; + }, + ); + + final characteristic = service.characteristics.singleWhere( + (characteristic) { + final uuid = Guid.fromBytes( + characteristic.uuid.value, + ); + + return uuid == request.characteristicUuid && + (characteristic.instanceId(service) == request.instanceId); + }, + ); + + await characteristic.writeValue( + request.value, + type: request.writeType == BmWriteType.withResponse + ? BlueZGattCharacteristicWriteType.request + : BlueZGattCharacteristicWriteType.command, + ); + + _onCharacteristicWrittenController.add( + BmCharacteristicData( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + value: request.value, + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onCharacteristicWrittenController.add( + BmCharacteristicData( + remoteId: request.remoteId, + primaryServiceUuid: null, + serviceUuid: request.serviceUuid, + characteristicUuid: request.characteristicUuid, + instanceId: request.instanceId, + value: request.value, + success: false, + errorCode: 0, + errorString: e.toString(), + ), + ); + + return false; + } + } + + @override + Future writeDescriptor( + BmWriteDescriptorRequest request, + ) async { + try { + await _initFlutterBluePlus(); + + final device = _client.devices.singleWhere( + (device) { + return device.remoteId == request.remoteId; + }, + ); + + final service = device.gattServices.singleWhere( + (service) { + final uuid = Guid.fromBytes( + service.uuid.value, + ); + + return uuid == request.serviceUuid; + }, + ); + + final characteristic = service.characteristics.singleWhere( + (characteristic) { + final uuid = Guid.fromBytes( + characteristic.uuid.value, + ); + + return uuid == request.characteristicUuid && + (characteristic.instanceId(service) == request.instanceId); + }, + ); + + final descriptor = characteristic.descriptors.singleWhere( + (descriptor) { + final uuid = Guid.fromBytes( + descriptor.uuid.value, + ); + + return uuid == request.descriptorUuid; + }, + ); + + await descriptor.writeValue(request.value); + + _onDescriptorWrittenController.add( + BmDescriptorData( + remoteId: device.remoteId, + primaryServiceUuid: null, + serviceUuid: Guid.fromBytes( + service.uuid.value, + ), + characteristicUuid: Guid.fromBytes( + characteristic.uuid.value, + ), + instanceId: characteristic.instanceId(service), + descriptorUuid: Guid.fromBytes( + descriptor.uuid.value, + ), + value: request.value, + success: true, + errorCode: 0, + errorString: '', + ), + ); + + return true; + } catch (e) { + _onDescriptorWrittenController.add( + BmDescriptorData( + remoteId: request.remoteId, + primaryServiceUuid: null, + serviceUuid: request.serviceUuid, + characteristicUuid: request.characteristicUuid, + instanceId: request.instanceId, + descriptorUuid: request.descriptorUuid, + value: request.value, + success: false, + errorCode: 0, + errorString: e.toString(), + ), + ); + + return false; + } + } + + static void registerWith() { + FlutterBluePlusPlatform.instance = FlutterBluePlusLinux(); + } + + Future _initFlutterBluePlus() async { + if (_initialized) { + return; + } + + _initialized = true; + + await _client.connect(); + + _client.devicesChanged.switchMap( + (devices) { + if (_logLevel == LogLevel.verbose) { + FlutterBluePlusPlatform.log( + '[FBP-Linux] devices changed ${devices.map((device) => device.remoteId).toList()}', + ); + } + + return MergeStream( + devices.map( + (device) { + return device.propertiesChanged.switchMap( + (properties) { + if (_logLevel == LogLevel.verbose) { + FlutterBluePlusPlatform.log( + '[FBP-Linux] device ${device.remoteId} properties changed $properties', + ); + } + + final streams = >[]; + + for (final service in device.gattServices) { + for (final characteristic in service.characteristics) { + streams.add( + characteristic.propertiesChanged.map( + (properties) { + if (_logLevel == LogLevel.verbose) { + FlutterBluePlusPlatform.log( + '[FBP-Linux] device ${device.remoteId} service ${service.uuid} characteristic ${characteristic.uuid} properties changed $properties', + ); + } + }, + ), + ); + } + } + + return MergeStream(streams); + }, + ); + }, + ), + ); + }, + ).listen(null); + } +} + +extension on BlueZClient { + Stream> get adaptersChanged { + return MergeStream([ + adapterAdded, + adapterRemoved, + ]).map( + (adapter) { + return adapters; + }, + ).startWith(adapters); + } + + Stream> get devicesChanged { + return MergeStream([ + deviceAdded, + deviceRemoved, + ]).map( + (device) { + return devices; + }, + ).startWith(devices); + } +} diff --git a/packages/flutter_blue_plus_linux/pubspec.yaml b/packages/flutter_blue_plus_linux/pubspec.yaml new file mode 100644 index 00000000..e78561c4 --- /dev/null +++ b/packages/flutter_blue_plus_linux/pubspec.yaml @@ -0,0 +1,27 @@ +name: flutter_blue_plus_linux +description: Linux implementation of the flutter_blue_plus plugin. +version: 8.2.2 +homepage: https://github.com/chipweinberger/flutter_blue_plus + +environment: + sdk: ^3.0.0 + flutter: '>=3.7.0' + +dependencies: + bluez: '>=0.7.8 <0.9.0' + flutter: + sdk: flutter + flutter_blue_plus_platform_interface: 8.2.2 + rxdart: '>=0.27.0 <0.29.0' + +dev_dependencies: + flutter_lints: ^5.0.0 + flutter_test: + sdk: flutter + +flutter: + plugin: + implements: flutter_blue_plus + platforms: + linux: + dartPluginClass: FlutterBluePlusLinux diff --git a/packages/flutter_blue_plus_winrt/.gitignore b/packages/flutter_blue_plus_winrt/.gitignore new file mode 100644 index 00000000..dd5eb989 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/flutter_blue_plus_winrt/.metadata b/packages/flutter_blue_plus_winrt/.metadata new file mode 100644 index 00000000..b8dd3d34 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "19074d12f7eaf6a8180cd4036a430c1d76de904e" + channel: "stable" + +project_type: package diff --git a/packages/flutter_blue_plus_winrt/CHANGELOG.md b/packages/flutter_blue_plus_winrt/CHANGELOG.md new file mode 100644 index 00000000..34a7a6f5 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/CHANGELOG.md @@ -0,0 +1,61 @@ +## 0.0.18 +* Fix multithreading & connection stability (#5) + +## 0.0.17 +* Fix: Initialize `manufacturer_data` map correctly (#10) + +## 0.0.16 +* Fix: MTU was always 23 on Windows. Now reports negotiated MTU correctly. + +## 0.0.15 +* Fix: missing runtimeobject.lib (#7) + +## 0.0.14 +* Improve: `systemDevices` now discovers both paired and connected devices. +* Fix: Build error (unused variable warning) in `flutterRestart`. + +## 0.0.13 +* Feat: Add bonding support and improve connection logic. + +## 0.0.12 +* Fix: Resolve extensive compilation errors (C2220, C2065, C2653, C4456) caused by scope resolution and variable shadowing in GATT discovery logic. +* Fix: `readRssi` now handles cache misses gracefully by returning 0 instead of throwing an exception when RSSI is not in the cache. + +## 0.0.11 +* Refactor characteristic lookup and fix memory management. + +## 0.0.10 +* Fix: ensure memory resources (like RSSI cache) are properly cleared upon disconnection. + +## 0.0.9 +* Fix: "vector erase iterator outside range" crash by safely handling device closure to avoid synchronous vector modifications. + +## 0.0.8 +* Fix: ensure `connect` method waits for actual physical connection completion before returning a result. + +## 0.0.7 +* Fix: ensure `connect` returns `false` on failure instead of throwing an exception. +* Improvement: refined connection state waiting logic for better reliability. + +## 0.0.6 +* Fix: ensure `connect` method waits for actual physical connection completion before returning a result. +* Fix: enhanced thread safety during rapid connection and disconnection to prevent `vector erase` crashes. +* Improvement: more robust resource cleanup when connection attempts fail. + +## 0.0.5 +* Fix: compilation errors (C2220) and typos in method signatures. + +## 0.0.4 +* Fix: crash during connection/disconnection caused by invalid vector iterators. +* Feature: add `setOptions` implementation. + +## 0.0.3 +* Fix: ensure physical disconnection by explicitly closing all GATT services. +* Fix: potential race condition where a device might stay connected if disconnected during the connection process. +* Fix: properly clear characteristic and descriptor caches upon disconnection. + +## 0.0.2 +* Fix: a version issue with `flutter_blue_plus_platform_interface` #1 + +## 0.0.1 +* Initial release. diff --git a/packages/flutter_blue_plus_winrt/LICENSE b/packages/flutter_blue_plus_winrt/LICENSE new file mode 100644 index 00000000..d2dd1d7a --- /dev/null +++ b/packages/flutter_blue_plus_winrt/LICENSE @@ -0,0 +1,7 @@ +Copyright 2025 Himchan Park + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/packages/flutter_blue_plus_winrt/README.md b/packages/flutter_blue_plus_winrt/README.md new file mode 100644 index 00000000..5c894281 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/README.md @@ -0,0 +1,15 @@ +# flutter_blue_plus_winrt + +The Windows implementation of [`flutter_blue_plus`][1]. + +## Usage + +This package is [endorsed][2], which means you can simply use `flutter_blue_plus` +normally. This package will be automatically included in your app when you do, +so you do not need to add it to your `pubspec.yaml`. + +However, if you `import` this package to use any of its APIs directly, you +should add it to your `pubspec.yaml` as usual. + +[1]: https://pub.dev/packages/flutter_blue_plus +[2]: https://flutter.dev/to/endorsed-federated-plugin diff --git a/packages/flutter_blue_plus_winrt/analysis_options.yaml b/packages/flutter_blue_plus_winrt/analysis_options.yaml new file mode 100644 index 00000000..1e432d55 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/tools/linter-rules. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/tools/analysis diff --git a/packages/flutter_blue_plus_winrt/lib/flutter_blue_plus_winrt.dart b/packages/flutter_blue_plus_winrt/lib/flutter_blue_plus_winrt.dart new file mode 100644 index 00000000..1f11304f --- /dev/null +++ b/packages/flutter_blue_plus_winrt/lib/flutter_blue_plus_winrt.dart @@ -0,0 +1,589 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart'; + +final class FlutterBluePlusWinrt extends FlutterBluePlusPlatform { + @visibleForTesting + final methodChannel = const MethodChannel('flutter_blue_plus/methods'); + + var _initialized = false; + var _logLevel = LogLevel.none; + var _logColor = true; + + final _onAdapterStateChangedController = + StreamController.broadcast(); + final _onBondStateChangedController = + StreamController.broadcast(); + final _onCharacteristicReceivedController = + StreamController.broadcast(); + final _onCharacteristicWrittenController = + StreamController.broadcast(); + final _onConnectionStateChangedController = + StreamController.broadcast(); + final _onDescriptorReadController = + StreamController.broadcast(); + final _onDescriptorWrittenController = + StreamController.broadcast(); + final _onDiscoveredServicesController = + StreamController.broadcast(); + final _onMtuChangedController = + StreamController.broadcast(); + final _onNameChangedController = StreamController.broadcast(); + final _onReadRssiController = StreamController.broadcast(); + final _onScanResponseController = + StreamController.broadcast(); + final _onServicesResetController = + StreamController.broadcast(); + final _onDetachedFromEngineController = + StreamController.broadcast(); + + @override + Stream get onAdapterStateChanged { + return _onAdapterStateChangedController.stream; + } + + @override + Stream get onBondStateChanged { + return _onBondStateChangedController.stream; + } + + @override + Stream get onCharacteristicReceived { + return _onCharacteristicReceivedController.stream; + } + + @override + Stream get onCharacteristicWritten { + return _onCharacteristicWrittenController.stream; + } + + @override + Stream get onConnectionStateChanged { + return _onConnectionStateChangedController.stream; + } + + @override + Stream get onDescriptorRead { + return _onDescriptorReadController.stream; + } + + @override + Stream get onDescriptorWritten { + return _onDescriptorWrittenController.stream; + } + + @override + Stream get onDiscoveredServices { + return _onDiscoveredServicesController.stream; + } + + @override + Stream get onMtuChanged { + return _onMtuChangedController.stream; + } + + @override + Stream get onNameChanged { + return _onNameChangedController.stream; + } + + @override + Stream get onReadRssi { + return _onReadRssiController.stream; + } + + @override + Stream get onScanResponse { + return _onScanResponseController.stream; + } + + @override + Stream get onServicesReset { + return _onServicesResetController.stream; + } + + @override + Stream get onDetachedFromEngine { + return _onDetachedFromEngineController.stream; + } + + static void registerWith() { + FlutterBluePlusPlatform.instance = FlutterBluePlusWinrt(); + } + + @override + Future clearGattCache( + BmClearGattCacheRequest request, + ) async { + return await _invokeMethod( + 'clearGattCache', + request.remoteId.str, + ) == + true; + } + + @override + Future connect( + BmConnectRequest request, + ) async { + return await _invokeMethod( + 'connect', + request.toMap(), + ) == + true; + } + + @override + Future createBond( + BmCreateBondRequest request, + ) async { + return await _invokeMethod( + 'createBond', + request.toMap(), + ) == + true; + } + + @override + Future disconnect( + BmDisconnectRequest request, + ) async { + return await _invokeMethod( + 'disconnect', + request.remoteId.str, + ) == + true; + } + + @override + Future discoverServices( + BmDiscoverServicesRequest request, + ) async { + return await _invokeMethod( + 'discoverServices', + request.remoteId.str, + ) == + true; + } + + @override + Future getAdapterName( + BmBluetoothAdapterNameRequest request, + ) async { + return BmBluetoothAdapterName( + adapterName: await _invokeMethod( + 'getAdapterName', + ), + ); + } + + @override + Future getAdapterState( + BmBluetoothAdapterStateRequest request, + ) async { + return BmBluetoothAdapterState.fromMap( + await _invokeMethod( + 'getAdapterState', + ), + ); + } + + @override + Future getBondState( + BmBondStateRequest request, + ) async { + return BmBondStateResponse.fromMap( + await _invokeMethod( + 'getBondState', + request.remoteId.str, + ), + ); + } + + @override + Future getBondedDevices( + BmBondedDevicesRequest request, + ) async { + return BmDevicesList.fromMap( + await _invokeMethod( + 'getBondedDevices', + ), + ); + } + + @override + Future getPhySupport( + PhySupportRequest request, + ) async { + return PhySupport.fromMap( + await _invokeMethod( + 'getPhySupport', + ), + ); + } + + @override + Future getSystemDevices( + BmSystemDevicesRequest request, + ) async { + // Windows implementation currently takes request.toMap(), platform interface default does not. + // Keeping request.toMap() for consistency with existing Windows code. + return BmDevicesList.fromMap( + await _invokeMethod( + 'getSystemDevices', + request.toMap(), + ), + ); + } + + @override + Future isSupported( + BmIsSupportedRequest request, + ) async { + return await _invokeMethod( + 'isSupported', + ) == + true; + } + + @override + Future readCharacteristic( + BmReadCharacteristicRequest request, + ) async { + return await _invokeMethod( + 'readCharacteristic', + request.toMap(), + ) == + true; + } + + @override + Future readDescriptor( + BmReadDescriptorRequest request, + ) async { + return await _invokeMethod( + 'readDescriptor', + request.toMap(), + ) == + true; + } + + @override + Future readRssi( + BmReadRssiRequest request, + ) async { + return await _invokeMethod( + 'readRssi', + request.remoteId.str, + ) == + true; + } + + @override + Future removeBond( + BmRemoveBondRequest request, + ) async { + return await _invokeMethod( + 'removeBond', + request.remoteId.str, + ) == + true; + } + + @override + Future requestConnectionPriority( + BmConnectionPriorityRequest request, + ) async { + return await _invokeMethod( + 'requestConnectionPriority', + request.toMap(), + ) == + true; + } + + @override + Future requestMtu( + BmMtuChangeRequest request, + ) async { + return await _invokeMethod( + 'requestMtu', + request.toMap(), + ) == + true; + } + + @override + Future setLogLevel( + BmSetLogLevelRequest request, + ) async { + _logLevel = request.logLevel; + _logColor = request.logColor; + + return await _invokeMethod( + 'setLogLevel', + request.logLevel.index, + ) == + true; + } + + @override + Future setNotifyValue( + BmSetNotifyValueRequest request, + ) async { + return await _invokeMethod( + 'setNotifyValue', + request.toMap(), + ) == + true; + } + + @override + Future setOptions( + BmSetOptionsRequest request, + ) async { + return await _invokeMethod( + 'setOptions', + request.toMap(), + ) == + true; + } + + @override + Future setPreferredPhy( + BmPreferredPhy request, + ) async { + return await _invokeMethod( + 'setPreferredPhy', + request.toMap(), + ) == + true; + } + + @override + Future startScan( + BmScanSettings request, + ) async { + return await _invokeMethod( + 'startScan', + request.toMap(), + ) == + true; + } + + @override + Future stopScan( + BmStopScanRequest request, + ) async { + return await _invokeMethod( + 'stopScan', + ) == + true; + } + + @override + Future turnOff( + BmTurnOffRequest request, + ) async { + return await _invokeMethod( + 'turnOff', + ) == + true; + } + + @override + Future turnOn( + BmTurnOnRequest request, + ) async { + return await _invokeMethod( + 'turnOn', + ) == + true; + } + + @override + Future writeCharacteristic( + BmWriteCharacteristicRequest request, + ) async { + return await _invokeMethod( + 'writeCharacteristic', + request.toMap(), + ) == + true; + } + + @override + Future writeDescriptor( + BmWriteDescriptorRequest request, + ) async { + return await _invokeMethod( + 'writeDescriptor', + request.toMap(), + ) == + true; + } + + Future _invokeMethod( + String method, [ + dynamic arguments, + ]) async { + // initialize + await _initFlutterBluePlus(); + + // log args + if (_logLevel == LogLevel.verbose) { + var func = '<$method>'; + var args = arguments.toString(); + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + args = _logColor ? '\x1B[1;35m$args\x1B[0m' : args; + print('[FBP] $func args: $args'); + } + + // invoke + final out = await methodChannel.invokeMethod(method, arguments); + + // log result + if (_logLevel == LogLevel.verbose) { + var func = '($method)'; + var result = out.toString(); + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result; + print('[FBP] $func result: $result'); + } + + return out; + } + + Future _initFlutterBluePlus() async { + if (_initialized) { + return; + } + + _initialized = true; + + // set platform method handler + methodChannel.setMethodCallHandler(_methodCallHandler); + + // flutter restart - wait for all devices to disconnect + if ((await methodChannel.invokeMethod('flutterRestart')) != 0) { + await Future.delayed(const Duration(milliseconds: 50)); + while ((await methodChannel.invokeMethod('connectedCount')) != 0) { + await Future.delayed(const Duration(milliseconds: 50)); + } + } + } + + Future _methodCallHandler( + MethodCall call, + ) async { + // log result + if (_logLevel == LogLevel.verbose) { + var func = '[[ ${call.method} ]]'; + var result = switch (call.method) { + 'OnDiscoveredServices' => _prettyPrint(call.arguments), + _ => call.arguments.toString(), + }; + func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func; + result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result; + print('[FBP] $func result: $result'); + } + + // handle method call + switch (call.method) { + case 'OnAdapterStateChanged': + return _onAdapterStateChangedController.add( + BmBluetoothAdapterState.fromMap( + call.arguments, + ), + ); + case 'OnBondStateChanged': + return _onBondStateChangedController.add( + BmBondStateResponse.fromMap( + call.arguments, + ), + ); + case 'OnCharacteristicReceived': + return _onCharacteristicReceivedController.add( + BmCharacteristicData.fromMap( + call.arguments, + ), + ); + case 'OnCharacteristicWritten': + return _onCharacteristicWrittenController.add( + BmCharacteristicData.fromMap( + call.arguments, + ), + ); + case 'OnConnectionStateChanged': + return _onConnectionStateChangedController.add( + BmConnectionStateResponse.fromMap( + call.arguments, + ), + ); + case 'OnDescriptorRead': + return _onDescriptorReadController.add( + BmDescriptorData.fromMap( + call.arguments, + ), + ); + case 'OnDescriptorWritten': + return _onDescriptorWrittenController.add( + BmDescriptorData.fromMap( + call.arguments, + ), + ); + case 'OnDetachedFromEngine': + return _onDetachedFromEngineController.add( + BmDetachedFromEngineResponse(), + ); + case 'OnDiscoveredServices': + return _onDiscoveredServicesController.add( + BmDiscoverServicesResult.fromMap( + call.arguments, + ), + ); + case 'OnMtuChanged': + return _onMtuChangedController.add( + BmMtuChangedResponse.fromMap( + call.arguments, + ), + ); + case 'OnNameChanged': + return _onNameChangedController.add( + BmNameChanged.fromMap( + call.arguments, + ), + ); + case 'OnReadRssi': + return _onReadRssiController.add( + BmReadRssiResult.fromMap( + call.arguments, + ), + ); + case 'OnScanResponse': + return _onScanResponseController.add( + BmScanResponse.fromMap( + call.arguments, + ), + ); + case 'OnServicesReset': + return _onServicesResetController.add( + BmBluetoothDevice.fromMap( + call.arguments, + ), + ); + } + } + + String _prettyPrint( + dynamic data, + ) { + if (data is Map || data is List) { + return const JsonEncoder.withIndent(' ').convert(data); + } else { + return data.toString(); + } + } +} diff --git a/packages/flutter_blue_plus_winrt/pubspec.yaml b/packages/flutter_blue_plus_winrt/pubspec.yaml new file mode 100644 index 00000000..ce5b1bb7 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/pubspec.yaml @@ -0,0 +1,31 @@ +name: flutter_blue_plus_winrt +description: Windows implementation of the flutter_blue_plus plugin. +# Vendored from upstream master 7b4504a2 (#686). Version marks it as our +# patched line; upstream published only up to 0.0.20. +version: 0.0.20+offband.1 +homepage: https://github.com/chan150/flutter_blue_plus_winrt + +environment: + sdk: ^3.0.0 + flutter: '>=3.7.0' + +dependencies: + flutter: + sdk: flutter + # Upstream master declares >=9.0.0 but its Dart layer is identical to 0.0.19 + # and uses nothing 9.x-only (#686). Relaxed so the app stays on 8.2.2; the + # 9.x/2.3.x upgrade was deliberately skipped (owner decision on #685). + flutter_blue_plus_platform_interface: ">=8.2.2" + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: + +flutter: + plugin: + implements: flutter_blue_plus + platforms: + windows: + pluginClass: FlutterBluePlusPlugin + dartPluginClass: FlutterBluePlusWinrt diff --git a/packages/flutter_blue_plus_winrt/windows/.gitignore b/packages/flutter_blue_plus_winrt/windows/.gitignore new file mode 100644 index 00000000..b3eb2be1 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/flutter_blue_plus_winrt/windows/CMakeLists.txt b/packages/flutter_blue_plus_winrt/windows/CMakeLists.txt new file mode 100644 index 00000000..2dcbb3b4 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/CMakeLists.txt @@ -0,0 +1,73 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "flutter_blue_plus_winrt") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Enable C++20 and coroutines +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "flutter_blue_plus_winrt_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "flutter_blue_plus_winrt_plugin.cpp" + "flutter_blue_plus_winrt_plugin.h" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h" + "flutter_blue_plus_winrt_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin runtimeobject ole32) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(flutter_blue_plus_winrt_bundled_libraries + "" + PARENT_SCOPE +) + +# === Tests === +# These unit tests can be run from a terminal after building the example, or +# from Visual Studio after opening the generated solution file. + +# Only enable test builds when building the example (which sets this variable) +# so that plugin clients aren't building the tests. +# Test section disabled because test directory is missing from the package. +# if (${include_${PROJECT_NAME}_tests}) +# ... +# endif() diff --git a/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.cpp b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.cpp new file mode 100644 index 00000000..241e9961 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.cpp @@ -0,0 +1,2056 @@ +#pragma warning(disable : 4819) + +#include "flutter_blue_plus_winrt_plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::Devices::Bluetooth; +using namespace Windows::Devices::Bluetooth::Advertisement; +using namespace Windows::Devices::Bluetooth::GenericAttributeProfile; +using namespace Windows::Devices::Enumeration; +using namespace Windows::Devices::Radios; + +namespace flutter_blue_plus_winrt { + +// Debug Logging Helper +void Log(const char* format, ...) { + char buffer[1024]; + va_list args; + va_start(args, format); + vsnprintf(buffer, sizeof(buffer), format, args); + va_end(args); + std::string msg = "[FBP-Win] "; + msg += buffer; + msg += "\n"; + OutputDebugStringA(msg.c_str()); +} + +namespace utils { +std::string to_string(const winrt::hstring& hstr) { + return winrt::to_string(hstr); +} + +template +T from_value(const flutter::EncodableValue* value) { + if (auto* ptr = std::get_if(value)) { + return *ptr; + } + if constexpr (std::is_integral_v && !std::is_same_v) { + if (auto* ptr64 = std::get_if(value)) { + return static_cast(*ptr64); + } + if (auto* ptr32 = std::get_if(value)) { + return static_cast(*ptr32); + } + } + return T{}; +} + +uint64_t mac_to_uint64(const std::string& mac_address) { + std::stringstream ss(mac_address); + uint64_t result = 0; + for (int i = 0; i < 6; ++i) { + long long byte; + ss >> std::hex >> byte; + result = (result << 8) | byte; + if (i < 5) { + ss.ignore(); + } + } + return result; +} + +std::vector to_vector(const winrt::Windows::Storage::Streams::IBuffer& buffer) { + auto reader = winrt::Windows::Storage::Streams::DataReader::FromBuffer(buffer); + std::vector data(reader.UnconsumedBufferLength()); + if (!data.empty()) { + reader.ReadBytes(data); + } + return data; +} + +std::string to_uuid_string(const winrt::guid& uuid) { + std::string uuid_str_with_braces = winrt::to_string(winrt::to_hstring(uuid)); + std::string full_uuid; + + if (uuid_str_with_braces.length() >= 2 && uuid_str_with_braces.front() == '{' && uuid_str_with_braces.back() == '}') { + full_uuid = uuid_str_with_braces.substr(1, uuid_str_with_braces.length() - 2); + } else { + full_uuid = uuid_str_with_braces; + } + + std::transform(full_uuid.begin(), full_uuid.end(), full_uuid.begin(), + [](unsigned char c){ return static_cast(std::tolower(c)); }); + + if (full_uuid.length() == 36 && + full_uuid.substr(0, 4) == "0000" && + full_uuid.substr(8) == "-0000-1000-8000-00805f9b34fb") { + return full_uuid.substr(4, 4); + } + return full_uuid; +} + +winrt::guid parse_uuid(const std::string& uuid_str) { + std::string full_uuid = uuid_str; + if (full_uuid.length() == 4) { + full_uuid = "0000" + full_uuid + "-0000-1000-8000-00805f9b34fb"; + } + else if (full_uuid.length() == 8) { + full_uuid = full_uuid + "-0000-1000-8000-00805f9b34fb"; + } + + if (full_uuid.length() > 0 && full_uuid.front() != '{') { + full_uuid = "{" + full_uuid + "}"; + } + + std::wstring wstr(full_uuid.begin(), full_uuid.end()); + GUID guid; + if (SUCCEEDED(IIDFromString(wstr.c_str(), &guid))) { + return winrt::guid(guid); + } + return winrt::guid(); +} + +} // namespace utils + +// --- GATT Helper Members --- + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::FindCharacteristicInServiceAsync( + GattDeviceService service, + int instance_id, + BluetoothCacheMode cacheMode) +{ + try { + auto charsResult = co_await service.GetCharacteristicsAsync(cacheMode); + if (charsResult.Status() == GattCommunicationStatus::Success) { + for (auto c : charsResult.Characteristics()) { + if (instance_id != 0 && static_cast(c.AttributeHandle()) == instance_id) { + co_return c; + } + } + } + + auto includedResult = co_await service.GetIncludedServicesAsync(cacheMode); + if (includedResult.Status() == GattCommunicationStatus::Success) { + for (auto includedService : includedResult.Services()) { + auto c = co_await FindCharacteristicInServiceAsync(includedService, instance_id, cacheMode); + if (c) co_return c; + } + } + } catch (...) {} + co_return nullptr; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::FindCharacteristicByDescriptorHandleInServiceAsync( + GattDeviceService service, + int descriptor_handle, + BluetoothCacheMode cacheMode) +{ + if (descriptor_handle == 0) co_return nullptr; + + try { + auto charsResult = co_await service.GetCharacteristicsAsync(cacheMode); + if (charsResult.Status() == GattCommunicationStatus::Success) { + for (auto c : charsResult.Characteristics()) { + auto descResult = co_await c.GetDescriptorsAsync(cacheMode); + if (descResult.Status() == GattCommunicationStatus::Success) { + for (auto d : descResult.Descriptors()) { + if (static_cast(d.AttributeHandle()) == descriptor_handle) { + co_return c; + } + } + } + } + } + + auto includedResult = co_await service.GetIncludedServicesAsync(cacheMode); + if (includedResult.Status() == GattCommunicationStatus::Success) { + for (auto includedService : includedResult.Services()) { + auto c = co_await FindCharacteristicByDescriptorHandleInServiceAsync(includedService, descriptor_handle, cacheMode); + if (c) co_return c; + } + } + } catch (...) {} + co_return nullptr; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::GetCharacteristicByHandleAsync( + BluetoothLEDevice device, + int instance_id) +{ + auto servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Cached); + if (servicesResult.Status() == GattCommunicationStatus::Success) { + for (auto service : servicesResult.Services()) { + auto c = co_await FindCharacteristicInServiceAsync(service, instance_id, BluetoothCacheMode::Cached); + if (c) co_return c; + } + } + + servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Uncached); + if (servicesResult.Status() == GattCommunicationStatus::Success) { + for (auto service : servicesResult.Services()) { + auto c = co_await FindCharacteristicInServiceAsync(service, instance_id, BluetoothCacheMode::Uncached); + if (c) co_return c; + } + } + co_return nullptr; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::GetCharacteristicByDescriptorHandleAsync( + BluetoothLEDevice device, + int descriptor_handle) +{ + auto servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Cached); + if (servicesResult.Status() == GattCommunicationStatus::Success) { + for (auto service : servicesResult.Services()) { + auto c = co_await FindCharacteristicByDescriptorHandleInServiceAsync(service, descriptor_handle, BluetoothCacheMode::Cached); + if (c) co_return c; + } + } + servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Uncached); + if (servicesResult.Status() == GattCommunicationStatus::Success) { + for (auto service : servicesResult.Services()) { + auto c = co_await FindCharacteristicByDescriptorHandleInServiceAsync(service, descriptor_handle, BluetoothCacheMode::Uncached); + if (c) co_return c; + } + } + co_return nullptr; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::GetCharacteristicAsync( + BluetoothLEDevice device, + std::string service_uuid_str, + std::string characteristic_uuid_str, + std::string primary_service_uuid_str, + int instance_id) +{ + GattCharacteristic targetChar = nullptr; + winrt::guid targetServiceUuid = utils::parse_uuid(service_uuid_str); + winrt::guid targetCharUuid = utils::parse_uuid(characteristic_uuid_str); + + if (!primary_service_uuid_str.empty()) { + winrt::guid primaryUuid = utils::parse_uuid(primary_service_uuid_str); + GattDeviceServicesResult primaryResult = co_await device.GetGattServicesForUuidAsync(primaryUuid, BluetoothCacheMode::Cached); + if (primaryResult.Status() != GattCommunicationStatus::Success || primaryResult.Services().Size() == 0) { + primaryResult = co_await device.GetGattServicesForUuidAsync(primaryUuid, BluetoothCacheMode::Uncached); + } + + if (primaryResult.Status() == GattCommunicationStatus::Success) { + for (auto primaryService : primaryResult.Services()) { + GattDeviceServicesResult includedResult = co_await primaryService.GetIncludedServicesForUuidAsync(targetServiceUuid, BluetoothCacheMode::Cached); + if (includedResult.Status() != GattCommunicationStatus::Success || includedResult.Services().Size() == 0) { + includedResult = co_await primaryService.GetIncludedServicesForUuidAsync(targetServiceUuid, BluetoothCacheMode::Uncached); + } + + if (includedResult.Status() == GattCommunicationStatus::Success) { + for (auto service : includedResult.Services()) { + GattCharacteristicsResult charsResult = co_await service.GetCharacteristicsForUuidAsync(targetCharUuid, BluetoothCacheMode::Cached); + if (charsResult.Status() != GattCommunicationStatus::Success || charsResult.Characteristics().Size() == 0) { + charsResult = co_await service.GetCharacteristicsForUuidAsync(targetCharUuid, BluetoothCacheMode::Uncached); + } + + if (charsResult.Status() == GattCommunicationStatus::Success) { + for (auto characteristic : charsResult.Characteristics()) { + if (instance_id == 0 || static_cast(characteristic.AttributeHandle()) == instance_id) { + targetChar = characteristic; + break; + } + } + } + if (targetChar) break; + } + } + if (targetChar) break; + } + } + } else { + GattDeviceServicesResult servicesResult = co_await device.GetGattServicesForUuidAsync(targetServiceUuid, BluetoothCacheMode::Cached); + if (servicesResult.Status() != GattCommunicationStatus::Success || servicesResult.Services().Size() == 0) { + servicesResult = co_await device.GetGattServicesForUuidAsync(targetServiceUuid, BluetoothCacheMode::Uncached); + } + + if (servicesResult.Status() == GattCommunicationStatus::Success) { + for (auto service : servicesResult.Services()) { + if (service.Uuid() == targetServiceUuid) { + GattCharacteristicsResult charsResult = co_await service.GetCharacteristicsForUuidAsync(targetCharUuid, BluetoothCacheMode::Cached); + if (charsResult.Status() != GattCommunicationStatus::Success || charsResult.Characteristics().Size() == 0) { + charsResult = co_await service.GetCharacteristicsForUuidAsync(targetCharUuid, BluetoothCacheMode::Uncached); + } + if (charsResult.Status() == GattCommunicationStatus::Success && charsResult.Characteristics().Size() > 0) { + for (auto c : charsResult.Characteristics()) { + if(instance_id == 0 || static_cast(c.AttributeHandle()) == instance_id) { + targetChar = c; + break; + } + } + } + } + if (targetChar) break; + } + } + } + co_return targetChar; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::GetDescriptorAsync( + GattCharacteristic characteristic, + std::string descriptor_uuid_str) +{ + if (!characteristic) co_return nullptr; + + winrt::guid descUuid = utils::parse_uuid(descriptor_uuid_str); + GattDescriptor targetDesc = nullptr; + + auto descResult = co_await characteristic.GetDescriptorsForUuidAsync(descUuid, BluetoothCacheMode::Cached); + if (descResult.Status() == GattCommunicationStatus::Success) { + for (auto descriptor : descResult.Descriptors()) { + if (utils::to_uuid_string(descriptor.Uuid()) == descriptor_uuid_str) { + targetDesc = descriptor; break; + } + } + } + + if (!targetDesc) { + descResult = co_await characteristic.GetDescriptorsForUuidAsync(descUuid, BluetoothCacheMode::Uncached); + if (descResult.Status() == GattCommunicationStatus::Success) { + for (auto descriptor : descResult.Descriptors()) { + if (utils::to_uuid_string(descriptor.Uuid()) == descriptor_uuid_str) { + targetDesc = descriptor; break; + } + } + } + } + co_return targetDesc; +} + +winrt::Windows::Foundation::IAsyncAction +FlutterBluePlusWinrtPlugin::PopulateCharacteristicsAsync( + GattDeviceService service, + std::string remote_id, + std::string primaryServiceUuid, + std::shared_ptr outList) +{ + auto charsResult = co_await service.GetCharacteristicsAsync(BluetoothCacheMode::Cached); + if (charsResult.Status() != GattCommunicationStatus::Success || charsResult.Characteristics().Size() == 0) { + charsResult = co_await service.GetCharacteristicsAsync(BluetoothCacheMode::Uncached); + } + + if (charsResult.Status() == GattCommunicationStatus::Success) { + for (auto characteristic : charsResult.Characteristics()) { + try { + flutter::EncodableMap charMap; + std::string serviceUuid = utils::to_uuid_string(service.Uuid()); + std::string charUuid = utils::to_uuid_string(characteristic.Uuid()); + int32_t handle = static_cast(characteristic.AttributeHandle()); + + { + std::lock_guard cache_lock(gatt_cache_mutex_); + characteristic_cache_[remote_id + ":" + std::to_string(handle)] = characteristic; + } + + charMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + if (!primaryServiceUuid.empty()) { + charMap[flutter::EncodableValue("primary_service_uuid")] = flutter::EncodableValue(primaryServiceUuid); + } + charMap[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(serviceUuid); + charMap[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(charUuid); + charMap[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(handle); + + auto props = characteristic.CharacteristicProperties(); + flutter::EncodableMap propsMap; + propsMap[flutter::EncodableValue("broadcast")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::Broadcast)) ? 1 : 0); + propsMap[flutter::EncodableValue("read")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::Read)) ? 1 : 0); + propsMap[flutter::EncodableValue("write_without_response")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::WriteWithoutResponse)) ? 1 : 0); + propsMap[flutter::EncodableValue("write")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::Write)) ? 1 : 0); + propsMap[flutter::EncodableValue("notify")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::Notify)) ? 1 : 0); + propsMap[flutter::EncodableValue("indicate")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::Indicate)) ? 1 : 0); + propsMap[flutter::EncodableValue("authenticated_signed_writes")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::AuthenticatedSignedWrites)) ? 1 : 0); + propsMap[flutter::EncodableValue("extended_properties")] = flutter::EncodableValue((static_cast(props) & static_cast(GattCharacteristicProperties::ExtendedProperties)) ? 1 : 0); + propsMap[flutter::EncodableValue("notify_encryption_required")] = flutter::EncodableValue(0); + propsMap[flutter::EncodableValue("indicate_encryption_required")] = flutter::EncodableValue(0); + + charMap[flutter::EncodableValue("properties")] = propsMap; + + auto descResult = co_await characteristic.GetDescriptorsAsync(BluetoothCacheMode::Cached); + if (descResult.Status() != GattCommunicationStatus::Success) { + descResult = co_await characteristic.GetDescriptorsAsync(BluetoothCacheMode::Uncached); + } + + flutter::EncodableList descList; + if (descResult.Status() == GattCommunicationStatus::Success) { + for (auto descriptor : descResult.Descriptors()) { + try { + flutter::EncodableMap descMap; + int32_t d_handle = static_cast(descriptor.AttributeHandle()); + + { + std::lock_guard cache_lock(gatt_cache_mutex_); + descriptor_cache_[remote_id + ":" + std::to_string(d_handle)] = descriptor; + } + + descMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + if (!primaryServiceUuid.empty()) { + descMap[flutter::EncodableValue("primary_service_uuid")] = flutter::EncodableValue(primaryServiceUuid); + } + descMap[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(serviceUuid); + descMap[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(charUuid); + descMap[flutter::EncodableValue("descriptor_uuid")] = flutter::EncodableValue(utils::to_uuid_string(descriptor.Uuid())); + descMap[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(handle); + + descList.push_back(descMap); + } catch(...) {} + } + } + charMap[flutter::EncodableValue("descriptors")] = descList; + outList->push_back(charMap); + } catch(...) {} + } + } + co_return; +} + +winrt::Windows::Foundation::IAsyncOperation +FlutterBluePlusWinrtPlugin::GetCharacteristicInternalAsync( + BluetoothLEDevice device, + std::string remote_id, + std::string service_uuid_str, + std::string characteristic_uuid_str, + std::string primary_service_uuid_str, + int instance_id) +{ + if (instance_id != 0) { + std::string cache_key = remote_id + ":" + std::to_string(instance_id); + winrt::Windows::Foundation::IInspectable cached = nullptr; + { + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it = characteristic_cache_.find(cache_key); + if (it != characteristic_cache_.end()) cached = it->second; + } + if (cached) co_return cached.as(); + } + + GattCharacteristic targetChar = nullptr; + if (instance_id != 0) { + targetChar = co_await GetCharacteristicByHandleAsync(device, instance_id); + } + if (!targetChar) { + targetChar = co_await GetCharacteristicAsync(device, service_uuid_str, characteristic_uuid_str, primary_service_uuid_str, instance_id); + } + + if (targetChar && instance_id != 0) { + std::lock_guard cache_lock(gatt_cache_mutex_); + characteristic_cache_[remote_id + ":" + std::to_string(instance_id)] = targetChar; + } + co_return targetChar; +} + +// --- Plugin Implementation --- + +void FlutterBluePlusWinrtPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows* registrar) { + auto plugin = std::make_unique(registrar); + auto* plugin_pointer = plugin.get(); + + plugin_pointer->channel_ = std::make_unique>( + registrar->messenger(), "flutter_blue_plus/methods", + &flutter::StandardMethodCodec::GetInstance()); + + plugin_pointer->channel_->SetMethodCallHandler( + [plugin_pointer](const auto& call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + registrar->AddPlugin(std::move(plugin)); +} + +FlutterBluePlusWinrtPlugin::FlutterBluePlusWinrtPlugin(flutter::PluginRegistrarWindows* registrar) + : registrar_(registrar) { + watcher_.ScanningMode(BluetoothLEScanningMode::Active); + received_token_ = watcher_.Received( + { this, &FlutterBluePlusWinrtPlugin::OnAdvertisementReceived }); + stopped_token_ = watcher_.Stopped( + { this, &FlutterBluePlusWinrtPlugin::OnAdvertisementStopped }); + + PeriodicConnectionCheck(); +} + +FlutterBluePlusWinrtPlugin::~FlutterBluePlusWinrtPlugin() { + // Signal all in-flight coroutines / event handlers that the plugin is gone. + // They capture a copy of this shared flag and bail out before touching + // `this`, avoiding use-after-free during teardown. + *is_alive_ = false; + try { watcher_.Stop(); } catch (...) {} + watcher_.Stopped(stopped_token_); + watcher_.Received(received_token_); + + // Revoke any still-registered per-device ConnectionStatusChanged handlers + // so a late event can't invoke OnConnectionStatusChanged on a destroyed + // plugin. Lock order is devices_mutex_ then gatt_cache_mutex_ (never the + // reverse anywhere), so this cannot deadlock. + std::lock_guard devices_lock(devices_mutex_); + std::lock_guard cache_lock(gatt_cache_mutex_); + auto revoke_all = [this](const std::vector>& devices) { + for (const auto& pair : devices) { + auto it = connection_tokens_.find(pair.first); + if (it == connection_tokens_.end()) continue; + try { pair.second.as().ConnectionStatusChanged(it->second); } catch (...) {} + } + }; + revoke_all(connected_devices_); + revoke_all(currently_connecting_devices_); + connection_tokens_.clear(); + + // Same reasoning for the MTU-change handlers: revoke them and close their + // sessions so a late MaxPduSizeChanged can't fire into a destroyed plugin. + for (const auto& entry : mtu_tokens_) { + auto it = gatt_sessions_.find(entry.first); + if (it == gatt_sessions_.end()) continue; + try { it->second.as().MaxPduSizeChanged(entry.second); } catch (...) {} + } + mtu_tokens_.clear(); + for (const auto& entry : gatt_sessions_) { + try { entry.second.as().Close(); } catch (...) {} + } + gatt_sessions_.clear(); +} + +void FlutterBluePlusWinrtPlugin::OnAdvertisementReceived( + const BluetoothLEAdvertisementWatcher&, + const BluetoothLEAdvertisementReceivedEventArgs& args) { + + [this, args, alive = is_alive_]() -> winrt::fire_and_forget { + try { + co_await ui_thread_; + if (!*alive) co_return; + + if (channel_) { + std::string remote_id = uint64_to_mac_string(args.BluetoothAddress()); + + // Bound memory usage: a hostile environment can rotate BLE + // addresses rapidly (address randomization / spoofing). Cap the + // number of distinct devices tracked during a scan session so + // the caches cannot grow without limit. Already-known devices + // keep updating normally. + constexpr size_t kMaxScanDevices = 4096; + bool is_new_device = scan_results_cache_.find(remote_id) == scan_results_cache_.end(); + if (is_new_device && scan_results_cache_.size() >= kMaxScanDevices) { + co_return; + } + + rssi_cache_[remote_id] = static_cast(args.RawSignalStrengthInDBm()); + + if (is_new_device) { + scan_results_cache_[remote_id] = {}; + } + auto& map = scan_results_cache_[remote_id]; + + map[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + map[flutter::EncodableValue("rssi")] = flutter::EncodableValue(static_cast(args.RawSignalStrengthInDBm())); + + int connectable = args.IsConnectable() ? 1 : 0; + if (connectable == 0) { + auto it = map.find(flutter::EncodableValue("connectable")); + if (it != map.end()) { + if (auto* val = std::get_if(&it->second)) { + if (*val == 1) connectable = 1; + } + } + } + map[flutter::EncodableValue("connectable")] = flutter::EncodableValue(connectable); + + auto advertisement = args.Advertisement(); + std::string localNameStr = utils::to_string(advertisement.LocalName()); + if (!localNameStr.empty()) { + map[flutter::EncodableValue("adv_name")] = flutter::EncodableValue(localNameStr); + map[flutter::EncodableValue("platform_name")] = flutter::EncodableValue(localNameStr); + } + + if (args.TransmitPowerLevelInDBm() != nullptr) { + map[flutter::EncodableValue("tx_power_level")] = + flutter::EncodableValue(static_cast(args.TransmitPowerLevelInDBm().Value())); + } + + for (const auto& section : advertisement.DataSections()) { + if (section.DataType() == 0x19) { + // Guard against a malformed/hostile peripheral sending an + // appearance section shorter than 2 bytes; ReadUInt16 would + // otherwise throw and abort processing of the whole packet. + if (section.Data().Length() < 2) break; + auto reader = winrt::Windows::Storage::Streams::DataReader::FromBuffer(section.Data()); + reader.ByteOrder(winrt::Windows::Storage::Streams::ByteOrder::LittleEndian); + uint16_t appearance_value = reader.ReadUInt16(); + map[flutter::EncodableValue("appearance")] = flutter::EncodableValue(static_cast(appearance_value)); + break; + } + } + + if (advertisement.ManufacturerData().Size() > 0) { + flutter::EncodableMap msd_map = flutter::EncodableMap(); + for (const auto& msd : advertisement.ManufacturerData()) { + msd_map[flutter::EncodableValue(static_cast(msd.CompanyId()))] = + flutter::EncodableValue(utils::to_vector(msd.Data())); + } + map[flutter::EncodableValue("manufacturer_data")] = msd_map; + } + + flutter::EncodableMap service_data_map; + auto it_sd = map.find(flutter::EncodableValue("service_data")); + if (it_sd != map.end()) { + if (auto* existing = std::get_if(&it_sd->second)) { + service_data_map = *existing; + } + } + + bool has_new_service_data = false; + for (const auto& section : advertisement.GetSectionsByType(0x16)) { + auto buffer = section.Data(); + if (buffer.Length() >= 2) { + has_new_service_data = true; + auto all_data = utils::to_vector(buffer); + uint16_t uuid16 = (all_data[1] << 8) | all_data[0]; + std::stringstream ss; + ss << std::hex << std::setfill('0') << std::setw(4) << uuid16; + std::string uuid_str = "0000" + ss.str() + "-0000-1000-8000-00805f9b34fb"; + std::vector data_vec(all_data.begin() + 2, all_data.end()); + service_data_map[flutter::EncodableValue(uuid_str)] = flutter::EncodableValue(data_vec); + } + } + if (has_new_service_data || !service_data_map.empty()) { + map[flutter::EncodableValue("service_data")] = service_data_map; + } + + if (advertisement.ServiceUuids().Size() > 0) { + flutter::EncodableList service_uuids_list; + auto it_u = map.find(flutter::EncodableValue("service_uuids")); + if (it_u != map.end()) { + if (auto* existing = std::get_if(&it_u->second)) { + service_uuids_list = *existing; + } + } + for (const auto& uuid : advertisement.ServiceUuids()) { + std::string uuid_str = utils::to_uuid_string(uuid); + bool found = false; + for(const auto& existing_val : service_uuids_list) { + if (auto* s = std::get_if(&existing_val)) { + if (*s == uuid_str) { found = true; break; } + } + } + if (!found) service_uuids_list.push_back(flutter::EncodableValue(uuid_str)); + } + map[flutter::EncodableValue("service_uuids")] = service_uuids_list; + } + + flutter::EncodableMap response; + response[flutter::EncodableValue("advertisements")] = flutter::EncodableList{ flutter::EncodableValue(map) }; + channel_->InvokeMethod("OnScanResponse", std::make_unique(response)); + } + } catch (...) {} + }(); +} + +void FlutterBluePlusWinrtPlugin::OnAdvertisementStopped( + const BluetoothLEAdvertisementWatcher&, + const BluetoothLEAdvertisementWatcherStoppedEventArgs&) { +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::GetSystemDevicesAsync(std::unique_ptr> result) { + std::string error_msg; + try { + // Broad selector for all Bluetooth LE devices using Association Endpoint protocol + auto selector = L"System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-9513-ade58156ee23}\""; + + Log("GetSystemDevices: Searching for connected BLE AEPs..."); + // Explicitly search for AssociationEndpoints + auto deviceInfoCollection = co_await DeviceInformation::FindAllAsync(selector, {}, DeviceInformationKind::AssociationEndpoint); + + Log("GetSystemDevices: Found %d biological AEPs", deviceInfoCollection.Size()); + + flutter::EncodableMap response = {}; + flutter::EncodableList deviceList; + + for (auto&& deviceInfo : deviceInfoCollection) { + try { + // Skip devices without a name as they are usually not useful + if (deviceInfo.Name().empty()) continue; + + auto bleDevice = co_await BluetoothLEDevice::FromIdAsync(deviceInfo.Id()); + if (!bleDevice) continue; + + // User requested ONLY connected devices + if (bleDevice.ConnectionStatus() == BluetoothConnectionStatus::Connected) { + std::string remote_id = uint64_to_mac_string(bleDevice.BluetoothAddress()); + + flutter::EncodableMap deviceMap = {}; + deviceMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + deviceMap[flutter::EncodableValue("platform_name")] = flutter::EncodableValue(utils::to_string(deviceInfo.Name())); + deviceMap[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(1); + deviceList.push_back(flutter::EncodableValue(deviceMap)); + + Log(" Added connected device: %ls (%s)", deviceInfo.Name().c_str(), remote_id.c_str()); + } + } catch (...) { + // Ignore failures for individual devices + } + } + + // Also ensure any devices connected directly by this app instance are included + // if they weren't already found by the system query (sometimes system cache lags) + { + std::lock_guard lock(devices_mutex_); + for (size_t i = 0; i < connected_devices_.size(); ++i) { + const auto& pair = connected_devices_[i]; + bool already_added = false; + for (const auto& val : deviceList) { + if (auto* m = std::get_if(&val)) { + auto it = m->find(flutter::EncodableValue("remote_id")); + if (it != m->end()) { + if (auto* s = std::get_if(&it->second)) { + if (*s == pair.first) { already_added = true; break; } + } + } + } + } + if (!already_added) { + try { + auto d = pair.second.as(); + flutter::EncodableMap deviceMap = {}; + deviceMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(pair.first); + deviceMap[flutter::EncodableValue("platform_name")] = flutter::EncodableValue(utils::to_string(d.Name())); + deviceMap[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(1); + deviceList.push_back(flutter::EncodableValue(deviceMap)); + } catch (...) {} + } + } + } + + + response[flutter::EncodableValue("devices")] = deviceList; + co_await ui_thread_; + result->Success(flutter::EncodableValue(response)); + co_return; + } catch (const std::exception& e) { error_msg = e.what(); Log("GetSystemDevices Error: %s", error_msg.c_str()); } + catch (...) { error_msg = "Unknown error occurred"; Log("GetSystemDevices Unknown Error"); } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("getSystemDevices", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::GetAdapterStateAsync(std::unique_ptr> result) { + std::string error_msg; + try { + auto radios = co_await Radio::GetRadiosAsync(); + std::string adapter_name = ""; + int adapter_state = 0; + for (auto radio : radios) { + if (radio.Kind() != RadioKind::Bluetooth) continue; + adapter_name = utils::to_string(radio.Name()); + switch (radio.State()) { + case RadioState::On: adapter_state = 4; break; + case RadioState::Off: adapter_state = 6; break; + default: adapter_state = 0; break; + } + break; + } + flutter::EncodableMap response = {}; + response[flutter::EncodableValue("adapter_state")] = flutter::EncodableValue(adapter_state); + response[flutter::EncodableValue("adapter_name")] = flutter::EncodableValue(adapter_name); + + co_await ui_thread_; + result->Success(flutter::EncodableValue(response)); + co_return; + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error occurred"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("getAdapterState", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::GetBondedDevicesAsync(std::unique_ptr> result) { + std::string error_msg; + try { + auto selector = BluetoothDevice::GetDeviceSelectorFromPairingState(true); + DeviceInformationCollection deviceInfoCollection = co_await DeviceInformation::FindAllAsync(selector); + flutter::EncodableMap response = {}; + flutter::EncodableList deviceList; + + for (auto&& deviceInfo : deviceInfoCollection) { + try { + auto bleDevice = co_await BluetoothLEDevice::FromIdAsync(deviceInfo.Id()); + if (!bleDevice) continue; + std::string remote_id = uint64_to_mac_string(bleDevice.BluetoothAddress()); + flutter::EncodableMap deviceMap = {}; + deviceMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + deviceMap[flutter::EncodableValue("platform_name")] = flutter::EncodableValue(utils::to_string(deviceInfo.Name())); + deviceMap[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(bleDevice.ConnectionStatus() == BluetoothConnectionStatus::Connected ? 1 : 0); + deviceList.push_back(flutter::EncodableValue(deviceMap)); + } catch (...) {} + } + response[flutter::EncodableValue("devices")] = deviceList; + co_await ui_thread_; + result->Success(flutter::EncodableValue(response)); + co_return; + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("getBondedDevices", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::CreateBondAsync(std::string remote_id, std::unique_ptr> result) { + std::string error_msg; + try { + auto bleDevice = co_await BluetoothLEDevice::FromBluetoothAddressAsync(utils::mac_to_uint64(remote_id)); + if (bleDevice) { + auto pairing = bleDevice.DeviceInformation().Pairing(); + auto result_val = co_await pairing.PairAsync(); + co_await ui_thread_; + result->Success(flutter::EncodableValue(result_val.Status() == DevicePairingResultStatus::Paired || result_val.Status() == DevicePairingResultStatus::AlreadyPaired)); + co_return; + } else { + error_msg = "Device not found"; + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("createBond", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::RemoveBondAsync(std::string remote_id, std::unique_ptr> result) { + std::string error_msg; + try { + auto bleDevice = co_await BluetoothLEDevice::FromBluetoothAddressAsync(utils::mac_to_uint64(remote_id)); + if (bleDevice) { + auto pairing = bleDevice.DeviceInformation().Pairing(); + auto result_val = co_await pairing.UnpairAsync(); + co_await ui_thread_; + result->Success(flutter::EncodableValue(result_val.Status() == DeviceUnpairingResultStatus::Unpaired || result_val.Status() == DeviceUnpairingResultStatus::AlreadyUnpaired)); + co_return; + } else { + error_msg = "Device not found"; + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("removeBond", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::GetBondStateAsync(std::string remote_id, std::unique_ptr> result) { + std::string error_msg; + try { + auto bleDevice = co_await BluetoothLEDevice::FromBluetoothAddressAsync(utils::mac_to_uint64(remote_id)); + if (bleDevice) { + bool isPaired = bleDevice.DeviceInformation().Pairing().IsPaired(); + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("bond_state")] = flutter::EncodableValue(isPaired ? 2 : 0); + co_await ui_thread_; + result->Success(flutter::EncodableValue(response)); + co_return; + } else { + error_msg = "Device not found"; + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Error("getBondState", error_msg); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::ConnectAsync( + std::string remote_id, + std::unique_ptr> result) { + + std::string error_msg; + try { + uint64_t bluetoothAddress = utils::mac_to_uint64(remote_id); + + co_await ui_thread_; + + { + std::lock_guard lock(devices_mutex_); + auto it_existing = std::find_if(connected_devices_.begin(), connected_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + if (it_existing != connected_devices_.end()) { + flutter::EncodableMap connection_state; + connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(1); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + result->Success(flutter::EncodableValue(true)); + // Normally a no-op (the session exists); repairs a connection + // whose earlier session creation failed. + CreateGattSessionAsync(remote_id, it_existing->second.as()); + co_return; + } + } + + co_await winrt::resume_background(); + auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(bluetoothAddress); + if (device) { + co_await ui_thread_; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + if (it == currently_connecting_devices_.end()) { + currently_connecting_devices_.emplace_back(remote_id, device); + } + } + auto conn_token = device.ConnectionStatusChanged({ this, &FlutterBluePlusWinrtPlugin::OnConnectionStatusChanged }); + { + std::lock_guard cache_lock(gatt_cache_mutex_); + connection_tokens_[remote_id] = conn_token; + } + + co_await winrt::resume_background(); + // Force connection by discovery + auto gatt_result = co_await device.GetGattServicesAsync(BluetoothCacheMode::Uncached); + + // Strictly wait for ConnectionStatus to be Connected (up to 5s) + int wait_retry = 0; + while (device.ConnectionStatus() != BluetoothConnectionStatus::Connected && wait_retry < 10) { + co_await winrt::resume_after(std::chrono::milliseconds(500)); + wait_retry++; + } + + co_await ui_thread_; + + bool should_close = false; + bool already_in_connected = false; + { + std::lock_guard lock(devices_mutex_); + + // Check if device was already moved to connected_devices_ by OnConnectionStatusChanged + auto it_connected = std::find_if(connected_devices_.begin(), connected_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + + auto it_connecting = std::find_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + + // If neither in connected nor connecting list, connection was cancelled/failed + if (it_connecting == currently_connecting_devices_.end() && it_connected == connected_devices_.end()) { + should_close = true; + } else if (gatt_result.Status() == GattCommunicationStatus::Success && device.ConnectionStatus() == BluetoothConnectionStatus::Connected) { + // Ensure device is in connected_devices_ (might already be added by OnConnectionStatusChanged) + if (it_connected == connected_devices_.end()) { + connected_devices_.emplace_back(remote_id, device); + } else { + already_in_connected = true; + } + + // Remove from connecting list if still there + currently_connecting_devices_.erase(std::remove_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }), currently_connecting_devices_.end()); + } + } + + if (should_close) { + if (device) { + { std::lock_guard cache_lock(gatt_cache_mutex_); connection_tokens_.erase(remote_id); } + device.Close(); + } + result->Success(flutter::EncodableValue(false)); + co_return; + } + + if (gatt_result.Status() == GattCommunicationStatus::Success && device.ConnectionStatus() == BluetoothConnectionStatus::Connected) { + // Only send connection state if not already sent by OnConnectionStatusChanged + if (!already_in_connected) { + flutter::EncodableMap connection_state; + connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(1); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + } + result->Success(flutter::EncodableValue(true)); + // After the connect result is reported, so a slow or failing + // session creation can never block or fail the connect itself. + CreateGattSessionAsync(remote_id, device); + co_return; + } else { + std::vector devices_to_close; + { + std::lock_guard lock(devices_mutex_); + + // Check connected devices + for (size_t i = 0; i < connected_devices_.size(); ++i) { + if (connected_devices_[i].first == remote_id) { + devices_to_close.push_back(connected_devices_[i].second.as()); + } + } + // Check connecting devices + for (size_t i = 0; i < currently_connecting_devices_.size(); ++i) { + if (currently_connecting_devices_[i].first == remote_id) { + devices_to_close.push_back(currently_connecting_devices_[i].second.as()); + } + } + + { + auto it = connected_devices_.begin(); + while (it != connected_devices_.end()) { + if (it->first == remote_id) { + it = connected_devices_.erase(it); + } else { + ++it; + } + } + } + + { + auto it = currently_connecting_devices_.begin(); + while (it != currently_connecting_devices_.end()) { + if (it->first == remote_id) { + it = currently_connecting_devices_.erase(it); + } else { + ++it; + } + } + } + } + + { std::lock_guard cache_lock(gatt_cache_mutex_); connection_tokens_.erase(remote_id); } + + for (auto& d : devices_to_close) { + try { d.Close(); } catch(...) {} + } + + flutter::EncodableMap connection_state; + connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(0); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + + result->Success(flutter::EncodableValue(false)); + co_return; + } + } else error_msg = "Device not found."; + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error occurred"; } + + if (!error_msg.empty()) { + co_await ui_thread_; + result->Success(flutter::EncodableValue(false)); + } +} + +std::string FlutterBluePlusWinrtPlugin::uint64_to_mac_string(uint64_t addr) { + std::stringstream stream; + stream << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << ((addr >> 40) & 0xFF) << ":" << std::setw(2) << ((addr >> 32) & 0xFF) << ":" << std::setw(2) << ((addr >> 24) & 0xFF) << ":" << std::setw(2) << ((addr >> 16) & 0xFF) << ":" << std::setw(2) << ((addr >> 8) & 0xFF) << ":" << std::setw(2) << (addr & 0xFF); + return stream.str(); +} + +void FlutterBluePlusWinrtPlugin::OnConnectionStatusChanged(const BluetoothLEDevice& device, const IInspectable&) { + // Capture device by value to avoid dangling references + [this, alive = is_alive_](BluetoothLEDevice d) -> winrt::fire_and_forget { + co_await ui_thread_; + if (!*alive) co_return; + + std::string remote_id = uint64_to_mac_string(d.BluetoothAddress()); + flutter::EncodableMap connection_state; + connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + + if (d.ConnectionStatus() == BluetoothConnectionStatus::Connected) { + bool solicited = false; + { + std::lock_guard lock(devices_mutex_); + + auto it_connected = std::find_if(connected_devices_.begin(), connected_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + + if (it_connected != connected_devices_.end()) { + solicited = true; + } else { + auto it_connecting = std::find_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; }); + + if(it_connecting != currently_connecting_devices_.end()) { + auto dev_obj = it_connecting->second; + connected_devices_.emplace_back(remote_id, dev_obj); + + // Safe removal: use temporary variable to store index to delete + currently_connecting_devices_.erase( + std::remove_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; } + ), + currently_connecting_devices_.end() + ); + solicited = true; + } + } + } + + if (solicited) { + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(1); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + } else { + Log("Unsolicited connection for %s, closing to prevent unintended auto-reconnect.", remote_id.c_str()); + try { d.Close(); } catch(...) {} + } + } else { + // Disconnection handling - immediately remove from connected list + Log("OnConnectionStatusChanged: device %s disconnected", remote_id.c_str()); + + ClearDeviceResources(remote_id); + + { + std::lock_guard lock(devices_mutex_); + + // Remove device from vectors first + currently_connecting_devices_.erase( + std::remove_if(currently_connecting_devices_.begin(), currently_connecting_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; } + ), + currently_connecting_devices_.end() + ); + + connected_devices_.erase( + std::remove_if(connected_devices_.begin(), connected_devices_.end(), + [&remote_id](const auto& pair) { return pair.first == remote_id; } + ), + connected_devices_.end() + ); + } + + // Close the device - similar to win_ble approach + try { + if (d) { + d.Close(); + } + } catch(...) { + Log("OnConnectionStatusChanged: error closing device %s", remote_id.c_str()); + } + + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(0); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + } + }(device); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::DiscoverServicesAsync( + std::string remote_id, + std::unique_ptr> result) { + + auto result_ptr = std::shared_ptr>(std::move(result)); + std::string error_msg; + try { + BluetoothLEDevice device = nullptr; + + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + if (!device) { error_msg = "device is disconnected"; } + else { + co_await winrt::resume_background(); + auto servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Uncached); + if (servicesResult.Status() != GattCommunicationStatus::Success) { + error_msg = "GetGattServicesAsync failed"; + } else { + flutter::EncodableList servicesList; + for (auto service : servicesResult.Services()) { + { + std::lock_guard cache_lock(gatt_cache_mutex_); + service_cache_[remote_id].push_back(service); + } + flutter::EncodableMap serviceMap; + std::string serviceUuid = utils::to_uuid_string(service.Uuid()); + serviceMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + serviceMap[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(serviceUuid); + auto charsList = std::make_shared(); + co_await PopulateCharacteristicsAsync(service, remote_id, "", charsList); + serviceMap[flutter::EncodableValue("characteristics")] = *charsList; + servicesList.push_back(serviceMap); + + auto includedResult = co_await service.GetIncludedServicesAsync(BluetoothCacheMode::Cached); + if (includedResult.Status() == GattCommunicationStatus::Success) { + for (auto includedService : includedResult.Services()) { + { + std::lock_guard cache_lock(gatt_cache_mutex_); + service_cache_[remote_id].push_back(includedService); + } + flutter::EncodableMap includedMap; + std::string includedUuid = utils::to_uuid_string(includedService.Uuid()); + includedMap[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + includedMap[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(includedUuid); + includedMap[flutter::EncodableValue("primary_service_uuid")] = flutter::EncodableValue(serviceUuid); + auto includedCharsList = std::make_shared(); + co_await PopulateCharacteristicsAsync(includedService, remote_id, serviceUuid, includedCharsList); + includedMap[flutter::EncodableValue("characteristics")] = *includedCharsList; + servicesList.push_back(includedMap); + } + } + } + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("services")] = servicesList; + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + co_await ui_thread_; + channel_->InvokeMethod("OnDiscoveredServices", std::make_unique(response)); + result_ptr->Success(flutter::EncodableValue(true)); + co_return; + } + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + if (error_msg.empty()) error_msg = "Unknown error"; + co_await ui_thread_; + result_ptr->Error("discoverServices", error_msg); +} + +void FlutterBluePlusWinrtPlugin::OnCharacteristicValueChanged(std::string remote_id, const GattCharacteristic& sender, const GattValueChangedEventArgs& args) { + [this, remote_id, sender, args, alive = is_alive_]() -> winrt::fire_and_forget { + try { + co_await ui_thread_; + if (!*alive) co_return; + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(utils::to_uuid_string(sender.Service().Uuid())); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(utils::to_uuid_string(sender.Uuid())); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(static_cast(sender.AttributeHandle())); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(utils::to_vector(args.CharacteristicValue())); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + channel_->InvokeMethod("OnCharacteristicReceived", std::make_unique(response)); + } catch(...) {} + }(); +} + +void FlutterBluePlusWinrtPlugin::OnMaxPduSizeChanged(std::string remote_id, const GattSession& sender, const IInspectable&) { + [this, remote_id, sender, alive = is_alive_]() -> winrt::fire_and_forget { + try { + co_await ui_thread_; + if (!*alive) co_return; + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("mtu")] = flutter::EncodableValue(static_cast(sender.MaxPduSize())); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue(""); + channel_->InvokeMethod("OnMtuChanged", std::make_unique(response)); + } catch(...) {} + }(); +} + +// Creates the GattSession that reports the negotiated ATT PDU size. Upstream +// never populates gatt_sessions_ / mtu_tokens_, so OnMtuChanged never fires +// and the Dart layer keeps its 23-byte default forever. Called fire-and-forget +// only after the connect result has been reported, so a slow or failing +// session creation can never block or fail the connect. MaintainConnection is +// deliberately never set: the session only observes the PDU size and must not +// hold the link open. +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::CreateGattSessionAsync( + std::string remote_id, + BluetoothLEDevice device) { + auto alive = is_alive_; + try { + co_await winrt::resume_background(); + if (!*alive || !device) co_return; + + { + std::lock_guard cache_lock(gatt_cache_mutex_); + if (gatt_sessions_.find(remote_id) != gatt_sessions_.end()) co_return; + } + + // Created outside gatt_cache_mutex_: never hold it across a co_await. + auto session = co_await GattSession::FromDeviceIdAsync(device.BluetoothDeviceId()); + if (!session) co_return; + if (!*alive) { try { session.Close(); } catch (...) {} co_return; } + + // If the device dropped during creation, ClearDeviceResources already + // ran and found nothing; storing now would leak the session. + if (device.ConnectionStatus() != BluetoothConnectionStatus::Connected) { + try { session.Close(); } catch (...) {} + co_return; + } + + auto token = session.MaxPduSizeChanged( + [this, remote_id](GattSession const& sender, IInspectable const& args) { + this->OnMaxPduSizeChanged(remote_id, sender, args); + }); + + bool stored = false; + { + std::lock_guard cache_lock(gatt_cache_mutex_); + if (gatt_sessions_.find(remote_id) == gatt_sessions_.end()) { + gatt_sessions_[remote_id] = session; + mtu_tokens_[remote_id] = token; + stored = true; + } + } + if (!stored) { + // A concurrent connect stored one first; drop ours. + try { session.MaxPduSizeChanged(token); } catch (...) {} + try { session.Close(); } catch (...) {} + co_return; + } + + // Close the disconnect/store race: a disconnect landing between the + // connected-check and the store means ClearDeviceResources missed our + // entry. Re-check and undo (ClearDeviceResources is idempotent). + bool still_connected = false; + try { still_connected = (device.ConnectionStatus() == BluetoothConnectionStatus::Connected); } catch (...) {} + if (!still_connected) { + ClearDeviceResources(remote_id); + co_return; + } + + // Emit the initial value: MaxPduSizeChanged only fires on a change, so + // a PDU negotiated before the session existed would never reach Dart. + OnMaxPduSizeChanged(remote_id, session, nullptr); + } catch (...) { + // Best-effort: without a session the Dart layer keeps the 23-byte + // default, exactly the pre-patch behavior. Never break the connect. + Log("CreateGattSessionAsync failed for %s", remote_id.c_str()); + } +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::SetNotifyValueAsync(std::shared_ptr args_ptr) { + co_await winrt::resume_background(); + flutter::EncodableMap& args = *args_ptr; + std::string remote_id = utils::from_value(&args[flutter::EncodableValue("remote_id")]); + std::string service_uuid_hint = utils::from_value(&args[flutter::EncodableValue("service_uuid")]); + std::string characteristic_uuid_hint = utils::from_value(&args[flutter::EncodableValue("characteristic_uuid")]); + std::string primary_service_uuid_str = ""; + auto it_primary = args.find(flutter::EncodableValue("primary_service_uuid")); + if (it_primary != args.end()) primary_service_uuid_str = utils::from_value(&it_primary->second); + int instance_id = utils::from_value(&args[flutter::EncodableValue("instance_id")]); + bool enable = utils::from_value(&args[flutter::EncodableValue("enable")]); + bool force_indications = false; + auto it_force = args.find(flutter::EncodableValue("force_indications")); + if (it_force != args.end()) force_indications = utils::from_value(&it_force->second); + + std::string error_string = "Unknown Error"; + bool success_event = false; + std::vector return_value = {0x00, 0x00}; + GattCharacteristic targetChar = nullptr; + std::string actual_service_uuid = service_uuid_hint; + std::string actual_char_uuid = characteristic_uuid_hint; + + try { + BluetoothLEDevice device = nullptr; + co_await ui_thread_; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + co_await winrt::resume_background(); + if (!device) { error_string = "Device not connected"; } + else { + targetChar = co_await this->GetCharacteristicInternalAsync(device, remote_id, service_uuid_hint, characteristic_uuid_hint, primary_service_uuid_str, instance_id); + if (!targetChar) { error_string = "Characteristic not found"; } + else { + actual_service_uuid = utils::to_uuid_string(targetChar.Service().Uuid()); + actual_char_uuid = utils::to_uuid_string(targetChar.Uuid()); + std::string token_key = remote_id + ":" + actual_service_uuid + ":" + actual_char_uuid + ":" + std::to_string(instance_id); + + if (enable) { + GattClientCharacteristicConfigurationDescriptorValue cccdValue = GattClientCharacteristicConfigurationDescriptorValue::None; + auto props = targetChar.CharacteristicProperties(); + bool canNotify = (static_cast(props) & static_cast(GattCharacteristicProperties::Notify)) != 0; + bool canIndicate = (static_cast(props) & static_cast(GattCharacteristicProperties::Indicate)) != 0; + if (force_indications && canIndicate) { cccdValue = GattClientCharacteristicConfigurationDescriptorValue::Indicate; return_value = {0x02, 0x00}; } + else if (canNotify) { cccdValue = GattClientCharacteristicConfigurationDescriptorValue::Notify; return_value = {0x01, 0x00}; } + else if (canIndicate) { cccdValue = GattClientCharacteristicConfigurationDescriptorValue::Indicate; return_value = {0x02, 0x00}; } + else { error_string = "Notify/Indicate not supported"; goto send_event; } + + GattCommunicationStatus status = GattCommunicationStatus::ProtocolError; + try { status = co_await targetChar.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue); } catch (...) {} + if (status != GattCommunicationStatus::Success) { + GattDescriptor cccdDescriptor = co_await GetDescriptorAsync(targetChar, "2902"); + if (cccdDescriptor) { + auto writer = winrt::Windows::Storage::Streams::DataWriter(); + writer.ByteOrder(winrt::Windows::Storage::Streams::ByteOrder::LittleEndian); + writer.WriteUInt16((cccdValue == GattClientCharacteristicConfigurationDescriptorValue::Indicate) ? 2 : 1); + auto writeResult = co_await cccdDescriptor.WriteValueWithResultAsync(writer.DetachBuffer()); + status = writeResult.Status(); + } + } + + if (status != GattCommunicationStatus::Success && (actual_char_uuid == "2a05" || actual_char_uuid == "2A05")) { + status = GattCommunicationStatus::Success; + } + + if (status == GattCommunicationStatus::Success) { + co_await ui_thread_; + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it = subscribed_characteristics_.find(token_key); + if (it != subscribed_characteristics_.end()) { + try { it->second.characteristic.as().ValueChanged(it->second.token); } catch(...) {} + subscribed_characteristics_.erase(it); + } + auto token = targetChar.ValueChanged([this, remote_id](GattCharacteristic const& sender, GattValueChangedEventArgs const& args) { + this->OnCharacteristicValueChanged(remote_id, sender, args); + }); + subscribed_characteristics_[token_key] = { targetChar, token }; + success_event = true; error_string = "GATT_SUCCESS"; + } else error_string = "Write CCCD failed: " + std::to_string((int)status); + } else { + return_value = {0x00, 0x00}; + GattCommunicationStatus status = co_await targetChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue::None); + if (status == GattCommunicationStatus::Success || actual_char_uuid == "2a05") { + co_await ui_thread_; + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it = subscribed_characteristics_.find(token_key); + if (it != subscribed_characteristics_.end()) { + try { it->second.characteristic.as().ValueChanged(it->second.token); } catch(...) {} + subscribed_characteristics_.erase(it); + } + success_event = true; error_string = "GATT_SUCCESS"; + } else error_string = "Disable CCCD failed"; + } + } + } + } catch (const std::exception& ex) { error_string = ex.what(); } + catch (...) { error_string = "Unknown Exception"; } + +send_event: + co_await ui_thread_; + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("primary_service_uuid")] = primary_service_uuid_str.empty() ? flutter::EncodableValue() : flutter::EncodableValue(primary_service_uuid_str); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(actual_service_uuid); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(actual_char_uuid); + response[flutter::EncodableValue("descriptor_uuid")] = flutter::EncodableValue("2902"); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(instance_id); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(return_value); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(success_event ? 1 : 0); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(success_event ? 0 : 1); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue(error_string); + if (channel_) channel_->InvokeMethod("OnDescriptorWritten", std::make_unique(response)); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::ReadCharacteristicAsync(flutter::EncodableMap args, std::unique_ptr> result) { + auto result_ptr = std::shared_ptr>(std::move(result)); + std::string error_msg; + try { + std::string remote_id = utils::from_value(&args[flutter::EncodableValue("remote_id")]); + std::string service_uuid_str = utils::from_value(&args[flutter::EncodableValue("service_uuid")]); + std::string characteristic_uuid_str = utils::from_value(&args[flutter::EncodableValue("characteristic_uuid")]); + int instance_id = utils::from_value(&args[flutter::EncodableValue("instance_id")]); + std::string primary_service_uuid_str = ""; + auto it_primary = args.find(flutter::EncodableValue("primary_service_uuid")); + if (it_primary != args.end()) primary_service_uuid_str = utils::from_value(&it_primary->second); + + BluetoothLEDevice device = nullptr; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + if (!device) { error_msg = "device is disconnected"; } + else { + co_await winrt::resume_background(); + GattCharacteristic targetChar = co_await this->GetCharacteristicInternalAsync(device, remote_id, service_uuid_str, characteristic_uuid_str, primary_service_uuid_str, instance_id); + if (!targetChar) { error_msg = "Characteristic not found"; } + else { + auto readResult = co_await targetChar.ReadValueAsync(BluetoothCacheMode::Uncached); + if (readResult.Status() == GattCommunicationStatus::Success) { + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(service_uuid_str); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(characteristic_uuid_str); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(instance_id); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(utils::to_vector(readResult.Value())); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + co_await ui_thread_; + channel_->InvokeMethod("OnCharacteristicReceived", std::make_unique(response)); + result_ptr->Success(flutter::EncodableValue(true)); + co_return; + } else { error_msg = "Read failed: " + std::to_string((int)readResult.Status()); } + } + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + co_await ui_thread_; + result_ptr->Error("readCharacteristic", error_msg); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::WriteCharacteristicAsync(flutter::EncodableMap args, std::unique_ptr> result) { + auto result_ptr = std::shared_ptr>(std::move(result)); + std::string error_msg; + try { + std::string remote_id = utils::from_value(&args[flutter::EncodableValue("remote_id")]); + std::string service_uuid_str = utils::from_value(&args[flutter::EncodableValue("service_uuid")]); + std::string characteristic_uuid_str = utils::from_value(&args[flutter::EncodableValue("characteristic_uuid")]); + int instance_id = utils::from_value(&args[flutter::EncodableValue("instance_id")]); + std::vector value = utils::from_value>(&args[flutter::EncodableValue("value")]); + int write_type = utils::from_value(&args[flutter::EncodableValue("write_type")]); + std::string primary_service_uuid_str = ""; + auto it_primary = args.find(flutter::EncodableValue("primary_service_uuid")); + if (it_primary != args.end()) primary_service_uuid_str = utils::from_value(&it_primary->second); + + BluetoothLEDevice device = nullptr; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + if (!device) { error_msg = "device is disconnected"; } + else { + co_await winrt::resume_background(); + GattCharacteristic targetChar = co_await this->GetCharacteristicInternalAsync(device, remote_id, service_uuid_str, characteristic_uuid_str, primary_service_uuid_str, instance_id); + if (!targetChar) { error_msg = "Characteristic not found"; } + else { + auto writer = winrt::Windows::Storage::Streams::DataWriter(); + writer.WriteBytes(value); + GattWriteOption option = (write_type == 1) ? GattWriteOption::WriteWithoutResponse : GattWriteOption::WriteWithResponse; + auto writeResult = co_await targetChar.WriteValueWithResultAsync(writer.DetachBuffer(), option); + + co_await ui_thread_; + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(service_uuid_str); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(characteristic_uuid_str); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(instance_id); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(value); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(writeResult.Status() == GattCommunicationStatus::Success ? 1 : 0); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue((int)writeResult.Status()); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue(writeResult.Status() == GattCommunicationStatus::Success ? "GATT_SUCCESS" : "Write failed"); + channel_->InvokeMethod("OnCharacteristicWritten", std::make_unique(response)); + result_ptr->Success(flutter::EncodableValue(true)); + co_return; + } + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + co_await ui_thread_; + result_ptr->Error("writeCharacteristic", error_msg); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::ReadDescriptorAsync(flutter::EncodableMap args, std::unique_ptr> result) { + auto result_ptr = std::shared_ptr>(std::move(result)); + std::string error_msg; + try { + std::string remote_id = utils::from_value(&args[flutter::EncodableValue("remote_id")]); + std::string service_uuid_hint = utils::from_value(&args[flutter::EncodableValue("service_uuid")]); + std::string characteristic_uuid_hint = utils::from_value(&args[flutter::EncodableValue("characteristic_uuid")]); + std::string descriptor_uuid_hint = utils::from_value(&args[flutter::EncodableValue("descriptor_uuid")]); + int instance_id = utils::from_value(&args[flutter::EncodableValue("instance_id")]); + std::string primary_service_uuid_str = ""; + auto it_primary = args.find(flutter::EncodableValue("primary_service_uuid")); + if (it_primary != args.end()) primary_service_uuid_str = utils::from_value(&it_primary->second); + + BluetoothLEDevice device = nullptr; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + if (!device) { error_msg = "device is disconnected"; } + else { + co_await winrt::resume_background(); + + GattDescriptor targetDesc = nullptr; + if (instance_id != 0) { + std::string d_key = remote_id + ":" + std::to_string(instance_id); + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it_d = descriptor_cache_.find(d_key); + if (it_d != descriptor_cache_.end()) targetDesc = it_d->second.as(); + } + + if (!targetDesc) { + GattCharacteristic targetChar = co_await this->GetCharacteristicByDescriptorHandleAsync(device, instance_id); + if (!targetChar) { + targetChar = co_await this->GetCharacteristicInternalAsync(device, remote_id, service_uuid_hint, characteristic_uuid_hint, primary_service_uuid_str, instance_id); + } + + if (targetChar) { + targetDesc = co_await GetDescriptorAsync(targetChar, descriptor_uuid_hint); + } + } + + if (!targetDesc) { error_msg = "Descriptor not found"; } + else { + auto readResult = co_await targetDesc.ReadValueAsync(BluetoothCacheMode::Uncached); + if (readResult.Status() == GattCommunicationStatus::Success) { + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("primary_service_uuid")] = primary_service_uuid_str.empty() ? flutter::EncodableValue() : flutter::EncodableValue(primary_service_uuid_str); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(service_uuid_hint); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(characteristic_uuid_hint); + response[flutter::EncodableValue("descriptor_uuid")] = flutter::EncodableValue(utils::to_uuid_string(targetDesc.Uuid())); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(instance_id); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(utils::to_vector(readResult.Value())); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + + co_await ui_thread_; + channel_->InvokeMethod("OnDescriptorRead", std::make_unique(response)); + result_ptr->Success(flutter::EncodableValue(true)); + co_return; + } else { error_msg = "Read failed: " + std::to_string((int)readResult.Status()); } + } + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + co_await ui_thread_; + result_ptr->Error("readDescriptor", error_msg); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::WriteDescriptorAsync(flutter::EncodableMap args, std::unique_ptr> result) { + auto result_ptr = std::shared_ptr>(std::move(result)); + std::string error_msg; + try { + std::string remote_id = utils::from_value(&args[flutter::EncodableValue("remote_id")]); + std::string service_uuid_hint = utils::from_value(&args[flutter::EncodableValue("service_uuid")]); + std::string characteristic_uuid_hint = utils::from_value(&args[flutter::EncodableValue("characteristic_uuid")]); + std::string descriptor_uuid_hint = utils::from_value(&args[flutter::EncodableValue("descriptor_uuid")]); + std::vector value = utils::from_value>(&args[flutter::EncodableValue("value")]); + int instance_id = utils::from_value(&args[flutter::EncodableValue("instance_id")]); + std::string primary_service_uuid_str = ""; + auto it_primary = args.find(flutter::EncodableValue("primary_service_uuid")); + if (it_primary != args.end()) primary_service_uuid_str = utils::from_value(&it_primary->second); + + BluetoothLEDevice device = nullptr; + { + std::lock_guard lock(devices_mutex_); + auto it = std::find_if(connected_devices_.begin(), connected_devices_.end(), [&](const auto& pair) { return pair.first == remote_id; }); + if (it != connected_devices_.end()) device = it->second.as(); + } + if (!device) { error_msg = "device is disconnected"; } + else { + co_await winrt::resume_background(); + + GattDescriptor targetDesc = nullptr; + if (instance_id != 0) { + std::string d_key = remote_id + ":" + std::to_string(instance_id); + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it_d = descriptor_cache_.find(d_key); + if (it_d != descriptor_cache_.end()) targetDesc = it_d->second.as(); + } + + if (!targetDesc) { + GattCharacteristic targetChar = co_await this->GetCharacteristicInternalAsync(device, remote_id, service_uuid_hint, characteristic_uuid_hint, primary_service_uuid_str, instance_id); + if (targetChar) { + targetDesc = co_await GetDescriptorAsync(targetChar, descriptor_uuid_hint); + } + } + + if (!targetDesc) { error_msg = "Descriptor not found"; } + else { + auto writer = winrt::Windows::Storage::Streams::DataWriter(); + writer.WriteBytes(value); + auto writeResult = co_await targetDesc.WriteValueWithResultAsync(writer.DetachBuffer()); + if (writeResult.Status() == GattCommunicationStatus::Success) { + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("primary_service_uuid")] = primary_service_uuid_str.empty() ? flutter::EncodableValue() : flutter::EncodableValue(primary_service_uuid_str); + response[flutter::EncodableValue("service_uuid")] = flutter::EncodableValue(service_uuid_hint); + response[flutter::EncodableValue("characteristic_uuid")] = flutter::EncodableValue(characteristic_uuid_hint); + response[flutter::EncodableValue("descriptor_uuid")] = flutter::EncodableValue(utils::to_uuid_string(targetDesc.Uuid())); + response[flutter::EncodableValue("instance_id")] = flutter::EncodableValue(instance_id); + response[flutter::EncodableValue("value")] = flutter::EncodableValue(value); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + + co_await ui_thread_; + channel_->InvokeMethod("OnDescriptorWritten", std::make_unique(response)); + result_ptr->Success(flutter::EncodableValue(true)); + co_return; + } else { error_msg = "Write failed: " + std::to_string((int)writeResult.Status()); } + } + } + } catch (const std::exception& e) { error_msg = e.what(); } + catch (...) { error_msg = "Unknown error"; } + + co_await ui_thread_; + result_ptr->Error("writeDescriptor", error_msg); +} + +void FlutterBluePlusWinrtPlugin::ClearDeviceResources(std::string remote_id) { + // Guards every cache touched below against concurrent background-thread + // access (service discovery / read / write). This function performs no + // co_await, so holding the lock for its whole body is safe. + std::lock_guard cache_lock(gatt_cache_mutex_); + + for (auto it = subscribed_characteristics_.begin(); it != subscribed_characteristics_.end(); ) { + if (it->first.find(remote_id) == 0) { + try { + auto characteristic = it->second.characteristic.as(); + if (characteristic) characteristic.ValueChanged(it->second.token); + } catch (...) {} + it = subscribed_characteristics_.erase(it); + } else { + ++it; + } + } + + for (auto it = characteristic_cache_.begin(); it != characteristic_cache_.end(); ) { + if (it->first.find(remote_id) == 0) it = characteristic_cache_.erase(it); + else ++it; + } + for (auto it = descriptor_cache_.begin(); it != descriptor_cache_.end(); ) { + if (it->first.find(remote_id) == 0) it = descriptor_cache_.erase(it); + else ++it; + } + + auto it_s = service_cache_.find(remote_id); + if (it_s != service_cache_.end()) { + for (auto& inspectable : it_s->second) { + try { + auto service = inspectable.as(); + if (service) service.Close(); + } catch (...) {} + } + service_cache_.erase(it_s); + } + + // Cleanup sessions and MTU tokens + auto it_gs = gatt_sessions_.find(remote_id); + if (it_gs != gatt_sessions_.end()) { + try { + auto session = it_gs->second.as(); + auto it_mtu = mtu_tokens_.find(remote_id); + if (it_mtu != mtu_tokens_.end()) { + session.MaxPduSizeChanged(it_mtu->second); + mtu_tokens_.erase(it_mtu); + } + session.Close(); + } catch(...) {} + gatt_sessions_.erase(it_gs); + } + + rssi_cache_.erase(remote_id); + + // The device is Closed by the caller in the same disconnect flow, so the + // handler stops firing; just drop the token entry to keep the map bounded. + connection_tokens_.erase(remote_id); +} + +winrt::fire_and_forget FlutterBluePlusWinrtPlugin::PeriodicConnectionCheck() { + // Copy the shared alive flag into the coroutine frame so it stays valid even + // after the plugin object is destroyed. Check it right after every resume, + // before touching any `this` member. + auto alive = is_alive_; + while (*alive) { + co_await winrt::resume_after(winrt::Windows::Foundation::TimeSpan(20000000)); + if (!*alive) co_return; + co_await ui_thread_; + if (!*alive) co_return; + + std::vector mac_to_remove; + { + std::lock_guard lock(devices_mutex_); + for (size_t i = 0; i < connected_devices_.size(); ++i) { + const auto& pair = connected_devices_[i]; + std::string remote_id = pair.first; + auto device = pair.second.as(); + bool is_connected = false; + try { if (device) is_connected = (device.ConnectionStatus() == BluetoothConnectionStatus::Connected); } catch (...) {} + if (!is_connected) { + Log("PeriodicCheck: Device %s disconnected, marking for removal.", remote_id.c_str()); + mac_to_remove.push_back(remote_id); + } + } + } + + for (const auto& remote_id : mac_to_remove) { + ClearDeviceResources(remote_id); + if (channel_) { + flutter::EncodableMap connection_state; + connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(0); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + } + + std::vector to_close; + { + std::lock_guard lock(devices_mutex_); + auto it = connected_devices_.begin(); + while (it != connected_devices_.end()) { + if (it->first == remote_id) { + try { auto d = it->second.as(); if (d) to_close.push_back(d); } catch(...) {} + it = connected_devices_.erase(it); + } else { + ++it; + } + } + } + + for (auto& d : to_close) { try { d.Close(); } catch(...) {} } + } + } +} + +void FlutterBluePlusWinrtPlugin::HandleMethodCall(const flutter::MethodCall& method_call, std::unique_ptr> result) { + const auto& method = method_call.method_name(); + if (method == "flutterRestart") { + int count = 0; + watcher_.Stop(); + + std::vector to_close; + std::vector devices_to_clear; + { + std::lock_guard lock(devices_mutex_); + count = static_cast(connected_devices_.size()); + + for (size_t i = 0; i < connected_devices_.size(); ++i) { + const auto& pair = connected_devices_[i]; + try { if (auto device = pair.second.as()) to_close.push_back(device); } catch(...) {} + devices_to_clear.push_back(pair.first); + } + for (size_t i = 0; i < currently_connecting_devices_.size(); ++i) { + const auto& pair = currently_connecting_devices_[i]; + try { if (auto device = pair.second.as()) to_close.push_back(device); } catch(...) {} + } + + connected_devices_.clear(); + currently_connecting_devices_.clear(); + } + + for (const auto& remote_id : devices_to_clear) { + ClearDeviceResources(remote_id); + } + + { + std::lock_guard cache_lock(gatt_cache_mutex_); + rssi_cache_.clear(); + scan_results_cache_.clear(); + subscribed_characteristics_.clear(); + characteristic_cache_.clear(); + descriptor_cache_.clear(); + service_cache_.clear(); + } + + for (auto& d : to_close) { try { d.Close(); } catch(...) {} } + + result->Success(flutter::EncodableValue(count)); return; + } + if (method == "startScan") { scan_results_cache_.clear(); watcher_.Start(); result->Success(flutter::EncodableValue(true)); return; } + if (method == "stopScan") { watcher_.Stop(); result->Success(flutter::EncodableValue(true)); return; } + if (method == "getSystemDevices") { GetSystemDevicesAsync(std::move(result)); return; } + if (method == "getAdapterState") { GetAdapterStateAsync(std::move(result)); return; } + if (method == "connect") { + const auto* args = std::get_if(method_call.arguments()); + std::string remote_id = ""; if (args) { auto it = args->find(flutter::EncodableValue("remote_id")); if (it != args->end()) remote_id = utils::from_value(&it->second); } + ConnectAsync(remote_id, std::move(result)); return; + } + if (method == "disconnect") { + const auto* remote_id_val_ptr = std::get_if(method_call.arguments()); + if (remote_id_val_ptr) { + std::string remote_id = *remote_id_val_ptr; + + std::vector to_close; + + { + std::lock_guard lock(devices_mutex_); + { + auto it = currently_connecting_devices_.begin(); + while (it != currently_connecting_devices_.end()) { + if (it->first == remote_id) { + try { if (auto device = it->second.as()) to_close.push_back(device); } catch(...) {} + it = currently_connecting_devices_.erase(it); + } else { + ++it; + } + } + } + + { + auto it = connected_devices_.begin(); + while (it != connected_devices_.end()) { + if (it->first == remote_id) { + try { if (auto device = it->second.as()) to_close.push_back(device); } catch(...) {} + it = connected_devices_.erase(it); + } else { + ++it; + } + } + } + } + + for (auto& d : to_close) { try { d.Close(); } catch(...) {} } + + ClearDeviceResources(remote_id); + + flutter::EncodableMap connection_state; connection_state[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); connection_state[flutter::EncodableValue("connection_state")] = flutter::EncodableValue(0); + channel_->InvokeMethod("OnConnectionStateChanged", std::make_unique(connection_state)); + } + result->Success(flutter::EncodableValue(true)); return; + } + if (method == "discoverServices") { + const auto* remote_id_val = std::get_if(method_call.arguments()); + if (remote_id_val) DiscoverServicesAsync(*remote_id_val, std::move(result)); + else result->Error("discoverServices", "Invalid arguments"); + return; + } + if (method == "setNotifyValue") { + const auto* args = std::get_if(method_call.arguments()); + if (args) { auto args_ptr = std::make_shared(*args); result->Success(flutter::EncodableValue(true)); SetNotifyValueAsync(args_ptr); } + else result->Error("setNotifyValue", "Invalid arguments"); + return; + } + if (method == "readCharacteristic") { + const auto* args = std::get_if(method_call.arguments()); + if (args) ReadCharacteristicAsync(*args, std::move(result)); else result->Error("readCharacteristic", "Invalid arguments"); + return; + } + if (method == "writeCharacteristic") { + const auto* args = std::get_if(method_call.arguments()); + if (args) WriteCharacteristicAsync(*args, std::move(result)); else result->Error("writeCharacteristic", "Invalid arguments"); + return; + } + if (method == "readDescriptor") { + const auto* args = std::get_if(method_call.arguments()); + if (args) ReadDescriptorAsync(*args, std::move(result)); else result->Error("readDescriptor", "Invalid arguments"); + return; + } + if (method == "writeDescriptor") { + const auto* args = std::get_if(method_call.arguments()); + if (args) WriteDescriptorAsync(*args, std::move(result)); else result->Error("writeDescriptor", "Invalid arguments"); + return; + } + if (method == "setLogLevel") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "setOptions") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "isSupported") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "requestMtu") { + const auto* args = std::get_if(method_call.arguments()); + std::string remote_id = ""; + if (args) { + auto it = args->find(flutter::EncodableValue("remote_id")); + if (it != args->end()) remote_id = utils::from_value(&it->second); + } + if (!remote_id.empty()) { + winrt::Windows::Foundation::IInspectable session_obj = nullptr; + { + std::lock_guard cache_lock(gatt_cache_mutex_); + auto it = gatt_sessions_.find(remote_id); + if (it != gatt_sessions_.end()) session_obj = it->second; + } + if (session_obj) { + auto session = session_obj.as(); + flutter::EncodableMap response; + response[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + response[flutter::EncodableValue("mtu")] = flutter::EncodableValue(static_cast(session.MaxPduSize())); + response[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + response[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + response[flutter::EncodableValue("error_string")] = flutter::EncodableValue(""); + channel_->InvokeMethod("OnMtuChanged", std::make_unique(response)); + } + } + result->Success(flutter::EncodableValue(true)); + return; + } + if (method == "requestConnectionPriority") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "setPreferredPhy") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "turnOn") { result->Success(flutter::EncodableValue(false)); return; } + if (method == "turnOff") { result->Success(flutter::EncodableValue(false)); return; } + if (method == "clearGattCache") { result->Success(flutter::EncodableValue(true)); return; } + if (method == "getPhySupport") { + flutter::EncodableMap response; + response[flutter::EncodableValue("le_2m")] = flutter::EncodableValue(true); + response[flutter::EncodableValue("le_coded")] = flutter::EncodableValue(true); + result->Success(flutter::EncodableValue(response)); + return; + } + if (method == "createBond") { + const auto* args = std::get_if(method_call.arguments()); + std::string remote_id = ""; if (args) { auto it = args->find(flutter::EncodableValue("remote_id")); if (it != args->end()) remote_id = utils::from_value(&it->second); } + CreateBondAsync(remote_id, std::move(result)); return; + } + if (method == "removeBond") { + const auto* remote_id_val = std::get_if(method_call.arguments()); + if (remote_id_val) RemoveBondAsync(*remote_id_val, std::move(result)); + else result->Error("removeBond", "Invalid arguments"); + return; + } + if (method == "getBondState") { + const auto* remote_id_val = std::get_if(method_call.arguments()); + if (remote_id_val) GetBondStateAsync(*remote_id_val, std::move(result)); + else result->Error("getBondState", "Invalid arguments"); + return; + } + if (method == "getBondedDevices") { + GetBondedDevicesAsync(std::move(result)); + return; + } + if (method == "connectedCount") { + int count = 0; + { + std::lock_guard lock(devices_mutex_); + count = static_cast(connected_devices_.size()); + } + result->Success(flutter::EncodableValue(count)); + return; + } + if (method == "readRssi") { + const auto* remote_id_arg = std::get_if(method_call.arguments()); + if (remote_id_arg) { + std::string remote_id = *remote_id_arg; + flutter::EncodableMap rssi_result; + rssi_result[flutter::EncodableValue("remote_id")] = flutter::EncodableValue(remote_id); + rssi_result[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + rssi_result[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + + auto it = rssi_cache_.find(remote_id); + if (it != rssi_cache_.end()) { + rssi_result[flutter::EncodableValue("rssi")] = flutter::EncodableValue(it->second); + } else { + rssi_result[flutter::EncodableValue("rssi")] = flutter::EncodableValue(0); + } + rssi_result[flutter::EncodableValue("success")] = flutter::EncodableValue(1); + rssi_result[flutter::EncodableValue("error_code")] = flutter::EncodableValue(0); + rssi_result[flutter::EncodableValue("error_string")] = flutter::EncodableValue("GATT_SUCCESS"); + channel_->InvokeMethod("OnReadRssi", std::make_unique(rssi_result)); + result->Success(flutter::EncodableValue(true)); + } else result->Error("readRssi", "Invalid arguments"); + return; + } + + result->NotImplemented(); +} + +} // namespace flutter_blue_plus_winrt diff --git a/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.h b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.h new file mode 100644 index 00000000..4112cb52 --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin.h @@ -0,0 +1,227 @@ +#ifndef FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_ +#define FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace flutter_blue_plus_winrt { + +struct SubscribedCharacteristic { + winrt::Windows::Foundation::IInspectable characteristic = nullptr; + winrt::event_token token; +}; + +class FlutterBluePlusWinrtPlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FlutterBluePlusWinrtPlugin(flutter::PluginRegistrarWindows* registrar); + + ~FlutterBluePlusWinrtPlugin(); + + // Disallow copy and assign. + FlutterBluePlusWinrtPlugin(const FlutterBluePlusWinrtPlugin&) = delete; + FlutterBluePlusWinrtPlugin& operator=(const FlutterBluePlusWinrtPlugin&) = delete; + + private: + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); + + flutter::PluginRegistrarWindows* registrar_; + std::unique_ptr> channel_; + + winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher watcher_{}; + winrt::event_token received_token_{}; + winrt::event_token stopped_token_{}; + + // Shared "alive" flag. Held by a shared_ptr so that fire-and-forget + // coroutines / event handlers can capture a copy and safely check whether + // the plugin has been destroyed after resuming, instead of dereferencing a + // dangling `this`. + std::shared_ptr> is_alive_ = std::make_shared>(true); + + // UI Thread context + winrt::apartment_context ui_thread_; + + std::mutex devices_mutex_; + std::vector> connected_devices_{}; + std::vector> currently_connecting_devices_{}; + std::map rssi_cache_{}; + + std::map> scan_results_cache_{}; + + // Map to store event tokens and characteristic objects for notifications + std::map subscribed_characteristics_{}; + + // Guards the GATT object caches below (characteristic_cache_, + // descriptor_cache_, service_cache_, subscribed_characteristics_, + // gatt_sessions_, mtu_tokens_, connection_tokens_). These are accessed both + // from background thread-pool continuations (service discovery / read / + // write) and from the UI thread (ClearDeviceResources on disconnect), so + // every access must hold this mutex. NOTE: never hold this across a + // `co_await`. + std::mutex gatt_cache_mutex_; + + // Caches for GATT objects to avoid repeated discovery + std::map characteristic_cache_{}; + std::map descriptor_cache_{}; + std::map> service_cache_{}; + + // MTU / Session Handling + std::map gatt_sessions_{}; + std::map mtu_tokens_{}; + + // Per-device ConnectionStatusChanged event tokens, so the handlers can be + // revoked (in ClearDeviceResources and the destructor) and never fire into a + // destroyed plugin. Guarded by gatt_cache_mutex_. + std::map connection_tokens_{}; + + void OnAdvertisementReceived( + const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher&, + const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementReceivedEventArgs&); + + void OnAdvertisementStopped( + const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher&, + const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcherStoppedEventArgs&); + + winrt::fire_and_forget GetSystemDevicesAsync( + std::unique_ptr> result); + + winrt::fire_and_forget GetAdapterStateAsync( + std::unique_ptr> result); + + winrt::fire_and_forget GetBondedDevicesAsync( + std::unique_ptr> result); + + winrt::fire_and_forget CreateBondAsync( + std::string remote_id, + std::unique_ptr> result); + + winrt::fire_and_forget RemoveBondAsync( + std::string remote_id, + std::unique_ptr> result); + + winrt::fire_and_forget GetBondStateAsync( + std::string remote_id, + std::unique_ptr> result); + + winrt::fire_and_forget ConnectAsync( + std::string remote_id, + std::unique_ptr> result); + + winrt::fire_and_forget DiscoverServicesAsync( + std::string remote_id, + std::unique_ptr> result); + + winrt::fire_and_forget SetNotifyValueAsync( + std::shared_ptr args); + + winrt::fire_and_forget ReadCharacteristicAsync( + flutter::EncodableMap args, + std::unique_ptr> result); + + winrt::fire_and_forget WriteCharacteristicAsync( + flutter::EncodableMap args, + std::unique_ptr> result); + + winrt::fire_and_forget ReadDescriptorAsync( + flutter::EncodableMap args, + std::unique_ptr> result); + + winrt::fire_and_forget WriteDescriptorAsync( + flutter::EncodableMap args, + std::unique_ptr> result); + + void OnConnectionStatusChanged( + const winrt::Windows::Devices::Bluetooth::BluetoothLEDevice&, + const winrt::Windows::Foundation::IInspectable&); + + void OnCharacteristicValueChanged( + std::string remote_id, + const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic& sender, + const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs& args); + + void OnMaxPduSizeChanged( + std::string remote_id, + const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession& sender, + const winrt::Windows::Foundation::IInspectable& args); + + winrt::fire_and_forget CreateGattSessionAsync( + std::string remote_id, + winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device); + + winrt::fire_and_forget PeriodicConnectionCheck(); + + std::string uint64_to_mac_string(uint64_t addr); + + // --- Private GATT Helpers --- + winrt::Windows::Foundation::IAsyncOperation + GetCharacteristicInternalAsync( + winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device, + std::string remote_id, + std::string service_uuid_str, + std::string characteristic_uuid_str, + std::string primary_service_uuid_str, + int instance_id); + + winrt::Windows::Foundation::IAsyncOperation + GetCharacteristicByHandleAsync( + winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device, + int instance_id); + + winrt::Windows::Foundation::IAsyncOperation + GetCharacteristicAsync( + winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device, + std::string service_uuid_str, + std::string characteristic_uuid_str, + std::string primary_service_uuid_str, + int instance_id); + + winrt::Windows::Foundation::IAsyncOperation + FindCharacteristicInServiceAsync( + winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service, + int instance_id, + winrt::Windows::Devices::Bluetooth::BluetoothCacheMode cacheMode); + + winrt::Windows::Foundation::IAsyncOperation + FindCharacteristicByDescriptorHandleInServiceAsync( + winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service, + int descriptor_handle, + winrt::Windows::Devices::Bluetooth::BluetoothCacheMode cacheMode); + + winrt::Windows::Foundation::IAsyncOperation + GetCharacteristicByDescriptorHandleAsync( + winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device, + int descriptor_handle); + + winrt::Windows::Foundation::IAsyncOperation + GetDescriptorAsync( + winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic characteristic, + std::string descriptor_uuid_str); + + winrt::Windows::Foundation::IAsyncAction PopulateCharacteristicsAsync( + winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service, + std::string remote_id, + std::string primaryServiceUuid, + std::shared_ptr outList); + + void ClearDeviceResources(std::string remote_id); +}; + +} // namespace flutter_blue_plus_winrt + +#endif // FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_ diff --git a/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin_c_api.cpp b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin_c_api.cpp new file mode 100644 index 00000000..8866882f --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/flutter_blue_plus_winrt_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h" + +#include + +#include "flutter_blue_plus_winrt_plugin.h" + +void FlutterBluePlusPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + flutter_blue_plus_winrt::FlutterBluePlusWinrtPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/flutter_blue_plus_winrt/windows/include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h b/packages/flutter_blue_plus_winrt/windows/include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h new file mode 100644 index 00000000..1306e8cc --- /dev/null +++ b/packages/flutter_blue_plus_winrt/windows/include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FlutterBluePlusPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_ diff --git a/play/1.5.0-beta.1.txt b/play/1.5.0-beta.1.txt new file mode 100644 index 00000000..f0adc26b --- /dev/null +++ b/play/1.5.0-beta.1.txt @@ -0,0 +1,3 @@ +Offband Meshcore 1.5.0-beta.1 (closed test) + +A testing build of the 1.5.0 line. New: an Experimental section unlocked by a 7-tap on the Build row, with OKIMesh CoreScope (per-packet observer counts from OKIMesh's service) inside it. Note it needs a forthcoming Offband firmware and stays inert until then. Also a new About screen with website, Play, and donate links, plus repeater CLI and broker import fixes. Bug reports welcome. diff --git a/play/1.6.0.txt b/play/1.6.0.txt new file mode 100644 index 00000000..574f2f0b --- /dev/null +++ b/play/1.6.0.txt @@ -0,0 +1,3 @@ +Offband Meshcore 1.6.0 + +Our biggest update yet. Contacts are reworked: tap a contact shared on a channel to add it, share your own contact into a channel, add by public key or QR, and swap contacts with stock MeshCore. Move a radio's setup with stock-compatible config export and import, and your identity too. New region radio presets. And a short contact sync now recovers itself automatically and tells you what came back. Plus an About screen and top-of-screen notifications. diff --git a/pubspec.lock b/pubspec.lock index 2add0a53..cb564804 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -420,11 +420,9 @@ packages: flserial: dependency: "direct main" description: - path: "." - ref: "48216310061efc8d5d217cc18014fc2cb501646e" - resolved-ref: "48216310061efc8d5d217cc18014fc2cb501646e" - url: "https://github.com/MeshEnvy/flserial.git" - source: git + path: "packages/flserial" + relative: true + source: path version: "0.3.5" flutter: dependency: "direct main" @@ -440,13 +438,12 @@ packages: source: hosted version: "2.2.3" flutter_blue_plus_android: - dependency: transitive + dependency: "direct overridden" description: - name: flutter_blue_plus_android - sha256: d66bdcb0438e643d5de4af914851bdf7322448384795666efe92236626484740 - url: "https://pub.dev" - source: hosted - version: "8.2.2" + path: "packages/flutter_blue_plus_android" + relative: true + source: path + version: "8.2.2+offband.1" flutter_blue_plus_darwin: dependency: transitive description: @@ -456,12 +453,11 @@ packages: source: hosted version: "8.2.2" flutter_blue_plus_linux: - dependency: transitive + dependency: "direct overridden" description: - name: flutter_blue_plus_linux - sha256: c08563ccef620be5a06dd6b895ee51ecd986d1fcab1edd2dbc3fa125518abb21 - url: "https://pub.dev" - source: hosted + path: "packages/flutter_blue_plus_linux" + relative: true + source: path version: "8.2.2" flutter_blue_plus_platform_interface: dependency: "direct main" @@ -480,13 +476,12 @@ packages: source: hosted version: "8.2.3" flutter_blue_plus_winrt: - dependency: transitive + dependency: "direct overridden" description: - name: flutter_blue_plus_winrt - sha256: dce19eb095c5ed70de997c02911afd255d867627fceff9c68c6f8b88792d597e - url: "https://pub.dev" - source: hosted - version: "0.0.19" + path: "packages/flutter_blue_plus_winrt" + relative: true + source: path + version: "0.0.20+offband.1" flutter_cache_manager: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 4fb20432..c34e5ee2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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: 1.4.0+65 +version: 1.6.0+67 environment: sdk: ^3.9.2 @@ -38,11 +38,11 @@ dependencies: # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 flutter_blue_plus: ^2.1.0 - # TODO: Switch to official flserial repo once changes are upstreamed + # Vendored from MeshEnvy/flserial 48216310061efc8d5d217cc18014fc2cb501646e + # (MIT) so its native serial buffering can be fixed: the 8 KB input ring + # overwrote bytes during a contact sync burst (#702, #704). flserial: - git: - url: https://github.com/MeshEnvy/flserial.git - ref: 48216310061efc8d5d217cc18014fc2cb501646e + path: packages/flserial provider: ^6.1.5+1 shared_preferences: ^2.2.2 uuid: ^4.3.3 @@ -98,6 +98,25 @@ hooks: android-x64: backends: [cpu] +# Both BLE platform implementations are vendored, each a pristine import first +# with its patch as a separate commit for reviewability. +# +# android: patched to close leaked BluetoothGatt handles (#694). +# winrt: patched to create the GattSession on connect, so Windows reports the +# negotiated MTU. No published version does, which left the Dart cache +# at the 23-byte default and capped the composer at 0-4 bytes, reading +# as a dead keyboard (#592, fix tracked in #686). +# linux: patched to report the negotiated MTU from BlueZ. Upstream returns an +# empty stream, so the MTU never reached Dart and the composer was +# capped at 0 bytes, the same end state as Windows (#717). +dependency_overrides: + flutter_blue_plus_android: + path: packages/flutter_blue_plus_android + flutter_blue_plus_linux: + path: packages/flutter_blue_plus_linux + flutter_blue_plus_winrt: + path: packages/flutter_blue_plus_winrt + dev_dependencies: flutter_test: sdk: flutter @@ -127,6 +146,7 @@ flutter: assets: - assets/images/ - assets/icons/ + - assets/radio_presets/ flutter_launcher_icons: android: true diff --git a/release-notes/1.5.0-beta.1.md b/release-notes/1.5.0-beta.1.md new file mode 100644 index 00000000..50e43e9d --- /dev/null +++ b/release-notes/1.5.0-beta.1.md @@ -0,0 +1,34 @@ +## Offband Meshcore 1.5.0-beta.1 + +First beta of the 1.5.0 line, for the closed test track. This is a testing build, +so features here are still being proven. Bug reports are what make the production +releases solid. + +### New to test + +- **Experimental section.** A hidden **7-tap on the Build row** in settings unlocks + an Experimental area. Turning the section off again clears every experimental + toggle (#509, #553). +- **OKIMesh CoreScope (Experimental).** See how many **OKIMesh CoreScope** observers + heard each packet: an observer / observations badge with adaptive polling and tap + or long-press to refresh (#549, #550). This is tied specifically to OKIMesh's + CoreScope service, not a generic or self-hosted backend. + - **Heads-up:** it needs a **forthcoming Offband firmware** (0xC6 support, firmware + ver code 22 or newer, tracked in #611) that is **not yet available for download**. + Until you are on that firmware it stays inert. This is here so it is ready to test + the moment the firmware ships. +- **About screen.** About now lives in its own Settings category, with links out to + the website, the Play listing, and the donate page (#526, #527). + +### Fixed + +- **Repeater CLI** is steadier: late replies are surfaced instead of dropped, + commands have their own timeout budget, the reported timeout window matches what + was actually armed, and a prefixed reply only completes the command that owns the + prefix (#528, #529, #531, #532, #533). +- **Broker import** never flips the broker enabled state, and a blank-field GET no + longer leaks the echoed key line (#469, #470). +- **Channel "Send Again"** is gated correctly on the repeat count (#555). + +Thanks for testing. If something acts weird, that is exactly what this track is for, +and your reports keep production solid for everyone. diff --git a/release-notes/1.6.0.md b/release-notes/1.6.0.md new file mode 100644 index 00000000..75bb0733 --- /dev/null +++ b/release-notes/1.6.0.md @@ -0,0 +1,87 @@ +## Offband Meshcore 1.6.0 + +The first stable release of the 1.5.0 line and the production successor to 1.4.0. One +of our largest releases: a full contacts overhaul, stock-compatible config and identity +portability, region radio presets, self-healing contact sync, and a deep pass on +Bluetooth reliability. Over 100 changes since the 1.5.0 beta. + +### Contacts, reworked + +- Tap a **contact shared on a channel** to add it, from an inline **Add Contact** card + (#610), and **share your own contact into a channel** from the + picker (#611). +- **Contact QR**: show your contact as a QR and scan someone else's to add them, + reachable from the contacts menu or the key field (#629). +- **Add by public key**: type or paste a key (#628), or add from a key alone before + any advert arrives (#627). +- **Cross-client with stock MeshCore**: Offband parses and emits the stock + contact-share URI, so contacts move both ways between Offband and stock (#625, #626), + and pasted shares in our own channel format are accepted too (#611). +- Each contact shows **how far its identity is confirmed** (#630), and names are + handled correctly on the wire (no truncation mid-character) (#636). +- **Channel senders**: add, view, or block a sender from an avatar tap or long-press, + with clear messaging when a name is unknown or an add fails (#565). + +### Bring your setup with you + +- **Stock-compatible config export and import**: move a radio's full configuration in + and out in the exact format stock MeshCore uses, wired into Settings + (#572, #573, #574, #575, #576). +- **Identity export/import** for your connector, with an auto-add hop limit (#578). + +### Radio presets + +- A **preset picker grouped by region** and labeled by source, crediting Liam Cottle / + MeshCore for the upstream presets (#727, #728, #729, #731). +- Apply a preset's path hash to a **companion, observer, repeater, or room server** + (#730, #735, #649), with the picker built into repeater and room-server settings + (#734). Region matching accounts for the path-hash mode, so a USA radio is not + mislabeled as Canada (#747). + +### Sync that heals itself + +- Offband **detects a short contact sync and recovers it** with paced, capped + re-syncs and per-key checks, then shows a banner with the recovered count and which + contacts are genuinely gone (#762, #763, #764, #674). +- A short or unreadable sync **never overwrites your saved contacts** (#671, #673), a + silent contact stream ends on its own after 30 seconds (#672), and only one contact + request runs at a time (#672). +- **Apply a remote radio setting temporarily** (tempradio) (#662), and **manage a + sensor like a repeater** (#745). + +### Bluetooth reliability + +- The composer is no longer locked by an unreported BLE MTU. Offband reports the + negotiated MTU on **Linux** (#717) and **Windows** (through a vendored BLE plugin + with live MTU updates) (#686), and lifts the floor that locked it on **web** (#718). + If a link genuinely cannot carry a message, it explains why instead of showing a + dead field (#684). +- Sturdier connects and disconnects: bounded GATT-133 retry with readable errors + (#698), an unconfirmed disconnect now retries and warns instead of being swallowed + (#697), and leaked GATT handles are closed (#696). +- USB serial no longer drops bytes: mutexes initialize before the reader runs, and + each callback drains fully (#710, #711). + +### Delivery and messaging fixes + +- Delivered direct messages are no longer marked failed: send correlation adopts the + radio's own ACK hash (#581). +- Late repeater replies go to the app log, not your screen (#589). + +### Also new since 1.4.0 (the 1.5.0 beta groundwork) + +- An **Experimental section** unlocked by a 7-tap on the Build row; disabling it clears + every experimental toggle (#509, #553). +- **OKIMesh CoreScope** (Experimental): per-packet observer counts from OKIMesh's + CoreScope service. It needs forthcoming Offband firmware and stays inert until then, + and now cleanly distinguishes not-found from unreachable (#549, #550, #678). +- An **About screen** in its own Settings category (#526, #527), **top-of-screen + toast** notifications announced to screen readers (#638), and a refreshed **web + identity** (#608). + +### Known issues + +- On Windows, BLE Disconnect can still leave the radio held by the OS until you replug + (#688). + +Offband is open source and always will be. If you would like to help keep it going, +there is a donation page at https://offband.org/donate. Thank you for being part of it. diff --git a/test/connector/build_update_contact_path_frame_test.dart b/test/connector/build_update_contact_path_frame_test.dart index 65cbf506..9b76c2de 100644 --- a/test/connector/build_update_contact_path_frame_test.dart +++ b/test/connector/build_update_contact_path_frame_test.dart @@ -155,4 +155,69 @@ void main() { expect(lonBytes.getInt32(0, Endian.little), (-123.123456 * 1e6).round()); }); }); + + group('last_advert_timestamp for key-only adds (#627)', () { + // 1 cmd + 32 pubKey + 1 type + 1 flags + 1 pathLen + 64 path + 32 name. + const int advertTsOffset = 132; + + int advertTs(Uint8List frame) => ByteData.sublistView( + frame, + advertTsOffset, + advertTsOffset + 4, + ).getUint32(0, Endian.little); + + test('a key-only add writes zero, not the current time', () { + // The whole point. The firmware discards any advert whose timestamp is + // <= this value as a replay attack (BaseChatMesh.cpp:142-145), and + // advert timestamps come from the SENDER's clock. Writing "now" here + // would leave a key-added contact permanently deaf to its own adverts. + final frame = buildUpdateContactPathFrame( + pubKey, + Uint8List(0), + -1, + name: 'Bob', + lastAdvert: DateTime.fromMillisecondsSinceEpoch(0), + ); + expect(advertTs(frame), 0); + }); + + test( + 'omitting lastAdvert still stamps now, so path updates are unchanged', + () { + final before = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final frame = buildUpdateContactPathFrame(pubKey, path, 1); + final after = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + expect(advertTs(frame), greaterThanOrEqualTo(before)); + expect(advertTs(frame), lessThanOrEqualTo(after)); + }, + ); + + test('a pre-epoch value clamps to zero rather than wrapping', () { + // writeUInt32LE on a negative would wrap to a huge timestamp, which is + // the worst possible value for the replay guard. + final frame = buildUpdateContactPathFrame( + pubKey, + Uint8List(0), + -1, + lastAdvert: DateTime.fromMillisecondsSinceEpoch(-86400000), + ); + expect(advertTs(frame), 0); + }); + + test('a key-only add is a full-length frame with the flood sentinel', () { + // The firmware guard is only `len >= 36`, but updateContactFromFrame + // reads through offset 136 regardless (MyMesh.cpp:295-318), so a short + // frame would have it read past what we sent. Never trim this. + final frame = buildUpdateContactPathFrame( + pubKey, + Uint8List(0), + -1, + name: 'Bob', + lastAdvert: DateTime.fromMillisecondsSinceEpoch(0), + ); + expect(frame.length, greaterThanOrEqualTo(baseFrameLength)); + expect(frame[pathLenOffset], 0xFF); + }); + }); } diff --git a/test/connector/caplog_reassembler_test.dart b/test/connector/caplog_reassembler_test.dart index 28352024..c4730c7a 100644 --- a/test/connector/caplog_reassembler_test.dart +++ b/test/connector/caplog_reassembler_test.dart @@ -113,4 +113,27 @@ void main() { expect(end.bytes, Uint8List.fromList(expected)); }); }); + + group('CaplogDownload', () { + test('truncated when received < expected, and keeps the partial bytes', () { + final d = CaplogDownload( + bytes: Uint8List.fromList([1, 2, 3]), + received: 3, + expected: 10, + chunks: 2, + ); + expect(d.truncated, isTrue); + expect(d.bytes, Uint8List.fromList([1, 2, 3])); + }); + + test('not truncated when received == expected', () { + final d = CaplogDownload( + bytes: Uint8List.fromList([1, 2, 3]), + received: 3, + expected: 3, + chunks: 1, + ); + expect(d.truncated, isFalse); + }); + }); } diff --git a/test/connector/channel_sender_resolution_test.dart b/test/connector/channel_sender_resolution_test.dart new file mode 100644 index 00000000..b5213a76 --- /dev/null +++ b/test/connector/channel_sender_resolution_test.dart @@ -0,0 +1,102 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; + +/// Channel posts carry a claimed NAME and no key (#468), so adding a channel +/// sender to contacts hangs entirely on resolving that name against what the +/// radio has already heard. These pin the resolution rules, including the +/// namesake case the UI must never resolve on the user's behalf. +Contact _contact(String name, int keyByte, {int type = advTypeChat}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, keyByte)), + name: name, + type: type, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 8, 11), +); + +void main() { + late MeshCoreConnector connector; + + setUp(() { + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + connector.discoveredContactsForTest.clear(); + }); + + group('resolveContactsByName', () { + test( + 'matches a known contact ignoring case and surrounding whitespace', + () { + connector.contactsForTest.add(_contact('Ben', 0x11)); + + expect(connector.resolveContactsByName(' bEn ').single.name, 'Ben'); + }, + ); + + test('matches a discovered node that is not a contact yet', () { + connector.discoveredContactsForTest.add(_contact('Rover', 0x22)); + + final resolved = connector.resolveContactsByName('Rover'); + expect( + resolved.single.publicKeyHex, + _contact('Rover', 0x22).publicKeyHex, + ); + }); + + test('returns every node claiming the name, known ones first', () { + connector.contactsForTest.add(_contact('Twin', 0x33)); + connector.discoveredContactsForTest.add(_contact('Twin', 0x44)); + + final resolved = connector.resolveContactsByName('Twin'); + expect(resolved.length, 2); + expect(resolved.first.publicKeyHex, _contact('x', 0x33).publicKeyHex); + }); + + test('a node in both lists resolves once, as the known contact', () { + connector.contactsForTest.add(_contact('Dup', 0x55)); + connector.discoveredContactsForTest.add(_contact('Dup', 0x55)); + + expect(connector.resolveContactsByName('Dup').length, 1); + }); + + test('a partial name is not a match', () { + connector.contactsForTest.add(_contact('Benjamin', 0x66)); + + expect(connector.resolveContactsByName('Ben'), isEmpty); + }); + + test('an unheard name resolves to nothing', () { + expect(connector.resolveContactsByName('Ghost'), isEmpty); + }); + + test('an empty or whitespace-only name resolves to nothing', () { + connector.contactsForTest.add(_contact('Ben', 0x77)); + + expect(connector.resolveContactsByName(''), isEmpty); + expect(connector.resolveContactsByName(' '), isEmpty); + }); + }); + + group('resolveContactKeysByName', () { + test('returns the keys of the same nodes, in the same order', () { + connector.contactsForTest.add(_contact('Twin', 0x33)); + connector.discoveredContactsForTest.add(_contact('Twin', 0x44)); + + expect( + connector.resolveContactKeysByName('Twin'), + connector.resolveContactsByName('Twin').map((c) => c.publicKeyHex), + ); + }); + + test( + 'stays empty for an unheard name, so blocking falls back to the name', + () { + expect(connector.resolveContactKeysByName('Ghost'), isEmpty); + }, + ); + }); +} diff --git a/test/connector/cli_timeout_test.dart b/test/connector/cli_timeout_test.dart new file mode 100644 index 00000000..d53b8be7 --- /dev/null +++ b/test/connector/cli_timeout_test.dart @@ -0,0 +1,228 @@ +// #529 (epic #473): a repeater CLI command is a request-execute-reply exchange, +// but its timeout used calculateTimeout, which mirrors the firmware's +// calcDirectTimeoutMillisFor and models ONE-WAY delivery only. +// +// Measured against rpt-01: 27 commands, 12 replies, and 4 of those 12 arrived +// after the 4074 ms window had expired (6.17 s, 8.28 s, 15.52 s, 20.33 s; +// median 2.75 s). The same verb returned in both 2.31 s and 20.33 s. The tail +// is transmit scheduling on both radios, not command execution: on the 20.33 s +// case the repeater stamped its reply ~5 s in and the packet took another ~15 s +// to arrive, and `wifi on N` only sets a deadline before replying. So it is not +// a per-command constant that could be tabulated. +// +// These tests pin the budget's construction and, just as importantly, pin that +// the direct-message ACK path was NOT changed. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + }); + + // With no SELF_INFO parsed there are no radio params, so _estimateAirtimeMs + // returns its 50 ms fallback and _physicsMaxTimeout(0, 50) is + // 500 + ((50 * 6) + 250) = 1050. Every expectation below is derived from + // that, not from a chosen number. + const fallbackPhysicsMax0Hop = 1050; + const retrievalBudget = 20000; // _queueSyncTimeoutMs 5000 * (3 retries + 1) + + group('retrieval budget', () { + test('is derived from the sync constants, not restated', () { + expect(connector.messageRetrievalBudgetMs, retrievalBudget); + }); + }); + + group('calculateCliTimeout', () { + test('sums outbound, repeater hold, reply leg and retrieval', () { + expect( + connector.calculateCliTimeout(pathLength: 0), + fallbackPhysicsMax0Hop + + cliReplyDelayMs + + fallbackPhysicsMax0Hop + + retrievalBudget, + ); + }); + + test('is never below the retrieval budget it depends on (#530)', () { + for (final path in [-1, 0, 1, 2, 5]) { + expect( + connector.calculateCliTimeout(pathLength: path), + greaterThanOrEqualTo(connector.messageRetrievalBudgetMs), + reason: 'path $path must not expire before the app can fetch a reply', + ); + } + }); + + test('is always larger than the one-way delivery estimate', () { + for (final path in [-1, 0, 1, 2, 5]) { + expect( + connector.calculateCliTimeout(pathLength: path), + greaterThan(connector.calculateTimeout(pathLength: path)), + reason: 'path $path', + ); + } + }); + + test('covers the slowest round trip actually measured (20.33 s)', () { + // The observed worst case on the owner's radio. The budget has to clear + // it even in this test's degraded no-radio-params state, where the + // physics terms are at their smallest. + expect(connector.calculateCliTimeout(pathLength: 0), greaterThan(20330)); + }); + + test('grows with path length', () { + final direct = connector.calculateCliTimeout(pathLength: 0); + final oneHop = connector.calculateCliTimeout(pathLength: 1); + final twoHop = connector.calculateCliTimeout(pathLength: 2); + expect(oneHop, greaterThan(direct)); + expect(twoHop, greaterThan(oneHop)); + }); + }); + + group('the direct-message ACK path is unchanged', () { + // Negative test. #529 must not move DM ACK behaviour, which legitimately + // uses the one-way formula. If this breaks, the fix has leaked. + test('calculateTimeout still returns the firmware formula', () { + expect(connector.calculateTimeout(pathLength: 0), fallbackPhysicsMax0Hop); + }); + + test('calculateTimeout does not include the CLI reply delay', () { + expect( + connector.calculateTimeout(pathLength: 0), + lessThan(cliReplyDelayMs + fallbackPhysicsMax0Hop), + ); + }); + + test('calculateTimeout stays well under the retrieval budget', () { + // Not a requirement, an observation that pins the #530 mismatch: the DM + // path is allowed to be shorter than retrieval because a DM ACK does not + // depend on fetching a queued message. If this ever flips, the invariant + // in calculateCliTimeout needs revisiting rather than silently holding. + expect( + connector.calculateTimeout(pathLength: 0), + lessThan(connector.messageRetrievalBudgetMs), + ); + }); + }); + + group('flood is a single firmware value, not a range (#533)', () { + // The flood branch used to be written as "trust ML, only enforce the + // firmware formula as floor". It never did that: _physicsMinTimeout and + // _physicsMaxTimeout return the identical expression for pathLength < 0, + // so a clamp between them discards any prediction. The branch was removed + // and the constraint stated instead, with behaviour unchanged. + // + // These tests pin the equality the simplification depends on. If a future + // change makes the flood floor and ceiling differ, the removed branch would + // no longer have been equivalent, and this fails loudly rather than + // silently altering flood timeouts. + + // firmware calcFloodTimeoutMillisFor: SEND_TIMEOUT_BASE_MILLIS 500 + + // FLOOD_SEND_TIMEOUT_FACTOR 16 * airtime, with the 50 ms fallback airtime. + const floodFirmwareValue = 500 + (16 * 50); // 1300 + + test('flood returns the firmware formula exactly', () { + expect(connector.calculateTimeout(pathLength: -1), floodFirmwareValue); + }); + + test('flood does not scale with hop count the way direct does', () { + // Direct grows per hop; flood has no hop term at all. + expect( + connector.calculateTimeout(pathLength: -1), + isNot(connector.calculateTimeout(pathLength: 0)), + ); + expect( + connector.calculateTimeout(pathLength: 1), + greaterThan(connector.calculateTimeout(pathLength: 0)), + ); + }); + + test('the CLI budget still covers flood through both of its legs', () { + // calculateCliTimeout takes the flood branch in the outbound term and in + // the reply term, so no flood-specific handling is needed there. + expect( + connector.calculateCliTimeout(pathLength: -1), + floodFirmwareValue + + cliReplyDelayMs + + floodFirmwareValue + + connector.messageRetrievalBudgetMs, + ); + }); + }); + + group('flood ignores the model even when one exists (#533)', () { + // The group above only exercises the no-model path. The actual claim is + // about what happens when predictTimeout returns a value: for flood it can + // never survive, because the floor and the ceiling are the same number. + // + // This attaches a real predictor, trains it on deliberately huge delivery + // times so any prediction is far from the firmware constant, and asserts + // flood is unmoved. Verified to pass against the pre-#533 code as well, + // which is what makes the branch removal a simplification rather than a + // behaviour change. + + late TimeoutPredictionService prediction; + + setUp(() { + prediction = TimeoutPredictionService.noStorage(); + connector.initialize( + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(StorageService()), + timeoutPredictionService: prediction, + ); + // minObservations is 10; vary the features so training does not discard + // them all for zero variance, and make deliveryMs enormous so any + // prediction lands nowhere near 1300. + for (var i = 0; i < 12; i++) { + prediction.recordObservation( + contactKey: 'contact$i', + pathLength: i.isEven ? -1 : (i % 4), + messageBytes: 40 + (i * 12), + tripTimeMs: 40000 + (i * 1500), + ); + } + }); + + test('the predictor is actually trained, so the test is not vacuous', () { + expect(prediction.hasModel, isTrue); + final predicted = prediction.predictTimeout( + pathLength: -1, + messageBytes: 172, + ); + expect(predicted, isNotNull); + expect( + predicted, + greaterThan(1300), + reason: + 'the prediction must differ from the flood constant, or this ' + 'group proves nothing', + ); + }); + + test('flood still returns the firmware constant', () { + expect(connector.calculateTimeout(pathLength: -1), 500 + (16 * 50)); + }); + + test('direct is still clamped to its ceiling, so the clamp is live', () { + // Contrast: on a direct path the prediction IS consulted and then + // clamped. If this returned the raw prediction the clamp would be broken. + expect(connector.calculateTimeout(pathLength: 0), 1050); + }); + }); +} diff --git a/test/connector/contact_key_check_test.dart b/test/connector/contact_key_check_test.dart new file mode 100644 index 00000000..de00e13e --- /dev/null +++ b/test/connector/contact_key_check_test.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #762: asking the radio for one contact by key. "Not found" is the only +/// proof a contact is gone from the radio, so it must never be inferred from +/// an ERR that something else could own. +Uint8List _key(int b) => Uint8List.fromList(List.filled(32, b)); + +Uint8List _contactFrame(int keyByte, String name) { + final b = BytesBuilder() + ..addByte(respCodeContact) + ..add(_key(keyByte)) + ..addByte(advTypeChat) + ..addByte(0) + ..addByte(0xFF) + ..add(List.filled(64, 0)) + ..add(Uint8List(32)..setRange(0, name.length, utf8.encode(name))) + ..add(_u32(1790000000)) + ..add(_u32(0)) + ..add(_u32(0)) + ..add(_u32(1790000000)); + return b.toBytes(); +} + +Uint8List _u32(int v) => + Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little); + +Uint8List _err(int code) => Uint8List.fromList([respCodeErr, code]); + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + connector.contactKeyCheckTimeout = const Duration(milliseconds: 50); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + int byKeyRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContactByKey).length; + + test('a CONTACT for the key means it is on the radio', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + expect(byKeyRequests(), 1); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + expect(await result, ContactKeyCheckResult.onRadio); + }); + + test('NOT_FOUND with nothing else in flight means gone', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.notFound); + }); + + test('a CONTACT for another key does not answer the check', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_contactFrame(0x22, 'Bravo')); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('BAD_STATE is never read as not found', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(4)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('no reply times out as unresolved', () async { + expect( + await connector.checkContactOnRadio(_key(0x11)), + ContactKeyCheckResult.unresolved, + ); + }); + + test('NOT_FOUND after another by-key request is not trusted', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + await connector.getContactByKey(_key(0x22)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('NOT_FOUND during a contact stream is not trusted', () async { + await connector.getContacts(); + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('a second check while one is pending sends nothing', () async { + final first = connector.checkContactOnRadio(_key(0x11)); + expect( + await connector.checkContactOnRadio(_key(0x22)), + ContactKeyCheckResult.unresolved, + ); + expect(byKeyRequests(), 1); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + expect(await first, ContactKeyCheckResult.onRadio); + }); + + test('a send failure is unresolved and frees the next check', () async { + connector.sendFrameOverrideForTest = (_) => throw Exception('usb gone'); + expect( + await connector.checkContactOnRadio(_key(0x11)), + ContactKeyCheckResult.unresolved, + ); + connector.sendFrameOverrideForTest = sent.add; + final next = connector.checkContactOnRadio(_key(0x22)); + connector.handleFrameForTest(_contactFrame(0x22, 'Bravo')); + expect(await next, ContactKeyCheckResult.onRadio); + }); + + test('a disconnect mid-check ends it unresolved', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.resetConnectionHandshakeStateForTest(); + expect(await result, ContactKeyCheckResult.unresolved); + }); +} diff --git a/test/connector/contact_sync_test.dart b/test/connector/contact_sync_test.dart new file mode 100644 index 00000000..8752e3f6 --- /dev/null +++ b/test/connector/contact_sync_test.dart @@ -0,0 +1,609 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #660 / #668: a radio declared 350 contacts, streamed 106, and the app +/// replaced the owner's saved list with the 106. A full sync must never drop a +/// contact unless the radio proved it sent everything. +Uint8List _contactFrame( + int keyByte, + String name, { + int code = respCodeContact, +}) { + final b = BytesBuilder() + ..addByte(code) + ..add(List.filled(32, keyByte)) + ..addByte(advTypeChat) + ..addByte(0) // flags + ..addByte(0xFF) // flood path + ..add(List.filled(64, 0)) + ..add(Uint8List(32)..setRange(0, name.length, utf8.encode(name))) + ..add(_u32(1790000000)) // last advert + ..add(_u32(0)) // lat + ..add(_u32(0)) // lon + ..add(_u32(1790000000)); // lastmod + return b.toBytes(); +} + +Uint8List _u32(int v) => + Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little); + +Uint8List _start(int declared) => + Uint8List.fromList([respCodeContactsStart, ..._u32(declared)]); + +Uint8List get _end => Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]); + +Contact _saved(int keyByte, String name) => Contact( + publicKey: Uint8List.fromList(List.filled(32, keyByte)), + name: name, + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + connector.contactRecoverySettle = Duration.zero; + connector.contactKeyCheckGap = Duration.zero; + connector.contactKeyCheckTimeout = const Duration(milliseconds: 20); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Set names() => connector.contactsForTest.map((c) => c.name).toSet(); + + int contactRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContacts).length; + + /// Seeds saved contacts A, B, C; the radio then streams [streamed] under a + /// declared total of [declared]. + Future fullSync({ + required int declared, + required List streamed, + }) async { + await connector.getContacts(); + connector.handleFrameForTest(_start(declared)); + for (final f in streamed) { + connector.handleFrameForTest(f); + } + connector.handleFrameForTest(_end); + await Future.delayed(Duration.zero); + } + + void seedSaved() { + connector.contactsForTest + ..add(_saved(0x11, 'Alpha')) + ..add(_saved(0x22, 'Bravo')) + ..add(_saved(0x33, 'Charlie')); + } + + test('completeness needs a declared total and at least that many', () { + expect( + MeshCoreConnector.isContactSyncComplete(declared: 3, received: 3), + isTrue, + ); + expect( + MeshCoreConnector.isContactSyncComplete(declared: 350, received: 106), + isFalse, + ); + expect( + MeshCoreConnector.isContactSyncComplete(declared: null, received: 50), + isFalse, + ); + }); + + test('starting a full sync does not clear the saved list', () async { + seedSaved(); + await connector.getContacts(); + connector.handleFrameForTest(_start(3)); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('a complete sync replaces the list, removals included', () async { + seedSaved(); + await fullSync( + declared: 2, + streamed: [_contactFrame(0x11, 'Alpha'), _contactFrame(0x44, 'Delta')], + ); + + expect(names(), {'Alpha', 'Delta'}); + expect(connector.contactSyncShortfall, isNull); + expect(contactRequests(), 1, reason: 'no retry after a complete sync'); + }); + + Future settle() => + Future.delayed(const Duration(milliseconds: 5)); + + int byKeyRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContactByKey).length; + + /// Answers the recovery request the app just sent with [streamed]. + Future answerStream(int? declared, List streamed) async { + connector.handleFrameForTest( + declared == null + ? Uint8List.fromList([respCodeContactsStart]) + : _start(declared), + ); + for (final f in streamed) { + connector.handleFrameForTest(f); + } + connector.handleFrameForTest(_end); + await settle(); + } + + /// Three short full syncs that each deliver only Alpha; the by-key checks + /// that follow get no reply, so every missing contact stays unresolved. + Future threeShortSyncs({int? declared = 350}) async { + seedSaved(); + final alpha = [_contactFrame(0x11, 'Alpha')]; + await connector.getContacts(); + await answerStream(declared, alpha); + await answerStream(declared, alpha); + await answerStream(declared, alpha); + await Future.delayed(const Duration(milliseconds: 100)); + } + + test('a short sync removes nothing, merges, and recovers quietly', () async { + seedSaved(); + await fullSync( + declared: 350, + streamed: [_contactFrame(0x11, 'Alpha'), _contactFrame(0x44, 'Delta')], + ); + await settle(); + + expect(names(), {'Alpha', 'Bravo', 'Charlie', 'Delta'}); + expect( + connector.contactSyncShortfall, + isNull, + reason: 'no banner while recovery is still running', + ); + expect(connector.contactSyncDecisionPending, isFalse); + expect(contactRequests(), 2, reason: 'recovery sync after the settle'); + }); + + test('no declared total is never treated as complete', () async { + await threeShortSyncs(declared: null); + + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + expect(connector.contactSyncShortfall!.declared, isNull); + expect(connector.contactSyncDecisionPending, isTrue); + }); + + group('still short after three full syncs', () { + test('stops at three, checks the rest by key, removes nothing', () async { + await threeShortSyncs(); + + expect(contactRequests(), 3, reason: 'owner cap: 3 per connection'); + expect(byKeyRequests(), 2, reason: 'Bravo and Charlie, one each'); + expect(connector.contactSyncDecisionPending, isTrue); + expect(connector.contactSyncUndeliveredCount, 2); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + final shortfall = connector.contactSyncShortfall!; + expect(shortfall.declared, 350); + expect(shortfall.received, 1); + expect(shortfall.keptLocally, 2); + }); + + test('keep my contacts leaves the list as is', () async { + await threeShortSyncs(); + connector.resolveContactSyncKeepLocal(); + + expect(connector.contactSyncDecisionPending, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('use the radio list drops what no sync delivered', () async { + await threeShortSyncs(); + await connector.resolveContactSyncUseRadio(); + + expect(connector.contactSyncDecisionPending, isFalse); + expect(connector.contactSyncShortfall, isNull); + expect(names(), {'Alpha'}); + }); + }); + + group('forced resync (#703)', () { + test('the cap and pacing defaults are pinned', () { + expect(MeshCoreConnector.contactSyncMaxFullStreams, 3); + expect( + MeshCoreConnector.defaultContactRecoverySettle, + const Duration(seconds: 10), + ); + expect( + MeshCoreConnector.defaultContactKeyCheckGap, + const Duration(milliseconds: 250), + ); + expect( + MeshCoreConnector().contactKeyCheckTimeout, + const Duration(seconds: 5), + ); + }); + + test( + 'syncs that each miss different contacts add up to complete', + () async { + seedSaved(); + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + ]); + await answerStream(3, [ + _contactFrame(0x22, 'Bravo'), + _contactFrame(0x33, 'Charlie'), + ]); + await settle(); + + expect(contactRequests(), 2, reason: 'no third sync once complete'); + expect(byKeyRequests(), 0); + expect(connector.contactSyncShortfall, isNull); + expect(connector.contactSyncDecisionPending, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }, + ); + + test('only a contact the radio says is gone is removed', () async { + seedSaved(); + connector.contactsForTest.add(_saved(0x44, 'Delta')); + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + ]); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x33, 'Charlie'), + ]); + expect(byKeyRequests(), 1, reason: 'Delta, the only one missing'); + connector.handleFrameForTest( + Uint8List.fromList([respCodeErr, errCodeNotFound]), + ); + await settle(); + + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + expect(connector.contactSyncShortfall, isNull); + }); + + test( + 'a contact with no answer is kept even when the rest add up', + () async { + seedSaved(); + connector.contactsForTest.add(_saved(0x44, 'Delta')); + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + ]); + await answerStream(3, [_contactFrame(0x33, 'Charlie')]); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(names(), {'Alpha', 'Bravo', 'Charlie', 'Delta'}); + }, + ); + + test('a by-key answer counts toward complete', () async { + seedSaved(); + await connector.getContacts(); + final alpha = [_contactFrame(0x11, 'Alpha')]; + await answerStream(3, alpha); + await answerStream(3, alpha); + await answerStream(3, alpha); + connector.handleFrameForTest(_contactFrame(0x22, 'Bravo')); + await settle(); + connector.handleFrameForTest(_contactFrame(0x33, 'Charlie')); + await settle(); + + expect(connector.contactSyncShortfall, isNull); + expect(connector.contactSyncDecisionPending, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('a disconnect mid-recovery stops it and removes nothing', () async { + seedSaved(); + connector.contactRecoverySettle = const Duration(milliseconds: 30); + await fullSync(declared: 350, streamed: [_contactFrame(0x11, 'Alpha')]); + connector.resetConnectionHandshakeStateForTest(); + await Future.delayed(const Duration(milliseconds: 80)); + + expect(contactRequests(), 1, reason: 'no recovery after disconnect'); + expect(byKeyRequests(), 0); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('a new connection starts with no recovery state', () async { + seedSaved(); + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + ]); + connector.resetConnectionHandshakeStateForTest(); + + await connector.getContacts(); + await answerStream(3, [_contactFrame(0x11, 'Alpha')]); + + expect( + connector.contactSyncUndeliveredCount, + 2, + reason: 'Bravo from the old connection must not count', + ); + }); + + test('a contact the radio holds again after "not found" is kept', () async { + seedSaved(); + connector.contactsForTest + ..add(_saved(0x44, 'Delta')) + ..add(_saved(0x55, 'Echo')); + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + ]); + await answerStream(3, [_contactFrame(0x33, 'Charlie')]); + connector.handleFrameForTest( + Uint8List.fromList([respCodeErr, errCodeNotFound]), + ); + await settle(); + connector.handleFrameForTest( + _contactFrame(0x44, 'Delta', code: pushCodeNewAdvert), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(names(), contains('Delta')); + }); + + test('a busy link cannot hide a short sync', () async { + var now = DateTime.utc(2026, 10, 2, 6); + connector.contactSyncClock = () => now; + connector.contactRecoverySettle = const Duration(milliseconds: 10); + seedSaved(); + await fullSync(declared: 350, streamed: [_contactFrame(0x11, 'Alpha')]); + now = now.add(MeshCoreConnector.contactRecoveryMaxWait); + connector.handleFrameForTest( + Uint8List.fromList([pushCodeAdvert, ...List.filled(32, 0x11)]), + ); + await Future.delayed(const Duration(milliseconds: 1100)); + + expect(contactRequests(), 1, reason: 'no sync onto a busy link'); + expect(byKeyRequests(), 0); + expect(connector.contactSyncDecisionPending, isTrue); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('the latest declared total decides the result', () async { + connector.contactKeyCheckTimeout = const Duration(milliseconds: 100); + seedSaved(); + final alpha = [_contactFrame(0x11, 'Alpha')]; + await connector.getContacts(); + await answerStream(350, alpha); + await answerStream(350, alpha); + await answerStream(350, alpha); + // By-key checks are running; a refresh reports a new total of 2, and + // Charlie turns up while the checks are still going. + await connector.getContacts(); + await answerStream(2, alpha); + connector.handleFrameForTest(_contactFrame(0x33, 'Charlie')); + await Future.delayed(const Duration(milliseconds: 400)); + + expect(connector.contactSyncShortfall, isNull); + expect(connector.contactSyncDecisionPending, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test( + 'a complete sync during the by-key checks ends the recovery', + () async { + seedSaved(); + final alpha = [_contactFrame(0x11, 'Alpha')]; + await connector.getContacts(); + await answerStream(350, alpha); + await answerStream(350, alpha); + await answerStream(350, alpha); + // The by-key checks are running; a refresh now comes back complete. + await connector.getContacts(); + await answerStream(3, [ + _contactFrame(0x11, 'Alpha'), + _contactFrame(0x22, 'Bravo'), + _contactFrame(0x33, 'Charlie'), + ]); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(connector.contactSyncShortfall, isNull); + expect(connector.contactSyncDecisionPending, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }, + ); + + test('the banner cannot be dismissed while a decision is open', () async { + await threeShortSyncs(); + connector.dismissContactSyncShortfall(); + + expect(connector.contactSyncShortfall, isNotNull); + }); + + test('the give-up wait is pinned', () { + expect( + MeshCoreConnector.contactRecoveryMaxWait, + const Duration(minutes: 2), + ); + }); + + test('recovery waits for the radio to go quiet', () async { + var now = DateTime.utc(2026, 10, 2, 6); + connector.contactSyncClock = () => now; + connector.contactRecoverySettle = const Duration(milliseconds: 10); + seedSaved(); + await fullSync(declared: 350, streamed: [_contactFrame(0x11, 'Alpha')]); + await Future.delayed(const Duration(milliseconds: 50)); + expect(contactRequests(), 1, reason: 'radio not quiet yet'); + + now = now.add(const Duration(seconds: 1)); + await Future.delayed(const Duration(milliseconds: 1100)); + expect(contactRequests(), 2); + }); + }); + + test('an advert heard mid-sync survives a complete sync', () async { + seedSaved(); + await connector.getContacts(); + connector.handleFrameForTest(_start(1)); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + connector.contactsForTest.add(_saved(0x55, 'Echo')); + connector.handleFrameForTest( + _contactFrame(0x55, 'Echo', code: pushCodeNewAdvert), + ); + connector.handleFrameForTest(_end); + await Future.delayed(Duration.zero); + + expect(names(), {'Alpha', 'Echo'}); + }); + + group('one contact request at a time (#672)', () { + late DateTime now; + + setUp(() { + now = DateTime.utc(2026, 9, 23, 6); + connector.contactSyncClock = () => now; + }); + + test('a request during a stream is queued, not sent, list kept', () async { + seedSaved(); + await connector.getContacts(); + connector.handleFrameForTest(_start(3)); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + + await connector.getContacts(); + + expect(contactRequests(), 1); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + }); + + test('the queued request runs after END', () async { + await connector.getContacts(); + connector.handleFrameForTest(_start(0)); + await connector.getContacts(since: 5, preserveExisting: true); + connector.handleFrameForTest(_end); + await Future.delayed(Duration.zero); + + expect(contactRequests(), 2); + expect(sent.last.length, 5, reason: 'the queued incremental request'); + }); + + test('a queued full request wins over an incremental one', () async { + await connector.getContacts(); + connector.handleFrameForTest(_start(0)); + await connector.getContacts(since: 5, preserveExisting: true); + await connector.getContacts(); + connector.handleFrameForTest(_end); + await Future.delayed(Duration.zero); + + expect(contactRequests(), 2); + expect(sent.last.length, 1, reason: 'a full request has no since'); + }); + + test('ERR before the stream ends the request and keeps the list', () async { + seedSaved(); + await connector.getContacts(); + connector.handleFrameForTest(Uint8List.fromList([respCodeErr, 4])); + + expect(connector.isLoadingContacts, isFalse); + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + await connector.getContacts(); + expect(contactRequests(), 2, reason: 'no longer blocked'); + }); + + test('a request idle for 30 s is treated as lost', () async { + await connector.getContacts(); + connector.handleFrameForTest(_start(3)); + + now = now.add(const Duration(seconds: 29)); + await connector.getContacts(); + expect(contactRequests(), 1, reason: 'still live at 29 s'); + + now = now.add(const Duration(seconds: 2)); + await connector.getContacts(); + expect(contactRequests(), 2, reason: 'stale at 31 s'); + }); + + test('contact frames keep a long stream alive', () async { + await connector.getContacts(); + connector.handleFrameForTest(_start(3)); + now = now.add(const Duration(seconds: 25)); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + now = now.add(const Duration(seconds: 25)); + + await connector.getContacts(); + expect(contactRequests(), 1); + }); + + test('a stream that never ends is ended at 30 s without pruning', () async { + seedSaved(); + await connector.getContacts(); + connector.handleFrameForTest(_start(3)); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + await connector.getContacts(since: 5, preserveExisting: true); + + now = now.add(const Duration(seconds: 29)); + connector.checkStaleContactRequest(); + expect(connector.isLoadingContacts, isTrue, reason: 'live at 29 s'); + + now = now.add(const Duration(seconds: 2)); + connector.checkStaleContactRequest(); + await Future.delayed(Duration.zero); + + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + expect(contactRequests(), 2, reason: 'the queued request ran'); + expect(sent.last.length, 5, reason: 'the queued incremental request'); + }); + + test('a failed send does not leave refreshes blocked', () async { + connector.sendFrameOverrideForTest = (_) => throw Exception('usb gone'); + await expectLater(connector.getContacts(), throwsException); + + connector.sendFrameOverrideForTest = sent.add; + await connector.getContacts(); + expect(contactRequests(), 1); + }); + }); + + test('an incremental sync never removes anything', () async { + seedSaved(); + await connector.getContacts(since: 1, preserveExisting: true); + connector.handleFrameForTest(_start(350)); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + connector.handleFrameForTest(_end); + await Future.delayed(Duration.zero); + + expect(names(), {'Alpha', 'Bravo', 'Charlie'}); + expect(connector.contactSyncShortfall, isNull); + expect(contactRequests(), 1); + }); +} diff --git a/test/connector/frame_budget_platform_test.dart b/test/connector/frame_budget_platform_test.dart new file mode 100644 index 00000000..9e19c560 --- /dev/null +++ b/test/connector/frame_budget_platform_test.dart @@ -0,0 +1,133 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +/// Regression lock for the frame budget, per platform. +/// +/// This one getter decides the composer's byte budget everywhere, and it had +/// collapsed that budget to zero on three of the five platforms before anyone +/// noticed, each time surfacing as a user reporting "the keyboard doesn't +/// respond": +/// +/// Windows (#686) - the WinRT plugin never created a GattSession, so no MTU +/// was ever reported and mtuNow stayed on its 23 default. +/// Linux (#717) - the plugin's onMtuChanged returned Stream.empty(). +/// Web (#718) - Web Bluetooth exposes no MTU at all, so the BLE floor +/// applied forever. +/// +/// None of those were caught by a test, because nothing exercised this +/// function. They were caught by users, two months and three platforms apart. +/// These cases exist so a regression is a red build instead of a bug report. +int _budget({ + MeshCoreTransportType transport = MeshCoreTransportType.bluetooth, + bool isWeb = false, + int mtuNow = 0, +}) => MeshCoreConnector.resolveFrameBudget( + transport: transport, + isWeb: isWeb, + mtuNow: mtuNow, +); + +void main() { + group('non-BLE transports are never floored', () { + test('usb gets the full frame', () { + expect(_budget(transport: MeshCoreTransportType.usb), maxFrameSize); + }); + + test('tcp gets the full frame', () { + expect(_budget(transport: MeshCoreTransportType.tcp), maxFrameSize); + }); + + test('a wired transport ignores a bogus MTU entirely', () { + expect( + _budget(transport: MeshCoreTransportType.usb, mtuNow: 23), + maxFrameSize, + ); + }); + }); + + group('web BLE is exempt from the floor (#718)', () { + // The branch that cannot be reached any other way: kIsWeb is a + // compile-time constant, so without the pure function this is untestable. + test('web gets the full frame even with no MTU reported', () { + expect(_budget(isWeb: true, mtuNow: 0), maxFrameSize); + }); + + test('web gets the full frame even at the 23-byte ATT default', () { + expect(_budget(isWeb: true, mtuNow: 23), maxFrameSize); + }); + + test('a web budget leaves BOTH composers usable', () { + // The actual regression: this is what was 0 before #718. + final budget = _budget(isWeb: true, mtuNow: 23); + expect( + isComposerBudgetUsable( + maxChannelMessageBytes('KB9QDI-JOE', maxFrameBytes: budget), + ), + isTrue, + ); + expect( + isComposerBudgetUsable(maxContactMessageBytes(maxFrameBytes: budget)), + isTrue, + ); + }); + }); + + group('native BLE keeps the write-safety floor (#395)', () { + test('no device reported yields the floor, never the full frame', () { + // Must NOT be maxFrameSize: defaulting an unknown link to the largest + // size would authorize an oversized write, which is what the floor is + // for. The floor is correct here even though it is what made the + // composer unusable; the fix was reporting the MTU, not removing this. + expect(_budget(mtuNow: 0), 20); + }); + + test('the 23-byte ATT minimum yields the floor', () { + expect(_budget(mtuNow: 23), 20); + }); + + test('a negotiated MTU is honoured minus the 3-byte ATT header', () { + expect(_budget(mtuNow: 100), 97); + }); + + test('a large MTU is capped at the frame size', () { + expect(_budget(mtuNow: 517), maxFrameSize); + }); + + test('never returns below the floor for an absurdly small MTU', () { + expect(_budget(mtuNow: 5), 20); + }); + }); + + group('the MTUs actually measured on hardware leave the composer usable', () { + // Pinning the real numbers, so a regression that silently reintroduces the + // floor on a healthy link fails here rather than in someone's chat window. + for (final probe in <({String platform, int mtu})>[ + (platform: 'Android', mtu: 247), + (platform: 'Windows after #686', mtu: 176), + ]) { + test('${probe.platform} (MTU ${probe.mtu})', () { + final budget = _budget(mtuNow: probe.mtu); + expect(budget, maxFrameSize); + expect( + isComposerBudgetUsable( + maxChannelMessageBytes('KB9QDI-JOE', maxFrameBytes: budget), + ), + isTrue, + reason: 'a healthy link must leave a usable channel composer', + ); + }); + } + }); + + group('the exact failure users reported is still reproducible', () { + test('an unreported MTU collapses the channel composer to zero', () { + // Not a fix to preserve, a fact to keep visible: when the MTU is + // genuinely unknown the budget IS unusable, which is why #684's guard + // has to exist and why reporting the MTU was the real fix. + final budget = _budget(mtuNow: 0); + expect(maxChannelMessageBytes('KB9QDI-JOE', maxFrameBytes: budget), 0); + expect(maxContactMessageBytes(maxFrameBytes: budget), 4); + }); + }); +} diff --git a/test/connector/identity_transfer_test.dart b/test/connector/identity_transfer_test.dart new file mode 100644 index 00000000..b6a3e011 --- /dev/null +++ b/test/connector/identity_transfer_test.dart @@ -0,0 +1,165 @@ +// #578 (epic #568): node identity export/import and the auto-add hop limit. +// +// The identity commands are behind firmware build flags, so a device can +// legitimately answer RESP_CODE_DISABLED. These tests pin that "this radio was +// built without the feature" stays distinguishable from "that request failed", +// because the export UI has to degrade rather than offer a retry that can never +// succeed. +// +// No key material here is real. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List fakeIdentity([int fill = 0x11]) => + Uint8List.fromList(List.filled(privateKeySize, fill)); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('frame construction', () { + test('the export request is a bare one-byte command', () { + expect(buildExportPrivateKeyFrame(), [cmdExportPrivateKey]); + }); + + test('the import request carries the command then 64 key bytes', () { + final frame = buildImportPrivateKeyFrame(fakeIdentity(0xAB)); + + // Firmware requires len >= 65 before it will even parse the command. + expect(frame, hasLength(1 + privateKeySize)); + expect(frame[0], cmdImportPrivateKey); + expect(frame.sublist(1), everyElement(0xAB)); + }); + + test( + 'an identity of the wrong size is refused before it reaches the wire', + () { + expect( + () => buildImportPrivateKeyFrame(Uint8List(32)), + throwsA(isA()), + ); + }, + ); + }); + + group('auto-add hop limit', () { + test( + 'omitting the limit keeps the frame two bytes, as firmware expects', + () { + // Firmware applies the third byte only when present, so a two-byte frame + // leaves the device's existing limit alone. Older behavior must not + // change just because the parameter now exists. + final frame = buildSetAutoAddConfigFrame( + autoAddChat: true, + autoAddRepeater: false, + autoAddRoomServer: false, + autoAddSensor: false, + overwriteOldest: false, + ); + + expect(frame, hasLength(2)); + expect(frame[0], cmdSetAutoAddConfig); + expect(frame[1], autoAddChatFlag); + }, + ); + + test('supplying the limit appends it as a third byte', () { + final frame = buildSetAutoAddConfigFrame( + autoAddChat: false, + autoAddRepeater: false, + autoAddRoomServer: false, + autoAddSensor: false, + overwriteOldest: true, + maxHops: 5, + ); + + expect(frame, hasLength(3)); + expect(frame[1], autoAddOverwriteOldestFlag); + expect(frame[2], 5); + }); + + test('the limit is clamped to what firmware will accept', () { + final frame = buildSetAutoAddConfigFrame( + autoAddChat: false, + autoAddRepeater: false, + autoAddRoomServer: false, + autoAddSensor: false, + overwriteOldest: false, + maxHops: 250, + ); + + expect(frame[2], autoAddMaxHopsLimit); + }); + }); + + group('connector', () { + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + }); + + test( + 'exporting while disconnected reports no reply, not a refusal', + () async { + final result = await connector.exportPrivateKey(); + + expect(result.outcome, IdentityTransfer.noReply); + expect(result.identity, isNull); + }, + ); + + test('importing while disconnected reports no reply', () async { + expect( + await connector.importPrivateKey(fakeIdentity()), + IdentityTransfer.noReply, + ); + }); + + test('importing a wrongly sized identity throws before any I/O', () async { + expect( + () => connector.importPrivateKey(Uint8List(10)), + throwsA(isA()), + ); + }); + + test('the hop limit defaults to no limit until a device reports one', () { + expect(connector.autoAddMaxHops, 0); + }); + + test('a three-byte auto-add reply sets the hop limit', () { + connector.handleFrameForTest([ + respCodeAutoAddConfig, + autoAddChatFlag | autoAddOverwriteOldestFlag, + 7, + ]); + + expect(connector.autoAddMaxHops, 7); + expect(connector.autoAddUsers, isTrue); + expect(connector.autoAddOverwriteOldest, isTrue); + expect(connector.autoAddRepeaters, isFalse); + }); + + test( + 'a two-byte auto-add reply from older firmware leaves the limit alone', + () { + connector.handleFrameForTest([ + respCodeAutoAddConfig, + autoAddChatFlag, + 9, + ]); + connector.handleFrameForTest([respCodeAutoAddConfig, autoAddChatFlag]); + + expect(connector.autoAddMaxHops, 9); + }, + ); + }); +} diff --git a/test/connector/mtu_composer_budget_test.dart b/test/connector/mtu_composer_budget_test.dart new file mode 100644 index 00000000..8c21cd67 --- /dev/null +++ b/test/connector/mtu_composer_budget_test.dart @@ -0,0 +1,139 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +/// Characterizes the #592 root cause: on a BLE link whose MTU was never +/// reported, `effectiveMaxFrameSize` falls to the 20-byte floor and the +/// composer byte budget collapses to the values below. These are the numbers +/// both field reports reduced to: "4 characters in a DM", "keyboard dead in +/// every channel". +/// +/// The fix is not to change this arithmetic. The frame budget is a write-safety +/// cap and stays honest (#395); the fix is the vendored Windows plugin +/// reporting the real MTU (#686) so a 20-byte frame budget stops occurring on +/// healthy links. The user-facing guard for a collapsed budget is #684. +void main() { + /// What `effectiveMaxFrameSize` yields for a BLE link with no reported MTU: + /// flutter_blue_plus defaults `mtuNow` to the 23-byte ATT minimum, minus the + /// 3-byte ATT header. + const unknownMtuFrameBudget = 20; + + group('composer budget at the unknown-MTU BLE floor (#592)', () { + test('a DM composer is left with exactly 4 bytes', () { + expect( + maxContactMessageBytes(maxFrameBytes: unknownMtuFrameBudget), + 4, + reason: + 'the owner typed four characters into a DM and then input died; ' + 'this is that number: 20 - 16 overhead', + ); + }); + + test('a short-named radio is left with one byte in a channel', () { + expect( + maxChannelMessageBytes('WSMJ898', maxFrameBytes: unknownMtuFrameBudget), + 1, + reason: + 'the ": " prefix eats the frame budget: 20 - 10 overhead - 9 ' + 'prefix leaves 1', + ); + }); + + test('any radio name of 8 characters or more reaches zero', () { + expect( + maxChannelMessageBytes( + 'WSMJ898-OBS-HV4', + maxFrameBytes: unknownMtuFrameBudget, + ), + 0, + reason: + 'a longer name pushes the frame budget negative and _minPositive ' + 'clamps to 0, so not one character is accepted', + ); + expect( + maxChannelMessageBytes(null, maxFrameBytes: unknownMtuFrameBudget), + 0, + ); + }); + }); + + group('budget on a transport with a full frame', () { + test('a DM composer gets the frame budget minus overhead', () { + // 172 frame - 16 overhead = 156, just under the 160 payload cap. + expect(maxContactMessageBytes(), 156); + }); + + test('a channel composer stays usable', () { + expect(maxChannelMessageBytes('WSMJ898'), greaterThan(100)); + }); + + test('a healthy negotiated BLE MTU restores a usable budget', () { + // A typical Windows/Android negotiation lands around 244-517; 185 is the + // value the app requests on Android. 185 - 3 = 182 writable, which is + // above maxFrameSize, so the budget is the same as a full frame. + expect(maxContactMessageBytes(maxFrameBytes: 172), 156); + expect( + maxChannelMessageBytes('WSMJ898', maxFrameBytes: 172), + greaterThan(100), + ); + }); + }); + + /// The guard #684 adds. These are the assertions that were left out of this + /// file while it lived on a throwaway branch, because the behaviour they + /// describe did not exist yet. + group('the composer guard recognises an unusable budget (#684)', () { + test('a zero budget is not usable', () { + // The literal #592 symptom: every keystroke rejected, field looks alive. + expect(isComposerBudgetUsable(0), isFalse); + }); + + test('the degenerate #592 budgets are all caught', () { + // DM 4 and channel 1 at the unknown-MTU floor. A field that accepts four + // characters is as misleading as one that accepts none, so the guard has + // to catch the near-misses, not just zero. + expect( + isComposerBudgetUsable( + maxContactMessageBytes(maxFrameBytes: unknownMtuFrameBudget), + ), + isFalse, + reason: 'the 4-byte DM budget must trigger the notice', + ); + expect( + isComposerBudgetUsable( + maxChannelMessageBytes( + 'WSMJ89', + maxFrameBytes: unknownMtuFrameBudget, + ), + ), + isFalse, + reason: 'the 1-byte channel budget must trigger the notice', + ); + }); + + test('the threshold boundary is exact', () { + expect(isComposerBudgetUsable(minUsableComposerBytes - 1), isFalse); + expect(isComposerBudgetUsable(minUsableComposerBytes), isTrue); + }); + + test('a healthy link does NOT trigger the notice', () { + // The negative test: the guard must stay invisible on a working link, or + // it becomes noise that trains users to ignore it. + expect(isComposerBudgetUsable(maxContactMessageBytes()), isTrue); + expect(isComposerBudgetUsable(maxChannelMessageBytes('WSMJ898')), isTrue); + // And at the MTU actually measured on hardware: 247 on Android, 176 on + // Windows once the vendored plugin reports it (#686). + expect( + isComposerBudgetUsable( + maxChannelMessageBytes('WSMJ898', maxFrameBytes: 247 - 3), + ), + isTrue, + ); + expect( + isComposerBudgetUsable( + maxChannelMessageBytes('WSMJ898', maxFrameBytes: 176 - 3), + ), + isTrue, + ); + }); + }); +} diff --git a/test/connector/observer_config_client_test.dart b/test/connector/observer_config_client_test.dart index 08b64016..cf38a150 100644 --- a/test/connector/observer_config_client_test.dart +++ b/test/connector/observer_config_client_test.dart @@ -208,4 +208,32 @@ void main() { expect(list, isNull); }); }); + + group('extractScalarValue (#469)', () { + String v(String reply) => ObserverConfigClient.extractScalarValue(reply); + + test('blank field returns empty, not the echoed key line', () { + // The bug: a blank field replies "key =" (no space after =); the old + // " = " match failed and leaked the whole line. + expect(v('mqtt.broker.1.iata_override ='), ''); + expect(v('mqtt.broker.1.iata_override =\n'), ''); + expect(v('mqtt.broker.1.iata_override = '), ''); + }); + + test('normal value extracted', () { + expect( + v('mqtt.broker.0.url = mqtt://mqtt1.okimesh.org:1883\n'), + 'mqtt://mqtt1.okimesh.org:1883', + ); + expect(v('mqtt.broker.0.enabled = 1'), '1'); + }); + + test('value containing = is preserved (split on first =)', () { + expect(v('mqtt.broker.0.jwt_token = a=b=c'), 'a=b=c'); + }); + + test('no = falls back to the trimmed line', () { + expect(v(' bareword '), 'bareword'); + }); + }); } diff --git a/test/connector/pkt_hash_protocol_test.dart b/test/connector/pkt_hash_protocol_test.dart new file mode 100644 index 00000000..ce6b234a --- /dev/null +++ b/test/connector/pkt_hash_protocol_test.dart @@ -0,0 +1,78 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +void main() { + group('0xC6 pkt-hash builder', () { + test('builds a 7-byte GET with little-endian timestamp', () { + final frame = buildOffbandPktHashGetFrame(0x11223344, 7); + expect(frame, [0xC6, 0x01, 0x44, 0x33, 0x22, 0x11, 0x07]); + }); + + test('masks channel_idx to one byte', () { + final frame = buildOffbandPktHashGetFrame(0, 0x1FF); + expect(frame[6], 0xFF); + }); + }); + + group('0xC6 pkt-hash reply parser', () { + Uint8List reply(int ts, int chan, List hash8) { + final f = Uint8List(15); + f[0] = cmdOffbandPktHash; + f[1] = pktHashRespGet; + ByteData.sublistView(f, 2, 6).setUint32(0, ts, Endian.little); + f[6] = chan; + f.setRange(7, 15, hash8); + return f; + } + + test('parses a success reply and echoes the key', () { + final parsed = parseOffbandPktHashReply( + reply(0x11223344, 3, [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x0a, 0xff]), + ); + expect(parsed, isNotNull); + expect(parsed!.timestamp, 0x11223344); + expect(parsed.channelIdx, 3); + // 16 lowercase hex chars, matching CoreScope + client _computePacketHash. + expect(parsed.hashHex, 'deadbeef01020aff'); + }); + + test('returns null on the error reply', () { + final err = Uint8List.fromList([cmdOffbandPktHash, pktHashRespErr, 1]); + expect(parseOffbandPktHashReply(err), isNull); + }); + + test('returns null on a short/malformed frame', () { + expect( + parseOffbandPktHashReply(Uint8List.fromList([0xC6, 0x01, 0, 0])), + isNull, + ); + expect(parseOffbandPktHashReply(Uint8List(0)), isNull); + }); + + test('returns null when the opcode is wrong', () { + final f = reply(1, 1, List.filled(8, 0)); + f[0] = 0xC4; // caplog, not pkt-hash + expect(parseOffbandPktHashReply(f), isNull); + }); + }); + + group('firmwareSupportsPktHash gate', () { + test('requires both the cap bit and ver >= 22', () { + expect(firmwareSupportsPktHash(0x08, 22), isTrue); + expect(firmwareSupportsPktHash(0x08, 23), isTrue); + expect(firmwareSupportsPktHash(0x08, 21), isFalse); // version too low + expect(firmwareSupportsPktHash(0x00, 22), isFalse); // bit clear + expect(firmwareSupportsPktHash(null, 22), isFalse); // no byte 2 + expect(firmwareSupportsPktHash(0x08, null), isFalse); // no version + }); + + test('ignores unrelated bits', () { + // 0x0A = button-matrix (0x02) + pkt-hash (0x08) both set. + expect(firmwareSupportsPktHash(0x0A, 22), isTrue); + // Only notify-scope (0x01) set: pkt-hash bit clear. + expect(firmwareSupportsPktHash(0x01, 22), isFalse); + }); + }); +} diff --git a/test/connector/preset_apply_frames_test.dart b/test/connector/preset_apply_frames_test.dart new file mode 100644 index 00000000..a810652d --- /dev/null +++ b/test/connector/preset_apply_frames_test.dart @@ -0,0 +1,72 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/services/radio_preset_service.dart'; + +/// What applying a preset puts on the wire to a companion or observer +/// (#730): stock CMD_SET_RADIO_PARAMS (11), CMD_SET_RADIO_TX_POWER (12) and, +/// when the preset carries one, CMD_SET_PATH_HASH_MODE (61). +void main() { + late List presets; + + setUpAll(() { + presets = mergeRadioPresets( + parseUpstreamPresets( + File('assets/radio_presets/meshcore-upstream.json').readAsStringSync(), + ).presets, + parseOverlayPresets( + File('assets/radio_presets/offband.json').readAsStringSync(), + ).presets, + ); + }); + + RadioPreset named(String title) => + presets.firstWhere((p) => p.title == title); + + List le32(int v) => [ + v & 0xFF, + (v >> 8) & 0xFF, + (v >> 16) & 0xFF, + (v >> 24) & 0xFF, + ]; + + test('radio params: frequency in kHz, bandwidth in Hz, as stock expects', () { + final philly = named('USA - Philly Mesh'); + // The form sends MHz * 1000, i.e. kHz; stock stores freq / 1000.0 as MHz. + final frame = buildSetRadioParamsFrame( + philly.frequencyKHz, + philly.bandwidth.hz, + philly.spreadingFactor.value, + philly.codingRate.value, + ); + expect(frame, [cmdSetRadioParams, ...le32(919500), ...le32(500000), 10, 5]); + // Inside stock's accepted ranges (150000-2500000 kHz, BW <= 500000 Hz). + expect(philly.frequencyKHz, inInclusiveRange(150000, 2500000)); + expect(philly.bandwidth.hz, lessThanOrEqualTo(500000)); + }); + + test('path hash: published bytes become the zero-based mode on the wire', () { + expect( + buildSetPathHashModeFrame(named('USA - Philly Mesh').pathHashMode!), + [cmdSetPathHashMode, 0, 1], + ); + expect( + buildSetPathHashModeFrame( + named('USA - Southern California').pathHashMode!, + ), + [cmdSetPathHashMode, 0, 2], + ); + expect( + buildSetPathHashModeFrame(named('New Zealand (Gisborne)').pathHashMode!), + [cmdSetPathHashMode, 0, 0], + ); + }); + + test('a preset without path hash or TX power sends neither', () { + final usa = named('USA'); + expect(usa.pathHashMode, isNull); + expect(usa.txPowerDbm, isNull); + }); +} diff --git a/test/connector/utf8_name_truncation_test.dart b/test/connector/utf8_name_truncation_test.dart new file mode 100644 index 00000000..346d8a51 --- /dev/null +++ b/test/connector/utf8_name_truncation_test.dart @@ -0,0 +1,124 @@ +// Grapheme-safe name truncation (#636). +// +// The on-wire name field is 32 bytes including a null terminator, so 31 are +// usable. Before this fix the three writers copied raw bytes up to that +// boundary, cutting multi-byte characters in half and putting invalid UTF-8 on +// the wire. ASCII names were unaffected, which is why it went unnoticed. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +/// Decodes strictly. Throws if the bytes are not valid UTF-8, which is exactly +/// the failure this fix prevents. +String strictDecode(List bytes) => + utf8.decode(bytes, allowMalformed: false); + +void main() { + group('utf8TruncateToBytes (#636)', () { + test('leaves anything that already fits completely alone', () { + for (final s in ['', 'Bob', 'Roger KY4RS', 'a' * 31]) { + expect(utf8TruncateToBytes(s, 31), utf8.encode(s), reason: s); + } + }); + + test('never emits invalid UTF-8, whatever the cut point', () { + // The core property. Sweep every budget across a string whose characters + // are 1, 3 and 4 bytes, so a byte-wise cut would land mid-character at + // many of these lengths. + const s = 'ab中文🧙cd漢字'; + for (var budget = 0; budget <= utf8.encode(s).length + 2; budget++) { + final out = utf8TruncateToBytes(s, budget); + expect(out.length, lessThanOrEqualTo(budget)); + // Would throw on a split character. + expect( + () => strictDecode(out), + returnsNormally, + reason: 'budget $budget', + ); + expect( + s.startsWith(strictDecode(out)), + isTrue, + reason: 'budget $budget', + ); + } + }); + + test('CJK truncates on a character boundary, not a byte one', () { + // 11 CJK characters is 33 bytes against a 31-byte budget. + const name = '中文节点名称测试一二三'; + expect(utf8.encode(name).length, 33); + final out = utf8TruncateToBytes(name, 31); + // 10 characters at 3 bytes each fit; the 11th does not. + expect(out.length, 30); + expect(strictDecode(out), '中文节点名称测试一二'); + }); + + test('a ZWJ emoji sequence is kept whole or dropped whole', () { + // The mage is 4 codepoints joined by ZWJ plus a variation selector, 13 + // bytes. A codepoint-safe cut would still be wrong here: it could leave a + // bare mage, a dangling joiner, or an orphaned selector. + const mage = '\u{1F9D9}‍♂️'; + expect(utf8.encode(mage).length, 13); + + // One byte short of fitting: the whole cluster must go. + expect(utf8TruncateToBytes(mage, 12), isEmpty); + // Exactly fitting: kept intact. + expect(strictDecode(utf8TruncateToBytes(mage, 13)), mage); + + // And no partial cluster survives at any budget below 13. + for (var b = 0; b < 13; b++) { + expect(utf8TruncateToBytes(mage, b), isEmpty, reason: 'budget $b'); + } + }); + + test('a zero or negative budget yields nothing', () { + expect(utf8TruncateToBytes('anything', 0), isEmpty); + expect(utf8TruncateToBytes('anything', -5), isEmpty); + }); + }); + + group('the three writers are grapheme-safe (#636)', () { + // Reads a fixed-width, null-padded name field back out. + String nameFrom(Uint8List frame, int offset, int width) { + final slice = frame.sublist(offset, offset + width); + final end = slice.indexOf(0); + return strictDecode(slice.sublist(0, end < 0 ? slice.length : end)); + } + + const cjk = '中文节点名称测试一二三'; + + test('buildSetAdvertNameFrame: own advert name survives intact', () { + // The most externally visible of the three: this is the name the whole + // mesh sees and the name embedded in emitted contact cards. + final frame = buildSetAdvertNameFrame(cjk); + final decoded = strictDecode(frame.sublist(1)); + expect(decoded, '中文节点名称测试一二'); + expect(frame.length - 1, lessThanOrEqualTo(maxNameSize - 1)); + }); + + test('buildUpdateContactPathFrame: contact name survives intact', () { + final frame = buildUpdateContactPathFrame( + Uint8List(pubKeySize), + Uint8List(0), + -1, + name: cjk, + ); + expect(nameFrom(frame, contactNameOffset, maxNameSize), '中文节点名称测试一二'); + }); + + test('buildSetChannelFrame: channel name survives intact', () { + final frame = buildSetChannelFrame(0, cjk, Uint8List(16)); + // [cmd][idx][name x32][psk x16] + expect(nameFrom(frame, 2, maxNameSize), '中文节点名称测试一二'); + }); + + test('ASCII names are byte-identical to the old behaviour', () { + // No regression for the overwhelmingly common case. + final frame = buildSetAdvertNameFrame('Roger KY4RS'); + expect(strictDecode(frame.sublist(1)), 'Roger KY4RS'); + }); + }); +} diff --git a/test/helpers/channel_send_timestamp_test.dart b/test/helpers/channel_send_timestamp_test.dart new file mode 100644 index 00000000..1cd3b0ad --- /dev/null +++ b/test/helpers/channel_send_timestamp_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/channel_send_timestamp.dart'; + +void main() { + group('monotonicChannelSendTs', () { + test('first send on a channel uses now', () { + expect(monotonicChannelSendTs(1000, null), 1000); + }); + + test('bumps by 1 on a same-second collision', () { + expect(monotonicChannelSendTs(1000, 1000), 1001); + }); + + test('uses now when it has advanced past the last send', () { + expect(monotonicChannelSendTs(1005, 1000), 1005); + }); + + test('bumps past the last send if the clock went backwards', () { + expect(monotonicChannelSendTs(1000, 1005), 1006); + }); + + test('a rapid burst stays strictly increasing', () { + int? last; + final produced = []; + // Same wall-clock second for the whole burst. + for (var i = 0; i < 5; i++) { + last = monotonicChannelSendTs(1000, last); + produced.add(last); + } + expect(produced, [1000, 1001, 1002, 1003, 1004]); + expect(produced.toSet().length, produced.length); // all unique + }); + }); +} diff --git a/test/helpers/remote_radio_commands_test.dart b/test/helpers/remote_radio_commands_test.dart new file mode 100644 index 00000000..f11eadd4 --- /dev/null +++ b/test/helpers/remote_radio_commands_test.dart @@ -0,0 +1,256 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/remote_radio_commands.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/models/radio_settings.dart'; + +RadioPreset preset( + String id, { + double mhz = 908.205, + LoRaBandwidth bw = LoRaBandwidth.bw62_5, + LoRaSpreadingFactor sf = LoRaSpreadingFactor.sf9, + LoRaCodingRate cr = LoRaCodingRate.cr4_8, + int? tx, + int? hashBytes, +}) => RadioPreset( + id: id, + title: id, + region: 'USA', + frequencyMHz: mhz, + bandwidth: bw, + spreadingFactor: sf, + codingRate: cr, + source: RadioPresetSource.offband, + txPowerDbm: tx, + pathHashBytes: hashBytes, +); + +void main() { + group('remote radio commands (#662)', () { + test('set radio keeps its existing format', () { + expect( + setRadioCommand('908.205', 62500, 9, 8), + 'set radio 908.205,62.5,9,8', + ); + }); + + test('tempradio carries the values of the OKI-published command', () { + // docs.okimesh.org 500kHz-testing: tempradio 909.750,500,10,5,1440. + // "500.0" and "500" parse to the same bandwidth (firmware strtof, + // CommonCLI.cpp tempradio handler). + expect( + tempRadioCommand('909.750', 500000, 10, 5, kTempRadioDefaultMinutes), + 'tempradio 909.750,500.0,10,5,1440', + ); + }); + + test('coding rate goes out as the 4/x denominator', () { + expect(tempRadioCommand('910.525', 62500, 7, 5, 60), endsWith(',7,5,60')); + }); + + test( + 'the default duration is valid, so no error shows by default (#748)', + () { + expect( + parseTempRadioMinutes('$kTempRadioDefaultMinutes'), + kTempRadioDefaultMinutes, + ); + }, + ); + + test('duration must be 1 to the firmware overflow bound', () { + expect(parseTempRadioMinutes('1440'), 1440); + expect(parseTempRadioMinutes(' 1 '), 1); + expect(parseTempRadioMinutes('$kTempRadioMaxMinutes'), 35791); + expect(parseTempRadioMinutes('${kTempRadioMaxMinutes + 1}'), isNull); + expect(parseTempRadioMinutes('0'), isNull); + expect(parseTempRadioMinutes('-5'), isNull); + expect(parseTempRadioMinutes('1.5'), isNull); + expect(parseTempRadioMinutes(''), isNull); + // 2000 + 35791 min fits a 32-bit int; one more minute does not. + expect(2000 + kTempRadioMaxMinutes * 60 * 1000, lessThan(1 << 31)); + expect( + 2000 + (kTempRadioMaxMinutes + 1) * 60 * 1000, + greaterThan(1 << 31), + ); + }); + + test('tempradio is sent after every other command', () { + final ordered = withRetuneLast([ + 'set name X', + 'tempradio 909.75,500.0,10,5,1440', + 'set tx 20', + 'set repeat on', + ], isRetuneCommand); + expect(ordered, [ + 'set name X', + 'set tx 20', + 'set repeat on', + 'tempradio 909.75,500.0,10,5,1440', + ]); + }); + + test('without tempradio the order is unchanged', () { + final commands = [ + 'set name X', + 'set radio 908.205,62.5,9,8', + 'set tx 20', + ]; + expect(withRetuneLast(commands, isRetuneCommand), commands); + }); + }); + + group('preset path hash on remote nodes (#735)', () { + test('published bytes become the zero-based CLI mode', () { + final philly = preset('philly', hashBytes: 2); + final socal = preset('socal', hashBytes: 3); + expect( + setPathHashModeCommand(philly.pathHashMode!), + 'set path.hash.mode 1', + ); + expect( + setPathHashModeCommand(socal.pathHashMode!), + 'set path.hash.mode 2', + ); + expect(preset('usa').pathHashMode, isNull); + }); + + test('a preset path hash is held back from a temporary change', () { + expect( + sendsPresetPathHash(temporaryRadio: true, pathHashFromPreset: true), + isFalse, + ); + expect( + sendsPresetPathHash(temporaryRadio: false, pathHashFromPreset: true), + isTrue, + ); + }); + + test('a path hash set by hand is always sent', () { + expect( + sendsPresetPathHash(temporaryRadio: true, pathHashFromPreset: false), + isTrue, + ); + expect( + sendsPresetPathHash(temporaryRadio: false, pathHashFromPreset: false), + isTrue, + ); + }); + }); + + group('matchRemotePresetId (#734)', () { + final presets = [ + preset('arizona', tx: 20), + preset( + 'oki', + mhz: 909.75, + bw: LoRaBandwidth.bw500, + sf: LoRaSpreadingFactor.sf10, + cr: LoRaCodingRate.cr4_5, + ), + ]; + + test('matches the frequency a repeater reports, to the nearest kHz', () { + expect( + matchRemotePresetId( + presets, + frequencyText: '908.205017', + bandwidthHz: 62500, + spreadingFactor: 9, + codingRate: 8, + pathHashMode: 0, + ), + 'arizona', + ); + expect( + matchRemotePresetId( + presets, + frequencyText: '909.750', + bandwidthHz: 500000, + spreadingFactor: 10, + codingRate: 5, + pathHashMode: 0, + ), + 'oki', + ); + }); + + test('any differing value means custom (null)', () { + expect( + matchRemotePresetId( + presets, + frequencyText: '908.205', + bandwidthHz: 62500, + spreadingFactor: 9, + codingRate: 5, + pathHashMode: 0, + ), + isNull, + ); + expect( + matchRemotePresetId( + presets, + frequencyText: '908.300', + bandwidthHz: 62500, + spreadingFactor: 9, + codingRate: 8, + pathHashMode: 0, + ), + isNull, + ); + }); + + test('unknown or unparsable fields match nothing', () { + expect( + matchRemotePresetId( + presets, + frequencyText: '', + bandwidthHz: 62500, + spreadingFactor: 9, + codingRate: 8, + pathHashMode: 0, + ), + isNull, + ); + expect( + matchRemotePresetId( + presets, + frequencyText: '908.205', + bandwidthHz: null, + spreadingFactor: 9, + codingRate: 8, + pathHashMode: 0, + ), + isNull, + ); + }); + + test('a path hash preset only matches a node on that mode (#747)', () { + final usaPair = [ + preset( + 'canada', + mhz: 910.525, + sf: LoRaSpreadingFactor.sf7, + cr: LoRaCodingRate.cr4_5, + hashBytes: 3, + ), + preset( + 'usa', + mhz: 910.525, + sf: LoRaSpreadingFactor.sf7, + cr: LoRaCodingRate.cr4_5, + ), + ]; + String? match(int mode) => matchRemotePresetId( + usaPair, + frequencyText: '910.525', + bandwidthHz: 62500, + spreadingFactor: 7, + codingRate: 5, + pathHashMode: mode, + ); + expect(match(0), 'usa'); + expect(match(1), 'usa'); + expect(match(2), 'canada'); + }); + }); +} diff --git a/test/models/contact_share_uri_test.dart b/test/models/contact_share_uri_test.dart new file mode 100644 index 00000000..8ed02f8c --- /dev/null +++ b/test/models/contact_share_uri_test.dart @@ -0,0 +1,380 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; + +/// A synthetic 64-hex key. Not a real node. +const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; + +void main() { + group('Contact share URI (#625)', () { + test('parses the documented spec example verbatim', () { + // Straight from the firmware docs/qr_codes.md "Add Contact" example. + final c = Contact.fromShareUri( + 'meshcore://contact/add' + '?name=Example+Contact' + '&public_key=9cd8fcf22a47333b591d96a2b848b73f457b1bb1a3ea2453a885f9e5787765b1' + '&type=1', + ); + expect(c, isNotNull); + // `+` must decode to a space, or stock-emitted names arrive mangled. + expect(c!.name, 'Example Contact'); + expect( + c.publicKeyHex, + '9cd8fcf22a47333b591d96a2b848b73f457b1bb1a3ea2453a885f9e5787765b1', + ); + expect(c.type, advTypeChat); + }); + + test('percent-encoded names round-trip, including emoji', () { + final c = Contact.fromShareUri( + 'meshcore://contact/add?name=${Uri.encodeComponent('DIRT WIZARD 🧙')}' + '&public_key=$_key&type=1', + ); + expect(c, isNotNull); + expect(c!.name, 'DIRT WIZARD 🧙'); + }); + + test('a parsed contact is an unverified stub, not a routed contact', () { + final c = Contact.fromShareUri( + 'meshcore://contact/add?name=Bob&public_key=$_key&type=1', + )!; + + // The load-bearing assertion for #620: lastSeen maps to the firmware's + // last_advert_timestamp. Anything other than the epoch would trip the + // advert replay guard and leave this contact permanently deaf to its + // own adverts. + expect(c.lastSeen, DateTime.fromMillisecondsSinceEpoch(0)); + + // Flood until a path is learned. + expect(c.pathLength, -1); + expect(c.path, isEmpty); + + // No signed advert, so it cannot be re-shared yet. + expect(c.rawPacket, isNull); + expect(c.flags, 0); + }); + + test('type is optional and defaults to companion', () { + final c = Contact.fromShareUri( + 'meshcore://contact/add?name=Bob&public_key=$_key', + ); + expect(c, isNotNull); + expect(c!.type, advTypeChat); + }); + + test('accepts every documented contact type', () { + for (final t in [ + advTypeChat, + advTypeRepeater, + advTypeRoom, + advTypeSensor, + ]) { + final c = Contact.fromShareUri( + 'meshcore://contact/add?name=N&public_key=$_key&type=$t', + ); + expect(c, isNotNull, reason: 'type $t should parse'); + expect(c!.type, t); + } + }); + + test('rejects an out-of-range or non-numeric type', () { + for (final t in ['0', '5', '255', '-1', 'chat', '1.5']) { + expect( + Contact.fromShareUri( + 'meshcore://contact/add?name=N&public_key=$_key&type=$t', + ), + isNull, + reason: 'type "$t" should be rejected', + ); + } + }); + + test('a missing name falls back rather than failing the add', () { + final c = Contact.fromShareUri( + 'meshcore://contact/add?public_key=$_key&type=1', + ); + expect(c, isNotNull); + expect(c!.name, 'Unknown'); + }); + + test('rejects a malformed or wrong-length public key', () { + final bad = [ + '', // absent value + '00112233', // too short + '${_key}ff', // too long + _key.replaceRange(0, 2, 'zz'), // right length, not hex + ]; + for (final k in bad) { + expect( + Contact.fromShareUri( + 'meshcore://contact/add?name=N&public_key=$k&type=1', + ), + isNull, + reason: 'key "$k" should be rejected', + ); + } + // Entirely absent parameter. + expect( + Contact.fromShareUri('meshcore://contact/add?name=N&type=1'), + isNull, + ); + }); + + test('rejects the wrong scheme, host or path', () { + final bad = [ + 'https://contact/add?public_key=$_key', + 'meshcore://channel/add?public_key=$_key', + 'meshcore://contact/remove?public_key=$_key', + 'meshcore://contact?public_key=$_key', + 'not a uri at all', + '', + ]; + for (final u in bad) { + expect(Contact.fromShareUri(u), isNull, reason: '"$u" should reject'); + } + }); + + test('leading and trailing whitespace is tolerated', () { + expect( + Contact.fromShareUri( + ' meshcore://contact/add?name=N&public_key=$_key&type=1\n', + ), + isNotNull, + ); + }); + + test( + 'returns null for the legacy advert-hex form so callers fall back', + () { + // The fork's older share format is `meshcore://`, whose + // host is the hex itself. It carries a full signed advert and must keep + // going down its own import path, not this one. + expect(Contact.fromShareUri('meshcore://${_key}aabbcc'), isNull); + }, + ); + + test('isValidShareUri agrees with fromShareUri', () { + const good = 'meshcore://contact/add?name=N&public_key=$_key&type=2'; + expect(Contact.isValidShareUri(good), isTrue); + expect(Contact.isValidShareUri('meshcore://channel/add?name=x'), isFalse); + }); + }); + + group('Contact share URI emit (#626)', () { + Contact stub(String name, int type) => Contact( + publicKey: hex2Uint8List(_key), + name: name, + type: type, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + + test('buildShareUri emits the documented parameter shape', () { + expect( + Contact.buildShareUri(publicKeyHex: _key, name: 'Bob', type: 2), + 'meshcore://contact/add?name=Bob&public_key=$_key&type=2', + ); + }); + + test('type defaults to companion when not supplied', () { + expect( + Contact.buildShareUri(publicKeyHex: _key, name: 'Bob'), + endsWith('&type=$advTypeChat'), + ); + }); + + test('toShareUri round-trips through fromShareUri', () { + for (final name in [ + 'Bob', + 'Two Words', + 'DIRT WIZARD 🧙', + 'amp&equals=hash#q', + 'Ka8sbi', + ]) { + final original = stub(name, advTypeRepeater); + final back = Contact.fromShareUri(original.toShareUri()); + expect(back, isNotNull, reason: 'name "$name" should round-trip'); + expect(back!.name, name); + expect(back.publicKeyHex, original.publicKeyHex); + expect(back.type, original.type); + } + }); + + test('reserved characters in a name are encoded, not emitted raw', () { + // A raw & or = would silently truncate or forge query parameters. + final uri = stub('a&b=c', advTypeChat).toShareUri(); + expect(uri.contains('name=a&b=c'), isFalse); + expect(Contact.fromShareUri(uri)!.name, 'a&b=c'); + }); + + test('every documented type survives a round-trip', () { + for (final t in [ + advTypeChat, + advTypeRepeater, + advTypeRoom, + advTypeSensor, + ]) { + expect(Contact.fromShareUri(stub('N', t).toShareUri())!.type, t); + } + }); + + test('what we emit is what we accept', () { + expect( + Contact.isValidShareUri(stub('N', advTypeChat).toShareUri()), + true, + ); + }); + }); + + group('Compact channel contact share (#611)', () { + Contact stub(String name, int type) => Contact( + publicKey: hex2Uint8List(_key), + name: name, + type: type, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + + test('matches the shape observed on the live mesh', () { + // Real traffic in #test and #hamradio carries , with the + // angle brackets as literal delimiters. Key is synthetic here; the repo + // is public. + expect( + Contact.buildChannelShare(publicKeyHex: _key, name: 'KE8AFF', type: 1), + '<$_key:1:KE8AFF>', + ); + }); + + test('a name with spaces is carried verbatim', () { + // One of the two observed samples was "Roger KY4RS". + expect( + Contact.buildChannelShare( + publicKeyHex: _key, + name: 'Roger KY4RS', + type: advTypeChat, + ), + '<$_key:1:Roger KY4RS>', + ); + }); + + test('angle brackets are stripped from the name', () { + // A bracket in the name would truncate the payload for every parser + // reading it, so the emitter must not produce one. + final out = Contact.buildChannelShare( + publicKeyHex: _key, + name: 'wename', + type: advTypeChat, + ); + expect(out, '<$_key:1:weirdname>'); + expect('>'.allMatches(out).length, 1); + expect('<'.allMatches(out).length, 1); + }); + + test('a colon in the name survives, since the name is the final field', () { + // A correct parser splits on the first two colons and takes the rest as + // the name, so this needs no escaping. + expect( + Contact.buildChannelShare( + publicKeyHex: _key, + name: 'a:b', + type: advTypeChat, + ), + '<$_key:1:a:b>', + ); + }); + + test('every documented type is emitted numerically', () { + for (final t in [ + advTypeChat, + advTypeRepeater, + advTypeRoom, + advTypeSensor, + ]) { + expect( + Contact.buildChannelShare(publicKeyHex: _key, name: 'N', type: t), + '<$_key:$t:N>', + ); + } + }); + + test('toChannelShare uses the contact own key, type and name', () { + expect(stub('Bob', advTypeRepeater).toChannelShare(), '<$_key:2:Bob>'); + }); + + test('what we emit, we can also parse back', () { + // Without this the app would emit a format it could not itself accept, + // and pasting our own card into the add dialog would be rejected. + final c = stub('Roger KY4RS', advTypeRepeater); + final back = Contact.fromChannelShare(c.toChannelShare()); + expect(back, isNotNull); + expect(back!.publicKeyHex, _key); + expect(back.name, 'Roger KY4RS'); + expect(back.type, advTypeRepeater); + // Same unverified stub as the URI path. + expect(back.lastSeen, DateTime.fromMillisecondsSinceEpoch(0)); + expect(back.pathLength, -1); + }); + + test('a name containing colons survives the split', () { + // The name is the final field, so the parser must split on the first two + // colons only. Splitting on the last one would eat the name. + final back = Contact.fromChannelShare('<$_key:1:a:b:c>'); + expect(back, isNotNull); + expect(back!.name, 'a:b:c'); + }); + + test('a card embedded in a longer message is still found', () { + // This is how it actually arrives: someone captions their card. + final back = Contact.fromChannelShare( + 'here is mine <$_key:1:Bob> add me', + ); + expect(back, isNotNull); + expect(back!.name, 'Bob'); + }); + + test('emoji and CJK names round-trip', () { + for (final n in ['DIRT WIZARD 🧙', '中文节点', 'ノード']) { + final back = Contact.fromChannelShare( + Contact.buildChannelShare(publicKeyHex: _key, name: n), + ); + expect(back, isNotNull, reason: 'name "$n" should parse'); + expect(back!.name, n); + } + }); + + test('rejects malformed cards', () { + for (final bad in [ + '<$_key:1>', // only one colon + '<$_key>', // no colons + '<0011:1:Bob>', // key too short + '<${_key}ff:1:Bob>', // key too long + '<${_key.replaceRange(0, 2, 'zz')}:1:Bob>', // not hex + '<$_key:9:Bob>', // type out of range + '<$_key:x:Bob>', // type not numeric + 'no brackets at all', + '', + ]) { + expect( + Contact.fromChannelShare(bad), + isNull, + reason: '"$bad" should be rejected', + ); + } + }); + + test('the compact form is materially cheaper than the URI', () { + // This is the whole reason both formats exist. Channel text shares a + // 160-byte payload with the "Sender: " prefix, so the difference is + // airtime, not tidiness. + final c = stub('KE8AFF', advTypeChat); + final compact = c.toChannelShare().length; + final uri = c.toShareUri().length; + expect(compact, lessThan(uri)); + expect(uri - compact, greaterThan(30)); + }); + }); +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 9402a654..5f3d76ab 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -278,6 +278,20 @@ void main() { expect(settings.maxMessageRetries, equals(5)); }); + test('experimentalUnlocked defaults off and round-trips (#509)', () { + expect(AppSettings().experimentalUnlocked, isFalse); + + final unlocked = AppSettings().copyWith(experimentalUnlocked: true); + expect(unlocked.experimentalUnlocked, isTrue); + expect(unlocked.toJson()['experimental_unlocked'], isTrue); + + final restored = AppSettings.fromJson(unlocked.toJson()); + expect(restored.experimentalUnlocked, isTrue); + + // Missing key (older persisted settings) defaults to locked. + expect(AppSettings.fromJson({}).experimentalUnlocked, isFalse); + }); + test('toJson includes all new fields', () { final settings = AppSettings(); final json = settings.toJson(); diff --git a/test/models/radio_preset_test.dart b/test/models/radio_preset_test.dart new file mode 100644 index 00000000..b2dd13d7 --- /dev/null +++ b/test/models/radio_preset_test.dart @@ -0,0 +1,285 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/models/radio_settings.dart'; + +String upstream(List> entries, {int version = 1}) => + jsonEncode({ + 'format': kUpstreamPresetFormat, + 'format_version': version, + 'source': 'https://api.meshcore.nz/api/v1/config', + 'credit': 'Liam Cottle / MeshCore', + 'updated_at': '2026-10-01T00:00:00Z', + 'suggested_radio_settings': {'entries': entries}, + }); + +String overlay(List> presets, {int version = 1}) => + jsonEncode({ + 'format': kOverlayPresetFormat, + 'format_version': version, + 'presets': presets, + }); + +Map overlayEntry(String id, {Map? extra}) => { + 'id': id, + 'title': 'USA - $id', + 'region': 'USA', + 'frequency': 909.75, + 'bandwidth': 500, + 'spreading_factor': 10, + 'coding_rate': 5, + 'status': 'published', + ...?extra, +}; + +void main() { + group('parseUpstreamPresets (#727)', () { + test('reads the API shape, where numbers are strings', () { + final r = parseUpstreamPresets( + upstream([ + { + 'title': 'USA - Southern California', + 'description': '927.875MHz / SF7 / BW62.5 / CR5 / 3B', + 'frequency': '927.875', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + 'network_settings': {'path_hash_size': 3}, + }, + { + 'title': 'EU/UK (Narrow)', + 'frequency': '869.618', + 'spreading_factor': '8', + 'bandwidth': '62.5', + 'coding_rate': '8', + }, + ]), + ); + expect(r.skipped, 0); + final socal = r.presets[0]; + expect(socal.id, 'meshcore:USA - Southern California'); + expect(socal.region, 'USA'); + expect(socal.frequencyKHz, 927875); + expect(socal.bandwidth, LoRaBandwidth.bw62_5); + expect(socal.spreadingFactor, LoRaSpreadingFactor.sf7); + expect(socal.codingRate, LoRaCodingRate.cr4_5); + expect(socal.pathHashBytes, 3); + expect(socal.txPowerDbm, isNull); + expect(socal.source, RadioPresetSource.meshcore); + expect(r.presets[1].codingRate, LoRaCodingRate.cr4_8); + expect(r.presets[1].pathHashBytes, isNull); + }); + + test('skips and counts malformed entries instead of failing', () { + final r = parseUpstreamPresets( + upstream([ + { + 'title': 'Good', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + }, + { + 'title': 'Bad BW', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '63', + 'coding_rate': '5', + }, + { + 'title': 'Bad hash', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + 'network_settings': {'path_hash_size': 4}, + }, + {'title': 'Missing values'}, + ]), + ); + expect(r.presets.map((p) => p.title), ['Good']); + expect(r.skipped, 3); + }); + + test('rejects a wrong format or a newer format_version', () { + expect( + () => parseUpstreamPresets(overlay([])), + throwsA(isA()), + ); + expect( + () => parseUpstreamPresets(upstream([], version: 2)), + throwsA(isA()), + ); + expect( + () => parseUpstreamPresets('502'), + throwsA(isA()), + ); + }); + }); + + group('parseOverlayPresets (#727)', () { + test( + 'reads overlay entries with optional TX power, path hash, off-grid', + () { + final r = parseOverlayPresets( + overlay([ + overlayEntry( + 'philly', + extra: {'tx_power': 20, 'path_hash_size': 2}, + ), + overlayEntry( + 'grid', + extra: { + 'region': 'Off-Grid', + 'frequency': 918.0, + 'bandwidth': 250, + 'spreading_factor': 11, + 'coding_rate': 8, + 'off_grid': true, + }, + ), + ]), + ); + expect(r.skipped, 0); + final philly = r.presets[0]; + expect(philly.id, 'offband:philly'); + expect(philly.bandwidth, LoRaBandwidth.bw500); + expect(philly.txPowerDbm, 20); + expect(philly.pathHashBytes, 2); + expect(philly.source, RadioPresetSource.offband); + expect(philly.offGrid, isFalse); + expect(r.presets[1].offGrid, isTrue); + expect(r.presets[1].region, 'Off-Grid'); + }, + ); + + test('drops retired entries without counting them as skipped', () { + final r = parseOverlayPresets( + overlay([ + overlayEntry('old', extra: {'status': 'retired'}), + overlayEntry('new'), + ]), + ); + expect(r.presets.map((p) => p.id), ['offband:new']); + expect(r.skipped, 0); + }); + + test('skips hand-edit mistakes: string numbers, bad TX, bad hash', () { + final r = parseOverlayPresets( + overlay([ + overlayEntry('a', extra: {'frequency': '909.75'}), + overlayEntry('b', extra: {'tx_power': 40}), + overlayEntry('c', extra: {'path_hash_size': '2'}), + overlayEntry('d', extra: {'coding_rate': 4}), + ]), + ); + expect(r.presets, isEmpty); + expect(r.skipped, 4); + }); + }); + + group('upstreamRegionFor (#727)', () { + test('groups upstream titles by their leading region', () { + expect(upstreamRegionFor('USA'), 'USA'); + expect(upstreamRegionFor('USA - Southern California'), 'USA'); + expect(upstreamRegionFor('Australia: QLD'), 'Australia'); + expect(upstreamRegionFor('Australia (Narrow)'), 'Australia'); + expect(upstreamRegionFor('EU/UK (Narrow)'), 'EU/UK'); + expect(upstreamRegionFor('Portugal 433'), 'Portugal'); + expect(upstreamRegionFor('Portugal 868'), 'Portugal'); + expect(upstreamRegionFor('Costa Rica'), 'Costa Rica'); + expect(upstreamRegionFor('New Zealand (Gisborne)'), 'New Zealand'); + }); + }); + + group('presetPathHashMatches (#747)', () { + final r = parseUpstreamPresets( + upstream([ + { + 'title': 'Canada', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + 'network_settings': {'path_hash_size': 3}, + }, + { + 'title': 'USA', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + }, + ]), + ); + final canada = r.presets[0]; + final usa = r.presets[1]; + + test('a preset with a path hash only fits a radio on that size', () { + expect(presetPathHashMatches(canada, 3), isTrue); + expect(presetPathHashMatches(canada, 2), isFalse); + expect(presetPathHashMatches(canada, 1), isFalse); + }); + + test('a preset without one fits any radio', () { + for (final bytes in [1, 2, 3]) { + expect(presetPathHashMatches(usa, bytes), isTrue); + } + }); + + test('a USA radio on 1- or 2-byte hashes is not mistaken for Canada', () { + // Same radio values; Canada sorts first by region, so without the + // path hash check it wins (the D1 screenshot). + for (final bytes in [1, 2]) { + final fitting = r.presets + .where((p) => presetPathHashMatches(p, bytes)) + .map((p) => p.title); + expect(fitting, ['USA']); + } + }); + }); + + group('path hash bytes to firmware mode (#649)', () { + test('published bytes map to the zero-based firmware mode', () { + expect(pathHashModeForBytes(1), 0); + expect(pathHashModeForBytes(2), 1); + expect(pathHashModeForBytes(3), 2); + }); + + test('a published 2 never becomes mode 2 (3-byte hashes)', () { + expect(pathHashModeForBytes(2), isNot(2)); + }); + + test('absent or out-of-range sizes send nothing', () { + expect(pathHashModeForBytes(null), isNull); + expect(pathHashModeForBytes(0), isNull); + expect(pathHashModeForBytes(4), isNull); + }); + + test('a parsed preset exposes its mode', () { + final r = parseUpstreamPresets( + upstream([ + { + 'title': 'Canada', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + 'network_settings': {'path_hash_size': 3}, + }, + { + 'title': 'USA', + 'frequency': '910.525', + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', + }, + ]), + ); + expect(r.presets[0].pathHashMode, 2); + expect(r.presets[1].pathHashMode, isNull); + }); + }); +} diff --git a/test/models/stock_config_test.dart b/test/models/stock_config_test.dart new file mode 100644 index 00000000..b3ca0b23 --- /dev/null +++ b/test/models/stock_config_test.dart @@ -0,0 +1,448 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/stock_config.dart'; + +/// All key material in this file is synthetic and obviously fake. Real stock +/// exports carry a live node private key and channel PSKs and must never enter +/// the repository (#568). +const String fakePublicKey = + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; +const String fakePrivateKey = + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + +/// 32 hex characters = the 16-byte channel PSK. +const String fakeChannelSecret = 'cccccccccccccccccccccccccccccccc'; + +Map contactJson({ + String name = 'Node', + String? customName, + String publicKey = fakePublicKey, + int type = 1, + int flags = 0, + String latitude = '0.0', + String longitude = '0.0', + int lastAdvert = 1785706493, + int lastModified = 1785706508, + Object? outPathList, +}) => { + 'type': type, + 'name': name, + 'custom_name': customName, + 'public_key': publicKey, + 'flags': flags, + 'latitude': latitude, + 'longitude': longitude, + 'last_advert': lastAdvert, + 'last_modified': lastModified, + 'out_path_list': outPathList, +}; + +Map fullConfigJson() => { + 'name': 'Test Radio', + 'public_key': fakePublicKey, + 'private_key': fakePrivateKey, + 'radio_settings': { + 'frequency': 910525, + 'bandwidth': 62500, + 'spreading_factor': 7, + 'coding_rate': 5, + 'tx_power': 22, + }, + 'position_settings': {'latitude': '39.561991', 'longitude': '-84.635731'}, + 'other_settings': {'manual_add_contacts': 1, 'advert_location_policy': 0}, + 'auto_add_settings': { + 'auto_add_chat': true, + 'auto_add_repeater': true, + 'auto_add_room_server': false, + 'auto_add_sensor': false, + 'overwrite_oldest': true, + 'auto_add_max_hops': 0, + }, + 'channels': [ + {'name': 'Public', 'secret': fakeChannelSecret}, + ], + 'contacts': [contactJson()], +}; + +void main() { + group('round trip', () { + test('a full config survives parse then encode unchanged', () { + final source = jsonEncode(fullConfigJson()); + + final reencoded = StockConfig.parse(source).encode(); + + expect(jsonDecode(reencoded), fullConfigJson()); + }); + + test('radio settings keep their raw values and units', () { + final radio = StockConfig.parse( + jsonEncode(fullConfigJson()), + ).radioSettings!; + + // frequency is kHz, bandwidth is Hz, coding_rate is a bare denominator. + expect(radio.frequencyKhz, 910525); + expect(radio.bandwidthHz, 62500); + expect(radio.codingRate, 5); + }); + + test('coordinates are emitted as strings, never numbers', () { + final encoded = + jsonDecode(StockConfig.parse(jsonEncode(fullConfigJson())).encode()) + as Map; + + expect(encoded['position_settings']['latitude'], isA()); + expect(encoded['position_settings']['latitude'], '39.561991'); + expect((encoded['contacts'] as List).first['latitude'], '0.0'); + }); + }); + + group('optional sections', () { + test('a config with no sections at all parses to all nulls', () { + final config = StockConfig.parse('{}'); + + expect(config.name, isNull); + expect(config.publicKey, isNull); + expect(config.channels, isNull); + expect(config.contacts, isNull); + }); + + test('an identity-only export parses, mirroring stock 272-byte files', () { + final config = StockConfig.parse( + jsonEncode({ + 'name': 'Test Radio', + 'public_key': fakePublicKey, + 'private_key': fakePrivateKey, + }), + ); + + expect(config.name, 'Test Radio'); + expect(config.privateKey, hasLength(64)); + expect(config.radioSettings, isNull); + expect(config.contacts, isNull); + }); + + test( + 'identity deselected omits both key fields, not just the private one', + () { + final json = fullConfigJson() + ..remove('public_key') + ..remove('private_key'); + + final encoded = + jsonDecode(StockConfig.parse(jsonEncode(json)).encode()) + as Map; + + expect(encoded.containsKey('public_key'), isFalse); + expect(encoded.containsKey('private_key'), isFalse); + }, + ); + + test('a public key without a private key is still accepted', () { + // Observed in a 2026-08-07 export, a combination current stock does not + // produce. The format has no version field, so the reader tolerates it. + final json = fullConfigJson()..remove('private_key'); + + final config = StockConfig.parse(jsonEncode(json)); + + expect(config.publicKey, hasLength(32)); + expect(config.privateKey, isNull); + }); + + test('absent sections are omitted rather than written as null', () { + final encoded = + jsonDecode(const StockConfig(name: 'Bare').encode()) + as Map; + + expect(encoded.keys, ['name']); + }); + + test('an empty contact list is distinct from an absent one', () { + expect(StockConfig.parse('{"contacts":[]}').contacts, isEmpty); + expect(StockConfig.parse('{}').contacts, isNull); + }); + + test('unknown top-level keys are ignored, not rejected', () { + final json = fullConfigJson()..['some_future_section'] = {'a': 1}; + + expect(StockConfig.parse(jsonEncode(json)).name, 'Test Radio'); + }); + }); + + group('channels', () { + test('array position is the index, since records carry none', () { + final config = StockConfig.parse( + jsonEncode({ + 'channels': [ + {'name': 'First', 'secret': fakeChannelSecret}, + {'name': 'Second', 'secret': fakeChannelSecret}, + ], + }), + ); + + expect(config.channels!.map((c) => c.name), ['First', 'Second']); + expect(config.channels!.first.secret, hasLength(16)); + }); + + test('a secret of the wrong length is rejected with its path', () { + expect( + () => StockConfig.parse('{"channels":[{"name":"X","secret":"aabb"}]}'), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'channels[0].secret', + ), + ), + ); + }); + }); + + group('contacts', () { + test('a 25-character name round trips', () { + final name = 'A' * 25; + final json = { + 'contacts': [contactJson(name: name)], + }; + + expect(StockConfig.parse(jsonEncode(json)).contacts!.first.name, name); + }); + + test('serializing a name longer than the firmware cap throws', () { + final config = StockConfig.parse( + jsonEncode({ + 'contacts': [contactJson(name: 'A' * 32)], + }), + ); + + expect(config.encode, throwsA(isA())); + }); + + test('an implausible far-future timestamp is preserved, not sanitized', () { + // The reference corpus contains values up to the year 2095. + final json = { + 'contacts': [contactJson(lastAdvert: 3950815473, lastModified: 14)], + }; + + final contact = StockConfig.parse(jsonEncode(json)).contacts!.first; + + expect(contact.lastAdvert, 3950815473); + expect(contact.lastModified, 14); + }); + + test('flags bit 0 decodes as favourite', () { + final json = { + 'contacts': [contactJson(flags: 15), contactJson(flags: 0)], + }; + + final contacts = StockConfig.parse(jsonEncode(json)).contacts!; + + expect(contacts[0].isFavourite, isTrue); + expect(contacts[1].isFavourite, isFalse); + }); + + test('a null custom name round trips as null', () { + final config = StockConfig.parse( + jsonEncode({ + 'contacts': [contactJson()], + }), + ); + + expect(config.contacts!.first.customName, isNull); + expect( + (jsonDecode(config.encode())['contacts'] as List).first['custom_name'], + isNull, + ); + }); + }); + + group('out_path_list', () { + test('null and empty string both mean no path', () { + final json = { + 'contacts': [ + contactJson(outPathList: null), + contactJson(outPathList: ''), + ], + }; + + final contacts = StockConfig.parse(jsonEncode(json)).contacts!; + + expect(contacts[0].outPath, isNull); + expect(contacts[1].outPath!.hopCount, 0); + }); + + test('the null and empty-string forms stay distinct on re-encode', () { + // Real exports contain both. We do not know what distinguishes them, so + // collapsing them would discard information we cannot recover. + final json = { + 'contacts': [ + contactJson(outPathList: null), + contactJson(outPathList: ''), + ], + }; + + final encoded = + jsonDecode(StockConfig.parse(jsonEncode(json)).encode())['contacts'] + as List; + + expect(encoded[0]['out_path_list'], isNull); + expect(encoded[1]['out_path_list'], ''); + }); + + test('a width-2 path yields hop count and width without inference', () { + // The only populated path in the reference corpus: two hops, four hex + // characters each. + final json = { + 'contacts': [contactJson(outPathList: 'a1b2,c3d4')], + }; + + final path = StockConfig.parse(jsonEncode(json)).contacts!.first.outPath!; + + expect(path.hashWidth, 2); + expect(path.hopCount, 2); + expect(path.bytes, [0xa1, 0xb2, 0xc3, 0xd4]); + }); + + test('width 1 and width 3 parse even though only width 2 was observed', () { + Map one(String p) => { + 'contacts': [contactJson(outPathList: p)], + }; + + final narrow = StockConfig.parse( + jsonEncode(one('a1,b2,c3')), + ).contacts!.first.outPath!; + final wide = StockConfig.parse( + jsonEncode(one('a1b2c3')), + ).contacts!.first.outPath!; + + expect(narrow.hashWidth, 1); + expect(narrow.hopCount, 3); + expect(wide.hashWidth, 3); + expect(wide.hopCount, 1); + }); + + test('a path round trips to the same string', () { + final json = { + 'contacts': [contactJson(outPathList: 'a1b2,c3d4')], + }; + + final encoded = jsonDecode(StockConfig.parse(jsonEncode(json)).encode()); + + expect((encoded['contacts'] as List).first['out_path_list'], 'a1b2,c3d4'); + }); + + test('mixed hop widths are rejected rather than guessed at', () { + final json = { + 'contacts': [contactJson(outPathList: 'a1b2,c3')], + }; + + expect( + () => StockConfig.parse(jsonEncode(json)), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'contacts[0].out_path_list', + ), + ), + ); + }); + + test('a hop width beyond three bytes is rejected', () { + final json = { + 'contacts': [contactJson(outPathList: 'a1b2c3d4')], + }; + + expect( + () => StockConfig.parse(jsonEncode(json)), + throwsA(isA()), + ); + }); + + test('non-hex hop content is rejected', () { + final json = { + 'contacts': [contactJson(outPathList: 'zzzz,c3d4')], + }; + + expect( + () => StockConfig.parse(jsonEncode(json)), + throwsA(isA()), + ); + }); + }); + + group('malformed input', () { + test('text that is not JSON is rejected', () { + expect( + () => StockConfig.parse('not json at all'), + throwsA(isA()), + ); + }); + + test('a top-level array is rejected', () { + expect( + () => StockConfig.parse('[]'), + throwsA(isA()), + ); + }); + + test('a public key of the wrong length is rejected', () { + expect( + () => StockConfig.parse('{"public_key":"aabb"}'), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'public_key', + ), + ), + ); + }); + + test('a numeric coordinate is rejected, since stock writes strings', () { + expect( + () => StockConfig.parse( + '{"position_settings":{"latitude":39.5,"longitude":-84.6}}', + ), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'position_settings.latitude', + ), + ), + ); + }); + + test('channels given as an object rather than an array is rejected', () { + expect( + () => StockConfig.parse('{"channels":{}}'), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'channels', + ), + ), + ); + }); + + test('the reported path points at the offending contact', () { + final json = { + 'contacts': [contactJson(), contactJson(publicKey: 'aabb')], + }; + + expect( + () => StockConfig.parse(jsonEncode(json)), + throwsA( + isA().having( + (e) => e.path, + 'path', + 'contacts[1].public_key', + ), + ), + ); + }); + }); +} diff --git a/test/services/corescope_service_test.dart b/test/services/corescope_service_test.dart new file mode 100644 index 00000000..47abf8eb --- /dev/null +++ b/test/services/corescope_service_test.dart @@ -0,0 +1,100 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/services/corescope_service.dart'; + +void main() { + group('CoreScopeService.fetchCounts', () { + test('found: parses observer + observation counts', () async { + late Uri captured; + final service = CoreScopeService( + host: 'map.okimesh.org', + client: MockClient((req) async { + captured = req.url; + return http.Response( + '{"packets":[{"hash":"abc123","observer_count":15,' + '"observation_count":34}],"total":1}', + 200, + ); + }), + ); + + final result = await service.fetchCounts('abc123'); + expect(result.status, CoreScopeStatus.found); + expect(result.counts!.observers, 15); + expect(result.counts!.observations, 34); + expect(captured.host, 'map.okimesh.org'); + expect(captured.path, '/api/packets'); + expect(captured.queryParameters['hash'], 'abc123'); + expect(captured.queryParameters['groupByHash'], 'true'); + }); + + test('found: observations falls back to observers when absent', () async { + final service = CoreScopeService( + client: MockClient( + (_) async => http.Response('{"packets":[{"observer_count":9}]}', 200), + ), + ); + final result = await service.fetchCounts('abc123'); + expect(result.status, CoreScopeStatus.found); + expect(result.counts!.observers, 9); + expect(result.counts!.observations, 9); + }); + + test('notFound: reachable but empty packets (the #571 case)', () async { + final service = CoreScopeService( + client: MockClient( + (_) async => http.Response('{"packets":[],"total":0}', 200), + ), + ); + final result = await service.fetchCounts('deadbeef'); + expect(result.status, CoreScopeStatus.notFound); + expect(result.counts, isNull); + }); + + test('unreachable on non-200', () async { + final service = CoreScopeService( + client: MockClient((_) async => http.Response('nope', 503)), + ); + expect( + (await service.fetchCounts('abc123')).status, + CoreScopeStatus.unreachable, + ); + }); + + test('unreachable on malformed body', () async { + final service = CoreScopeService( + client: MockClient((_) async => http.Response('not json', 200)), + ); + expect( + (await service.fetchCounts('abc123')).status, + CoreScopeStatus.unreachable, + ); + }); + + test('unreachable (never throws) on transport failure', () async { + final service = CoreScopeService( + client: MockClient((_) async => throw Exception('offline')), + ); + expect( + (await service.fetchCounts('abc123')).status, + CoreScopeStatus.unreachable, + ); + }); + + test('empty hash: unreachable without hitting the network', () async { + var called = false; + final service = CoreScopeService( + client: MockClient((_) async { + called = true; + return http.Response('{}', 200); + }), + ); + expect( + (await service.fetchCounts('')).status, + CoreScopeStatus.unreachable, + ); + expect(called, isFalse); + }); + }); +} diff --git a/test/services/radio_preset_live_test.dart b/test/services/radio_preset_live_test.dart new file mode 100644 index 00000000..9f9cc730 --- /dev/null +++ b/test/services/radio_preset_live_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/services/config_source_service.dart'; +import 'package:meshcore_open/services/radio_preset_service.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// Fetches the real preset files from config-profiles (#748). Every other +// preset test fakes the network, so a 404 on main passed them all and the +// owner saw "Couldn't update presets" on a test build twice. This one fails +// whenever the app's own refresh would. +void main() { + test( + 'refresh from config-profiles succeeds with no error', + () async { + SharedPreferences.setMockInitialValues({}); + final service = RadioPresetService( + prefs: await SharedPreferences.getInstance(), + loadAsset: (_) async => throw StateError('bundled copies not used'), + ); + addTearDown(service.dispose); + + final ok = await service.refresh(); + + expect(service.refreshError, isNull, reason: 'refresh reported an error'); + expect(ok, isTrue); + expect(service.skipped, 0); + final sources = service.presets.map((p) => p.source).toSet(); + expect(sources, {RadioPresetSource.meshcore, RadioPresetSource.offband}); + }, + timeout: const Timeout(Duration(seconds: 60)), + ); + + test( + 'a missing file on config-profiles is reported, not ignored', + () async { + final source = ConfigSourceService(); + addTearDown(source.dispose); + await expectLater( + source.fetchText('${kRadioPresetBaseUrl}missing-748.json'), + throwsA( + isA().having( + (e) => '$e', + 'message', + contains('HTTP 404'), + ), + ), + ); + }, + timeout: const Timeout(Duration(seconds: 60)), + ); +} diff --git a/test/services/radio_preset_service_test.dart b/test/services/radio_preset_service_test.dart new file mode 100644 index 00000000..b385163c --- /dev/null +++ b/test/services/radio_preset_service_test.dart @@ -0,0 +1,293 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/models/radio_settings.dart'; +import 'package:meshcore_open/services/radio_preset_service.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +String upstreamFile(List> entries) => jsonEncode({ + 'format': kUpstreamPresetFormat, + 'format_version': 1, + 'source': 'https://api.meshcore.nz/api/v1/config', + 'credit': 'Liam Cottle / MeshCore', + 'updated_at': '2026-10-01T00:00:00Z', + 'suggested_radio_settings': {'entries': entries}, +}); + +String overlayFile(List> presets) => jsonEncode({ + 'format': kOverlayPresetFormat, + 'format_version': 1, + 'presets': presets, +}); + +Map up(String title, {String freq = '910.525'}) => { + 'title': title, + 'frequency': freq, + 'spreading_factor': '7', + 'bandwidth': '62.5', + 'coding_rate': '5', +}; + +Map ov( + String id, + String title, { + double freq = 909.75, + String region = 'USA', +}) => { + 'id': id, + 'title': title, + 'region': region, + 'frequency': freq, + 'bandwidth': 500, + 'spreading_factor': 10, + 'coding_rate': 5, + 'status': 'published', +}; + +RadioPreset preset(String title, String region, RadioPresetSource source) => + RadioPreset( + id: '$source:$title', + title: title, + region: region, + frequencyMHz: 910.525, + bandwidth: LoRaBandwidth.bw62_5, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + source: source, + ); + +void main() { + late SharedPreferences prefs; + final bundled = { + '${kRadioPresetAssetDir}meshcore-upstream.json': upstreamFile([ + up('USA'), + up('Canada'), + ]), + '${kRadioPresetAssetDir}offband.json': overlayFile([ + ov('oki', 'USA - OKI-Mesh 500kHz Test'), + ]), + }; + + Future loadBundled(String path) async { + final text = bundled[path]; + if (text == null) throw StateError('no asset $path'); + return text; + } + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + prefs = await SharedPreferences.getInstance(); + }); + + RadioPresetService service({ + Map? remote, + Object? remoteError, + DateTime Function()? clock, + }) => RadioPresetService( + prefs: prefs, + loadAsset: loadBundled, + clock: clock, + fetch: (url) async { + if (remoteError != null) throw remoteError; + final file = url.substring(kRadioPresetBaseUrl.length); + final text = remote?[file]; + if (text == null) throw StateError('HTTP 404 for $url'); + return text; + }, + ); + + group('mergeRadioPresets (#728)', () { + test('an overlay entry replaces the upstream one with the same title', () { + final merged = mergeRadioPresets( + [ + preset('USA', 'USA', RadioPresetSource.meshcore), + preset('Canada', 'Canada', RadioPresetSource.meshcore), + ], + [preset('usa', 'USA', RadioPresetSource.offband)], + ); + expect(merged.length, 2); + final usa = merged.firstWhere((p) => p.title.toLowerCase() == 'usa'); + expect(usa.source, RadioPresetSource.offband); + }); + + test('sorts by region, then title', () { + final merged = mergeRadioPresets( + [ + preset('USA', 'USA', RadioPresetSource.meshcore), + preset('Australia', 'Australia', RadioPresetSource.meshcore), + ], + [preset('USA - Arizona', 'USA', RadioPresetSource.offband)], + ); + expect(merged.map((p) => p.title), ['Australia', 'USA', 'USA - Arizona']); + }); + }); + + group('RadioPresetService (#728)', () { + test('offline: loads the bundled copies when nothing is saved', () async { + final s = service(); + await s.load(); + expect(s.presets.map((p) => p.title), [ + 'Canada', + 'USA', + 'USA - OKI-Mesh 500kHz Test', + ]); + expect(s.refreshError, isNull); + expect(s.lastRefreshed, isNull); + }); + + test('refresh replaces the list, saves it, and records the time', () async { + final now = DateTime.utc(2026, 10, 1, 12); + final s = service( + clock: () => now, + remote: { + kUpstreamPresetFile: upstreamFile([up('USA'), up('Brazil')]), + kOverlayPresetFile: overlayFile([ + ov('philly', 'USA - Philly Mesh', freq: 919.5), + ]), + }, + ); + await s.load(); + expect(await s.refresh(), isTrue); + expect(s.presets.map((p) => p.title), [ + 'Brazil', + 'USA', + 'USA - Philly Mesh', + ]); + expect(s.refreshError, isNull); + expect(s.lastRefreshed, now); + + // The saved copy is what the next launch starts from, even offline. + final next = service(remoteError: StateError('offline')); + await next.load(); + expect(next.presets.map((p) => p.title), contains('USA - Philly Mesh')); + expect(next.lastRefreshed, now); + }); + + test('an overlay edit reaches the app with no new build', () async { + final s = service( + remote: { + kUpstreamPresetFile: upstreamFile([up('USA')]), + kOverlayPresetFile: overlayFile([ + ov('oki', 'USA - OKI-Mesh 500kHz Test', freq: 911.5), + ]), + }, + ); + await s.load(); + expect( + s.presets.firstWhere((p) => p.id == 'offband:oki').frequencyMHz, + 909.75, + ); + await s.refresh(); + expect( + s.presets.firstWhere((p) => p.id == 'offband:oki').frequencyMHz, + 911.5, + ); + }); + + test('a failed refresh keeps the list in use and reports why', () async { + final s = service(remoteError: StateError('network down')); + await s.load(); + final before = s.presets.map((p) => p.title).toList(); + expect(await s.refresh(), isFalse); + expect(s.presets.map((p) => p.title), before); + expect(s.refreshError, contains('network down')); + expect(s.lastRefreshed, isNull); + expect(prefs.getKeys(), isEmpty); + }); + + test('a bad or empty file never replaces a good copy', () async { + final s = service( + remote: { + kUpstreamPresetFile: '502 Bad Gateway', + kOverlayPresetFile: overlayFile([]), + }, + ); + await s.load(); + expect(await s.refresh(), isFalse); + expect(s.presets.length, 3); + expect(s.refreshError, contains(kUpstreamPresetFile)); + expect(s.refreshError, contains(kOverlayPresetFile)); + }); + + test('one good file is still taken when the other fails', () async { + final s = service( + remote: { + kOverlayPresetFile: overlayFile([ov('az', 'USA - Arizona')]), + }, + ); + await s.load(); + expect(await s.refresh(), isFalse); + expect(s.presets.map((p) => p.title), ['Canada', 'USA', 'USA - Arizona']); + expect(s.refreshError, contains(kUpstreamPresetFile)); + }); + + test('malformed entries are skipped and counted', () async { + final s = service( + remote: { + kUpstreamPresetFile: upstreamFile([ + up('USA'), + {'title': 'Broken'}, + ]), + kOverlayPresetFile: overlayFile([ov('az', 'USA - Arizona')]), + }, + ); + await s.load(); + await s.refresh(); + expect(s.skipped, 1); + expect(s.presets.map((p) => p.title), isNot(contains('Broken'))); + }); + + test( + 'refreshIfStale only refreshes an old or never-refreshed copy', + () async { + var now = DateTime.utc(2026, 10, 1, 12); + var fetches = 0; + final s = RadioPresetService( + prefs: prefs, + loadAsset: loadBundled, + clock: () => now, + fetch: (url) async { + fetches++; + return url.endsWith(kUpstreamPresetFile) + ? upstreamFile([up('USA')]) + : overlayFile([ov('az', 'USA - Arizona')]); + }, + ); + await s.load(); + await s.refreshIfStale(); + expect(fetches, 2); + now = now.add(const Duration(hours: 1)); + await s.refreshIfStale(); + expect(fetches, 2); + now = now.add(const Duration(hours: 12)); + await s.refreshIfStale(); + expect(fetches, 4); + }, + ); + }); + + group('bundled preset files (#728)', () { + test('parse cleanly and do not clash on titles', () { + final upstream = parseUpstreamPresets( + File('assets/radio_presets/meshcore-upstream.json').readAsStringSync(), + ); + final overlay = parseOverlayPresets( + File('assets/radio_presets/offband.json').readAsStringSync(), + ); + expect(upstream.skipped, 0); + expect(overlay.skipped, 0); + expect(upstream.presets.length, 26); + expect(overlay.presets.length, 33); + final merged = mergeRadioPresets(upstream.presets, overlay.presets); + expect(merged.length, 59); + final philly = merged.firstWhere((p) => p.title == 'USA - Philly Mesh'); + expect(philly.frequencyKHz, 919500); + expect(philly.bandwidth, LoRaBandwidth.bw500); + expect(philly.pathHashMode, 1); + final euNarrow = merged.firstWhere((p) => p.title == 'EU/UK (Narrow)'); + expect(euNarrow.codingRate, LoRaCodingRate.cr4_8); + }); + }); +} diff --git a/test/services/repeater_command_service_test.dart b/test/services/repeater_command_service_test.dart new file mode 100644 index 00000000..c7913e3b --- /dev/null +++ b/test/services/repeater_command_service_test.dart @@ -0,0 +1,277 @@ +// #528 (epic #473): a repeater CLI reply that arrives with no command waiting +// for it used to hit `if (commandId.isEmpty) return;` and vanish. No log, no +// UI, nothing. Since a command's window can close before the app has even +// finished fetching the message (MSG_WAITING then SYNC_NEXT_MESSAGE), that +// made "the command ran but the response was never reported" the normal +// outcome rather than an edge case. +// +// These tests pin the contract that no reply is ever dropped silently. + +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/services/repeater_command_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Contact _repeater() => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i)), + name: 'Test Repeater', + type: 2, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late RepeaterCommandService service; + late Contact repeater; + late List surfaced; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + + service = RepeaterCommandService(MeshCoreConnector()); + repeater = _repeater(); + surfaced = []; + service.onUnmatchedResponse = surfaced.add; + }); + + tearDown(() => service.dispose()); + + test('a reply with no pending command is surfaced, not discarded', () { + service.handleResponse(repeater, 'Version: 1.2.3'); + + expect(surfaced, hasLength(1)); + expect(surfaced.single.response, 'Version: 1.2.3'); + expect(surfaced.single.repeaterKeyHex, repeater.publicKeyHex); + }); + + test('a reply for a command that already timed out names that command', () { + service.recordExpiredCommandForTest('A3|', 'ver'); + + service.handleResponse(repeater, 'A3|Version: 1.2.3'); + + expect(surfaced, hasLength(1)); + final reply = surfaced.single; + expect(reply.isLateReply, isTrue); + expect(reply.command, 'ver'); + expect(reply.response, 'Version: 1.2.3', reason: 'prefix must be stripped'); + expect(reply.sinceTimeout, isNotNull); + }); + + test('an unattributable reply is still surfaced, just without a command', () { + service.handleResponse(repeater, 'ZZ|unsolicited chatter'); + + expect(surfaced, hasLength(1)); + expect(surfaced.single.isLateReply, isFalse); + expect(surfaced.single.command, isNull); + expect(surfaced.single.response, 'unsolicited chatter'); + }); + + test('an expired command is only consumed once', () { + service.recordExpiredCommandForTest('A3|', 'ver'); + + service.handleResponse(repeater, 'A3|first'); + service.handleResponse(repeater, 'A3|second'); + + expect(surfaced, hasLength(2)); + expect(surfaced[0].command, 'ver'); + expect( + surfaced[1].command, + isNull, + reason: 'the record is consumed by the first reply that claims it', + ); + }); + + test('a reply is never swallowed when no callback is wired', () { + service.onUnmatchedResponse = null; + + // The contract is that this cannot throw and cannot hang. The logging path + // still runs; the absence of a listener must not resurrect the silent drop + // as an unhandled error. + expect( + () => service.handleResponse(repeater, 'orphan reply'), + returnsNormally, + ); + }); + + test('dispose clears the late-reply records', () { + service.recordExpiredCommandForTest('A3|', 'ver'); + service.dispose(); + + // Re-arm a listener on the disposed service and confirm the stale record is + // gone, so a reply after disposal cannot be mis-attributed to it. + final seen = []; + service.onUnmatchedResponse = seen.add; + service.handleResponse(repeater, 'A3|Version: 1.2.3'); + + expect(seen.single.command, isNull); + }); + + group('timeout reporting (#531)', () { + // The old message printed (timeoutMs / 1000).ceil(), so every window in + // (4000, 5000] announced "5 seconds" and the figure shown was never the + // one armed. The owner's 0-hop window was 4074 ms and it claimed 5. + test('reports the armed window to one decimal, not rounded up', () { + const e = RepeaterCommandTimeout(command: 'ver', timeoutMs: 4074); + expect(e.secondsText, '4.1'); + expect(e.toString(), 'Command timed out after 4.1 seconds'); + }); + + test('does not round a sub-second remainder up to the next second', () { + // 28748 ms is the new CLI budget on the owner's preset. ceil() would say + // 29; the armed window is 28.7. + const e = RepeaterCommandTimeout(command: 'status', timeoutMs: 28748); + expect(e.secondsText, '28.7'); + }); + + test('distinct windows in the same second are distinguishable', () { + // The defect's signature: 4001 and 4999 both printed "5 seconds". + const a = RepeaterCommandTimeout(command: 'a', timeoutMs: 4001); + const b = RepeaterCommandTimeout(command: 'b', timeoutMs: 4999); + expect(a.secondsText, isNot(b.secondsText)); + }); + + test('carries the command so a caller can name what timed out', () { + const e = RepeaterCommandTimeout(command: 'get tx', timeoutMs: 1234); + expect(e.command, 'get tx'); + expect(e.timeoutMs, 1234); + }); + }); + + group('reply correlation (#532)', () { + // A reply carrying a prefix identifies itself. Before this fix, a prefix + // that matched nothing pending fell through to "first pending command for + // this repeater", so a straggler from an expired command could complete an + // unrelated one and report its output as that command's result. + // + // Not reachable from today's callers, which all pass retries: 1 and await + // sequentially, but live the moment anything issues concurrent commands. + + test( + 'a stale prefix does NOT complete a different in-flight command', + () async { + final other = service.registerPendingForTest( + repeater.publicKeyHex, + 'B7|', + ); + var otherCompleted = false; + unawaited(other.then((_) => otherCompleted = true)); + + // 'A3|' expired earlier and is no longer pending. + service.recordExpiredCommandForTest('A3|', 'ver'); + service.handleResponse(repeater, 'A3|v1.16.0'); + await Future.delayed(Duration.zero); + + expect( + otherCompleted, + isFalse, + reason: "the 'B7|' command must not be completed by 'A3|' output", + ); + expect(surfaced, hasLength(1)); + expect(surfaced.single.command, 'ver'); + expect(surfaced.single.response, 'v1.16.0'); + }, + ); + + test( + 'an unknown prefix with nothing expired is surfaced, not misapplied', + () async { + final other = service.registerPendingForTest( + repeater.publicKeyHex, + 'B7|', + ); + var otherCompleted = false; + unawaited(other.then((_) => otherCompleted = true)); + + service.handleResponse(repeater, 'ZZ|orphan output'); + await Future.delayed(Duration.zero); + + expect(otherCompleted, isFalse); + expect(surfaced.single.command, isNull); + expect(surfaced.single.response, 'orphan output'); + }, + ); + + test('a matching prefix still completes its own command', () async { + final own = service.registerPendingForTest(repeater.publicKeyHex, 'C1|'); + + service.handleResponse(repeater, 'C1|hello'); + + expect(await own, 'hello'); + expect(surfaced, isEmpty); + }); + + test('an unprefixed reply still falls back to the pending command', () async { + // Preserved behaviour: with no correlation token there is nothing else to + // match on, so position is all we have. + final own = service.registerPendingForTest(repeater.publicKeyHex, 'D2|'); + + service.handleResponse(repeater, 'no prefix here'); + + expect(await own, 'no prefix here'); + expect(surfaced, isEmpty); + }); + }); + + group('unprefixed reply ambiguity (Gemini review)', () { + // #532 constrained PREFIXED replies. An unprefixed one still fell back to + // "first pending command for this repeater", which with two or more in + // flight is map-iteration order, so a caller could receive another + // command's output. + // + // The fallback cannot simply be deleted: firmware only echoes the prefix + // when the command exceeds four characters including it + // (simple_repeater/MyMesh.cpp, `strlen(command) > 4 && command[2] == '|'`), + // so a very short command legitimately replies without one. + + test( + 'with exactly one pending, an unprefixed reply still resolves it', + () async { + final only = service.registerPendingForTest( + repeater.publicKeyHex, + 'E1|', + ); + + service.handleResponse(repeater, 'bare payload'); + + expect(await only, 'bare payload'); + expect(surfaced, isEmpty); + }, + ); + + test('with two pending, an unprefixed reply resolves NEITHER', () async { + final first = service.registerPendingForTest( + repeater.publicKeyHex, + 'E1|', + ); + final second = service.registerPendingForTest( + repeater.publicKeyHex, + 'E2|', + ); + var firstDone = false, secondDone = false; + unawaited(first.then((_) => firstDone = true)); + unawaited(second.then((_) => secondDone = true)); + + service.handleResponse(repeater, 'ambiguous payload'); + await Future.delayed(Duration.zero); + + expect(firstDone, isFalse); + expect(secondDone, isFalse); + expect( + surfaced.single.response, + 'ambiguous payload', + reason: 'ambiguity must be surfaced, never guessed at', + ); + expect(surfaced.single.command, isNull); + }); + }); +} diff --git a/test/services/retry_and_protocol_test.dart b/test/services/retry_and_protocol_test.dart index c957ff8d..0860f2d6 100644 --- a/test/services/retry_and_protocol_test.dart +++ b/test/services/retry_and_protocol_test.dart @@ -709,4 +709,238 @@ void main() { }, ); }); + + group('RESP_CODE_SENT correlation uses the radio hash (#449/#581)', () { + // The radio is authoritative for the expected-ACK hash. Firmware forks + // (Wadamesh on the HV4 TFT, in the #449 capture) build the payload + // differently, so the client's locally recomputed hash can disagree while + // delivery works perfectly. Correlation must not depend on that guess. + const int radioHash = 0xDEADBEEF; // deliberately not the client's value + + test('a RESP_CODE_SENT hash the client did not predict still marks the ' + 'message sent, and its ACK still marks it delivered', () async { + final retryService = MessageRetryService(); + final contact = _makeContact( + publicKey: recipientKey, + pathLength: 2, + path: const [0x10, 0x20], + ); + final updates = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: updates.add, + getSelfPublicKey: () => fixedKey, + ), + ); + + await retryService.sendMessageWithRetry( + contact: contact, + text: 'Weird that I am getting errors though.', + ); + await Future.delayed(const Duration(milliseconds: 20)); + + final matched = retryService.updateMessageFromSent(radioHash, 4884); + + expect( + matched, + isTrue, + reason: + 'the radio replied to our own CMD_SEND_TXT_MSG, so it must be ' + 'correlated even though the hash is not the one we predicted', + ); + expect( + updates.last.status, + equals(MessageStatus.sent), + reason: + 'an unpredicted hash must not leave the message pending, ' + 'because the 8s watchdog would then mark a delivered DM failed', + ); + + // The real ACK carries the radio's hash, not ours. + retryService.handleAckReceived(radioHash, 7354); + + expect( + updates.last.status, + equals(MessageStatus.delivered), + reason: 'the ACK must resolve against the radio-supplied hash', + ); + + retryService.dispose(); + }); + + test('an unpredicted hash is not adopted while two sends are awaiting ' + 'confirmation, because the correlation would be a guess', () async { + final retryService = MessageRetryService(); + final contactA = _makeContact(publicKey: recipientKey, pathLength: 2); + final contactB = _makeContact(publicKey: _makeKey(0x55), pathLength: 2); + final updates = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: updates.add, + getSelfPublicKey: () => fixedKey, + ), + ); + + // Per-contact queues, so two contacts means two in flight at once. + await retryService.sendMessageWithRetry(contact: contactA, text: 'a'); + await retryService.sendMessageWithRetry(contact: contactB, text: 'b'); + await Future.delayed(const Duration(milliseconds: 20)); + + expect( + retryService.updateMessageFromSent(radioHash, 4884), + isFalse, + reason: + 'with two candidates the owner would rather keep the old ' + 'behaviour than attach the confirmation to the wrong message', + ); + + retryService.dispose(); + }); + + test('an unpredicted hash is not adopted while a channel send is also ' + 'awaiting confirmation, because that frame could be either', () async { + final retryService = MessageRetryService(); + final contact = _makeContact(publicKey: recipientKey, pathLength: 2); + final updates = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: updates.add, + getSelfPublicKey: () => fixedKey, + ), + ); + + await retryService.sendMessageWithRetry(contact: contact, text: 'dm'); + await Future.delayed(const Duration(milliseconds: 20)); + + // The connector passes false while _pendingChannelSentQueue is not + // empty. Adopting here would attach a channel message's confirmation + // to this DM and lose both. + expect( + retryService.updateMessageFromSent( + radioHash, + 4884, + allowUnpredictedAdoption: false, + ), + isFalse, + ); + expect( + updates.every((m) => m.status != MessageStatus.sent), + isTrue, + reason: 'the DM must not be marked sent off an ambiguous frame', + ); + + retryService.dispose(); + }); + + test( + 'an unpredicted hash with nothing awaiting confirmation is ignored', + () { + final retryService = MessageRetryService(); + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: (_) {}, + getSelfPublicKey: () => fixedKey, + ), + ); + + expect( + retryService.updateMessageFromSent(radioHash, 4884), + isFalse, + reason: + 'with no send in flight the frame must fall through to the ' + 'channel handler, not be swallowed', + ); + + retryService.dispose(); + }, + ); + + test( + 'a late stray frame is not adopted once the message has resolved', + () async { + final retryService = MessageRetryService(); + final contact = _makeContact(publicKey: recipientKey, pathLength: 2); + final updates = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: updates.add, + getSelfPublicKey: () => fixedKey, + ), + ); + + await retryService.sendMessageWithRetry(contact: contact, text: 'one'); + await Future.delayed(const Duration(milliseconds: 20)); + + expect(retryService.updateMessageFromSent(radioHash, 4884), isTrue); + retryService.handleAckReceived(radioHash, 5000); + expect(updates.last.status, equals(MessageStatus.delivered)); + + // A second, unrelated unpredicted frame arrives afterwards. Nothing is + // awaiting confirmation now, so it must not be attached to anything. + expect( + retryService.updateMessageFromSent(0xFEEDFACE, 4884), + isFalse, + reason: 'a stray frame must not be adopted by a resolved message', + ); + + retryService.dispose(); + }, + ); + + test( + 'a hash the client did predict still matches on the fast path', + () async { + final retryService = MessageRetryService(); + final contact = _makeContact(publicKey: recipientKey, pathLength: 2); + final updates = []; + int? sentTs; + int? sentAttempt; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, attempt, ts) async { + sentAttempt = attempt; + sentTs = ts; + }, + addMessage: (_, _) {}, + updateMessage: updates.add, + getSelfPublicKey: () => fixedKey, + ), + ); + + await retryService.sendMessageWithRetry(contact: contact, text: 'Yep.'); + await Future.delayed(const Duration(milliseconds: 20)); + + final predicted = _manualAckHash( + sentTs!, + sentAttempt! & 0x03, + 'Yep.', + fixedKey, + ); + + expect(retryService.updateMessageFromSent(predicted, 3252), isTrue); + expect(updates.last.status, equals(MessageStatus.sent)); + + retryService.handleAckReceived(predicted, 1200); + expect(updates.last.status, equals(MessageStatus.delivered)); + + retryService.dispose(); + }, + ); + }); } diff --git a/test/services/stock_config_export_service_test.dart b/test/services/stock_config_export_service_test.dart new file mode 100644 index 00000000..3ed8db8f --- /dev/null +++ b/test/services/stock_config_export_service_test.dart @@ -0,0 +1,197 @@ +// #573 (epic #568): mapping live device state onto the stock export format. +// +// The mapping functions are pure, so they are tested directly. The parts that +// need a radio (identity read, connector state) belong to the T1 hardware gate. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/stock_config.dart'; +import 'package:meshcore_open/services/stock_config_export_service.dart'; + +Uint8List bytes(List values) => Uint8List.fromList(values); + +Contact makeContact({ + int type = 1, + int flags = 0, + String name = 'Node', + double? latitude, + double? longitude, + int pathLength = -1, + int pathHashWidth = 1, + List path = const [], + DateTime? lastSeen, + DateTime? lastModified, +}) { + return Contact( + publicKey: Uint8List(32), + name: name, + type: type, + flags: flags, + pathLength: pathLength, + pathHashWidth: pathHashWidth, + path: bytes(path), + latitude: latitude, + longitude: longitude, + lastSeen: lastSeen ?? DateTime.fromMillisecondsSinceEpoch(1785706493000), + lastModified: lastModified, + ); +} + +void main() { + group('channel mapping', () { + test('carries name and psk, and writes no index', () { + final stock = toStockChannel( + Channel(index: 4, name: 'Public', psk: Uint8List(16)), + ); + + expect(stock.name, 'Public'); + expect(stock.secret, hasLength(16)); + expect(stock.toJson().keys, unorderedEquals(['name', 'secret'])); + }); + }); + + group('contact mapping', () { + test('an absent position becomes zero, which is what stock writes', () { + final stock = toStockContact(makeContact()); + + expect(stock.latitude, 0); + expect(stock.toJson()['latitude'], '0.0'); + }); + + test('a position is carried through as a decimal string', () { + final stock = toStockContact( + makeContact(latitude: 39.561991, longitude: -84.635731), + ); + + expect(stock.toJson()['latitude'], '39.561991'); + expect(stock.toJson()['longitude'], '-84.635731'); + }); + + test('timestamps convert to epoch seconds', () { + final stock = toStockContact( + makeContact( + lastSeen: DateTime.fromMillisecondsSinceEpoch(1785706493000), + lastModified: DateTime.fromMillisecondsSinceEpoch(1785706508000), + ), + ); + + expect(stock.lastAdvert, 1785706493); + expect(stock.lastModified, 1785706508); + }); + + test('a contact with no recorded modification falls back to last seen', () { + final stock = toStockContact( + makeContact( + lastSeen: DateTime.fromMillisecondsSinceEpoch(1785706493000), + ), + ); + + expect(stock.lastModified, 1785706493); + }); + + test('a flood route is written as no path', () { + // pathLength of -1 means flood, which stock has no representation for. + final stock = toStockContact(makeContact(pathLength: -1)); + + expect(stock.outPath, isNull); + expect(stock.toJson()['out_path_list'], isNull); + }); + + test('a width-aware path keeps both its hop count and its width', () { + final stock = toStockContact( + makeContact( + pathLength: 2, + pathHashWidth: 2, + path: [0xa1, 0xb2, 0xc3, 0xd4], + ), + ); + + expect(stock.outPath!.hopCount, 2); + expect(stock.outPath!.hashWidth, 2); + expect(stock.toJson()['out_path_list'], 'a1b2,c3d4'); + }); + + test('a single-width path round trips to comma separated bytes', () { + final stock = toStockContact( + makeContact(pathLength: 3, pathHashWidth: 1, path: [0x0a, 0x0b, 0x0c]), + ); + + expect(stock.toJson()['out_path_list'], '0a,0b,0c'); + }); + + test('trailing path bytes beyond the hop count are not written', () { + // The buffer can be longer than the live path; only hopCount * width + // bytes are meaningful. + final stock = toStockContact( + makeContact( + pathLength: 1, + pathHashWidth: 2, + path: [0xa1, 0xb2, 0xff, 0xff], + ), + ); + + expect(stock.toJson()['out_path_list'], 'a1b2'); + }); + + test( + 'a path shorter than its declared hop count is dropped, not guessed', + () { + final stock = toStockContact( + makeContact(pathLength: 4, pathHashWidth: 2, path: [0xa1, 0xb2]), + ); + + expect(stock.outPath, isNull); + }, + ); + + test('a hash width stock cannot express is dropped', () { + final stock = toStockContact( + makeContact(pathLength: 1, pathHashWidth: 4, path: [1, 2, 3, 4]), + ); + + expect(stock.outPath, isNull); + }); + + test('a zero position stays zero rather than becoming absent', () { + // Review flagged (0, 0) as a lost position on import. It is not: the + // frame builder writes the position block whenever lastModified is + // present, so zero lands as zero. Pinned here so the export side of the + // pair cannot start emitting something else. + final stock = toStockContact(makeContact(latitude: 0, longitude: 0)); + + expect(stock.latitude, 0); + expect(stock.longitude, 0); + expect(stock.toJson()['latitude'], '0.0'); + expect(stock.toJson()['longitude'], '0.0'); + }); + + test('flags and type pass through untouched', () { + final stock = toStockContact(makeContact(type: 3, flags: 15)); + + expect(stock.type, 3); + expect(stock.flags, 15); + expect(stock.isFavourite, isTrue); + }); + }); + + group('export result', () { + test('is only complete when nothing was omitted', () { + const complete = StockConfigExportResult( + config: StockConfig(), + included: {StockConfigSection.name}, + omitted: {}, + ); + const partial = StockConfigExportResult( + config: StockConfig(), + included: {}, + omitted: {StockConfigSection.identity: StockConfigOmission.unsupported}, + ); + + expect(complete.isComplete, isTrue); + expect(partial.isComplete, isFalse); + }); + }); +} diff --git a/test/services/stock_config_import_service_test.dart b/test/services/stock_config_import_service_test.dart new file mode 100644 index 00000000..a8bcfcc1 --- /dev/null +++ b/test/services/stock_config_import_service_test.dart @@ -0,0 +1,164 @@ +// #575 (epic #568): import merge semantics. +// +// Stock's own import screen states the rules: contacts are upserted, existing +// channels never change. The channel planner is where that rule lives, so it is +// tested directly. Applying to a device is the T1 hardware gate's job. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/stock_config.dart'; +import 'package:meshcore_open/services/stock_config_import_service.dart'; + +Uint8List psk(int fill) => Uint8List.fromList(List.filled(16, fill)); + +Channel live(int index, String name, int fill) => + Channel(index: index, name: name, psk: psk(fill)); + +StockChannel incoming(String name, int fill) => + StockChannel(name: name, secret: psk(fill)); + +void main() { + group('channel import planning', () { + test( + 'a channel the device does not have goes into the first free slot', + () { + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: [incoming('Weather', 0x22)], + maxChannels: 40, + ); + + expect(plan.assignments, hasLength(1)); + expect(plan.assignments.single.slot, 1); + expect(plan.skipped, isEmpty); + }, + ); + + test('a matching psk is left alone, matching stock', () { + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: [incoming('Renamed', 0x11)], + maxChannels: 40, + ); + + expect(plan.assignments, isEmpty); + expect(plan.skipped.single.reason, StockConfigImportIssue.alreadyPresent); + }); + + test('a rotated psk under an existing name does NOT overwrite', () { + // This is stock's rule and it is surprising: importing a file with a new + // key for a channel the user already has is a no-op. We match it, but the + // skip is reported rather than silent. + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: [incoming('Public', 0x99)], + maxChannels: 40, + ); + + expect(plan.assignments, isEmpty); + expect(plan.skipped.single.name, 'Public'); + expect(plan.skipped.single.reason, StockConfigImportIssue.alreadyPresent); + }); + + test('empty slots are reused, and gaps are filled lowest first', () { + // Slot 1 is empty while 0 and 2 are taken, so the newcomer lands in 1. + final plan = planChannelImport( + existing: [ + live(0, 'Public', 0x11), + Channel(index: 1, name: '', psk: Uint8List(16)), + live(2, 'Weather', 0x22), + ], + incoming: [incoming('Emergency', 0x33)], + maxChannels: 40, + ); + + expect(plan.assignments.single.slot, 1); + }); + + test('several new channels take consecutive free slots in file order', () { + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: [ + incoming('First', 0x22), + incoming('Second', 0x33), + incoming('Third', 0x44), + ], + maxChannels: 40, + ); + + expect(plan.assignments.map((a) => a.slot), [1, 2, 3]); + expect(plan.assignments.map((a) => a.channel.name), [ + 'First', + 'Second', + 'Third', + ]); + }); + + test('a full device reports every leftover instead of dropping it', () { + final plan = planChannelImport( + existing: [live(0, 'A', 0x11), live(1, 'B', 0x22)], + incoming: [incoming('C', 0x33), incoming('D', 0x44)], + maxChannels: 2, + ); + + expect(plan.assignments, isEmpty); + expect(plan.skipped.map((s) => s.name), ['C', 'D']); + expect( + plan.skipped.map((s) => s.reason), + everyElement(StockConfigImportIssue.noFreeSlot), + ); + }); + + test('a duplicate inside the file itself is only written once', () { + final plan = planChannelImport( + existing: const [], + incoming: [incoming('Dupe', 0x55), incoming('Dupe', 0x55)], + maxChannels: 40, + ); + + expect(plan.assignments, hasLength(1)); + expect(plan.skipped.single.reason, StockConfigImportIssue.alreadyPresent); + }); + + test('nothing incoming means nothing planned and nothing skipped', () { + final plan = planChannelImport( + existing: [live(0, 'Public', 0x11)], + incoming: const [], + maxChannels: 40, + ); + + expect(plan.assignments, isEmpty); + expect(plan.skipped, isEmpty); + }); + }); + + group('import result', () { + test('skipped channels alone make a result incomplete', () { + const result = StockConfigImportResult( + applied: {}, + failed: {}, + skippedChannels: [ + SkippedChannel('Public', StockConfigImportIssue.alreadyPresent), + ], + contactsWritten: 0, + channelsAdded: 0, + ); + + expect(result.isComplete, isFalse); + }); + + test('a clean run is complete', () { + const result = StockConfigImportResult( + applied: {}, + failed: {}, + skippedChannels: [], + contactsWritten: 3, + channelsAdded: 1, + ); + + expect(result.isComplete, isTrue); + }); + }); +} diff --git a/test/services/usb_serial_frame_codec_test.dart b/test/services/usb_serial_frame_codec_test.dart index 5d91d05b..7686818c 100644 --- a/test/services/usb_serial_frame_codec_test.dart +++ b/test/services/usb_serial_frame_codec_test.dart @@ -164,4 +164,81 @@ void main() { expect(packets.single.isRxFrame, isTrue); expect(packets.single.payload, orderedEquals([0x88])); }); + + group('skip report (#711): discarded bytes are never silent', () { + test('clean input reports nothing', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest( + Uint8List.fromList([usbSerialRxFrameStart, 0x01, 0x00, 0x55]), + ); + + expect(decoder.takeSkipReport(), isNull); + }); + + test('counts and samples noise before a frame', () { + final decoder = UsbSerialFrameDecoder(); + final packets = decoder.ingest( + Uint8List.fromList([ + 0xAA, + 0xBB, + usbSerialRxFrameStart, + 0x01, + 0x00, + 0x55, + ]), + ); + + expect(packets.single.payload, orderedEquals([0x55])); + final report = decoder.takeSkipReport()!; + expect(report.count, 2); + expect(report.sample, orderedEquals([0xAA, 0xBB])); + expect(report.describe(), contains('discarded 2 byte(s)')); + expect(report.describe(), contains('aa bb')); + }); + + test('counts an oversized header and still decodes the next frame', () { + final decoder = UsbSerialFrameDecoder(); + final oversized = usbSerialMaxPayloadLength + 1; + final packets = decoder.ingest( + Uint8List.fromList([ + usbSerialRxFrameStart, + oversized & 0xff, + (oversized >> 8) & 0xff, + usbSerialRxFrameStart, + 0x01, + 0x00, + 0x44, + ]), + ); + + expect(packets.single.payload, orderedEquals([0x44])); + expect(decoder.takeSkipReport()!.count, 3); + }); + + test('a report is taken once, then cleared', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList([0x01, 0x02])); + + expect(decoder.takeSkipReport()!.count, 2); + expect(decoder.takeSkipReport(), isNull); + }); + + test('the sample is capped, the count is not', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList(List.filled(40, 0x00))); + + final report = decoder.takeSkipReport()!; + expect(report.count, 40); + expect(report.sample, hasLength(16)); + expect(report.describe(), endsWith('...)')); + }); + + test('reset clears a pending report', () { + final decoder = UsbSerialFrameDecoder(); + decoder.ingest(Uint8List.fromList([0x01])); + decoder.reset(); + + expect(decoder.takeSkipReport(), isNull); + }); + }); } diff --git a/test/storage/contact_store_test.dart b/test/storage/contact_store_test.dart new file mode 100644 index 00000000..e892177e --- /dev/null +++ b/test/storage/contact_store_test.dart @@ -0,0 +1,97 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #673: contacts the app could not read must never be replaced by a save. +/// A decode failure used to return an empty list silently, and the next save +/// wrote whatever was in memory over the stored contacts. +Contact _contact(int keyByte, String name) => Contact( + publicKey: Uint8List.fromList(List.filled(32, keyByte)), + name: name, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + const radioKey = 'd549bbfbd003e580'; + late OffbandDatabase db; + late BlobStore blobs; + late ContactStore store; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + store = ContactStore()..setPublicKeyHex = radioKey; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test('a readable store round-trips and saves normally', () async { + await store.saveContacts([_contact(0x11, 'Alpha')]); + final loaded = await store.loadContacts(); + + expect(loaded.map((c) => c.name), ['Alpha']); + expect(store.lastLoadFailed, isFalse); + }); + + group('an unreadable store', () { + const corrupt = '[{"publicKey": 12345, "name": "Alpha"'; + + setUp(() => blobs.write(store.keyFor, corrupt)); + + test('loads as empty but reports the failure', () async { + expect(await store.loadContacts(), isEmpty); + expect(store.lastLoadFailed, isTrue); + }); + + test('keeps the raw value aside, untouched', () async { + await store.loadContacts(); + + final aside = (await blobs.keysWithPrefix( + '${store.keyFor}.unreadable-', + )).single; + expect(await blobs.read(aside), corrupt); + }); + + test('refuses a save that would replace it', () async { + await store.loadContacts(); + await store.saveContacts([_contact(0x22, 'Bravo')]); + + expect(await blobs.read(store.keyFor), corrupt); + }); + + test('saving resumes once a load succeeds again', () async { + await store.loadContacts(); + await blobs.write(store.keyFor, '[]'); + await store.loadContacts(); + await store.saveContacts([_contact(0x22, 'Bravo')]); + + expect(store.lastLoadFailed, isFalse); + expect((await store.loadContacts()).map((c) => c.name), ['Bravo']); + }); + + test('does not block saves for a different radio', () async { + await store.loadContacts(); + store.setPublicKeyHex = 'aa2dccf401e5aaaa'; + await store.saveContacts([_contact(0x33, 'Charlie')]); + + expect((await store.loadContacts()).map((c) => c.name), ['Charlie']); + }); + }); +} diff --git a/test/utils/stock_config_file_test.dart b/test/utils/stock_config_file_test.dart new file mode 100644 index 00000000..ad798a01 --- /dev/null +++ b/test/utils/stock_config_file_test.dart @@ -0,0 +1,56 @@ +// #574 (epic #568): the export file name has to match stock's convention and +// survive real device names, which contain emoji and trailing spaces. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/utils/stock_config_file.dart'; + +void main() { + final at = DateTime(2026, 8, 12, 22, 16, 25); + + test('matches stock: name, then meshcore_config, then a stamp', () { + expect( + stockConfigFileName('Strycher-RAK-CAR', at), + 'Strycher-RAK-CAR_meshcore_config_2026-08-12-221625.json', + ); + }); + + test('single-digit months, days and times are zero padded', () { + expect( + stockConfigFileName('Node', DateTime(2026, 1, 2, 3, 4, 5)), + 'Node_meshcore_config_2026-01-02-030405.json', + ); + }); + + test('emoji in a device name are kept, as stock keeps them', () { + expect( + stockConfigFileName('Strycher T1000\u{1F6F0}️', at), + startsWith('Strycher T1000\u{1F6F0}️_meshcore_config_'), + ); + }); + + test('a trailing space is dropped, since Windows rejects it', () { + // Observed in a real export: the device name ended in a space. + expect( + stockConfigFileName('Strycher-Wio-L1 ', at), + 'Strycher-Wio-L1_meshcore_config_2026-08-12-221625.json', + ); + }); + + test('path separators and reserved characters are stripped', () { + expect( + stockConfigFileName(r'a/b\c:d*e?f"gi|j', at), + 'abcdefghij_meshcore_config_2026-08-12-221625.json', + ); + }); + + test('a device with no name still produces a usable file name', () { + expect( + stockConfigFileName(null, at), + 'meshcore_config_2026-08-12-221625.json', + ); + expect( + stockConfigFileName(' ', at), + 'meshcore_config_2026-08-12-221625.json', + ); + }); +} diff --git a/test/widgets/add_contact_by_key_dialog_test.dart b/test/widgets/add_contact_by_key_dialog_test.dart new file mode 100644 index 00000000..e6780ad9 --- /dev/null +++ b/test/widgets/add_contact_by_key_dialog_test.dart @@ -0,0 +1,198 @@ +// Widget tests for manual key entry (#628). +// +// The point of this dialog is that it must produce exactly the same contact +// stub a scanned QR would, so these pin what actually reaches the connector: +// the key, the typed name, the chosen type, and the epoch lastSeen that keeps +// the firmware advert replay guard from muting the contact (#620). + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/widgets/add_contact_by_key_dialog.dart'; + +const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; + +class _CapturingConn extends MeshCoreConnector { + final List added = []; + + @override + Future addContactByKey(Contact stub) async { + added.add(stub); + return true; + } +} + +Future _open(WidgetTester tester, _CapturingConn conn) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: conn, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () => showAddContactByKeyDialog(context), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('a valid key produces an unverified stub with the typed name', ( + tester, + ) async { + final conn = _CapturingConn(); + await _open(tester, conn); + + await tester.enterText(find.byType(TextField).first, _key); + await tester.enterText(find.byType(TextField).last, 'Ka8sbi'); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, hasLength(1)); + final stub = conn.added.single; + expect(stub.publicKeyHex, _key); + expect(stub.name, 'Ka8sbi'); + expect(stub.type, advTypeChat); + // The reason this whole path exists. Anything else here and the contact + // goes permanently deaf to its own adverts. + expect(stub.lastSeen, DateTime.fromMillisecondsSinceEpoch(0)); + expect(stub.pathLength, -1); + }); + + testWidgets('pasting a full contact link fills in every field', ( + tester, + ) async { + final conn = _CapturingConn(); + await _open(tester, conn); + + await tester.enterText( + find.byType(TextField).first, + 'meshcore://contact/add?name=Two+Words&public_key=$_key&type=2', + ); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, hasLength(1)); + final stub = conn.added.single; + expect(stub.publicKeyHex, _key); + // Name and type came from the pasted link, not retyped by hand. + expect(stub.name, 'Two Words'); + expect(stub.type, advTypeRepeater); + }); + + testWidgets('whitespace in a pasted key is tolerated', (tester) async { + final conn = _CapturingConn(); + await _open(tester, conn); + + // A key copied out of a chat log often arrives wrapped. + await tester.enterText( + find.byType(TextField).first, + '${_key.substring(0, 32)}\n${_key.substring(32)}', + ); + await tester.enterText(find.byType(TextField).last, 'Bob'); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, hasLength(1)); + expect(conn.added.single.publicKeyHex, _key); + }); + + testWidgets('an invalid key shows an error and sends nothing', ( + tester, + ) async { + final conn = _CapturingConn(); + await _open(tester, conn); + + await tester.enterText(find.byType(TextField).first, 'not-a-key'); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, isEmpty); + // Dialog stays open so the user can correct it. + expect(find.byType(AlertDialog), findsOneWidget); + expect( + find.textContaining('64 hex characters', findRichText: true), + findsWidgets, + ); + }); + + testWidgets('a scanned link opens the dialog already populated', ( + tester, + ) async { + // The contacts-menu scan route hands its result straight to the dialog, so + // the user should not have to paste anything. (#629) + final conn = _CapturingConn(); + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: conn, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () => showAddContactByKeyDialog( + context, + initialKeyText: + 'meshcore://contact/add?name=Scanned+Node' + '&public_key=$_key&type=3', + ), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + // Straight to Add, with nothing typed by hand. + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, hasLength(1)); + final stub = conn.added.single; + expect(stub.publicKeyHex, _key); + expect(stub.name, 'Scanned Node'); + expect(stub.type, advTypeRoom); + expect(stub.lastSeen, DateTime.fromMillisecondsSinceEpoch(0)); + }); + + testWidgets('a missing name falls back rather than blocking the add', ( + tester, + ) async { + final conn = _CapturingConn(); + await _open(tester, conn); + + await tester.enterText(find.byType(TextField).first, _key); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Add')); + await tester.pumpAndSettle(); + + expect(conn.added, hasLength(1)); + expect(conn.added.single.name, 'Unknown'); + }); +} diff --git a/test/widgets/composer_budget_notice_test.dart b/test/widgets/composer_budget_notice_test.dart new file mode 100644 index 00000000..e9ec33cd --- /dev/null +++ b/test/widgets/composer_budget_notice_test.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/widgets/composer_budget_notice.dart'; + +/// #684: a composer whose byte budget has collapsed must say so, instead of +/// presenting a field that silently rejects every keystroke (#592 was reported +/// three times as "the keyboard doesn't respond"). Equally it must stay +/// invisible the rest of the time, or it becomes noise that teaches people to +/// ignore it. +Widget _wrap(Widget child) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: child), +); + +void main() { + group('stays invisible when it should (#684)', () { + testWidgets('healthy budget renders nothing', (tester) async { + await tester.pumpWidget( + _wrap( + const ComposerBudgetNotice( + maxBytes: 148, // a channel composer on a 172-byte frame budget + transport: MeshCoreTransportType.bluetooth, + isConnected: true, + ), + ), + ); + + expect(find.byIcon(Icons.error_outline), findsNothing); + expect(find.byIcon(Icons.info_outline), findsNothing); + expect(find.byType(Text), findsNothing); + }); + + testWidgets('collapsed budget while DISCONNECTED renders nothing', ( + tester, + ) async { + // The regression the pre-PR review caught. While disconnected the + // transport still reads bluetooth and there is no device, so the budget + // collapses to the same floor an unreported MTU produces. Without the + // gate this banner appeared on every disconnect and blamed the link for + // a small packet size when there was no link at all. + await tester.pumpWidget( + _wrap( + const ComposerBudgetNotice( + maxBytes: 0, + transport: MeshCoreTransportType.bluetooth, + isConnected: false, + ), + ), + ); + + expect(find.byIcon(Icons.error_outline), findsNothing); + expect(find.byType(Text), findsNothing); + }); + }); + + group('explains itself when the budget has collapsed (#684)', () { + testWidgets('zero budget reads as a failure, not a hint', (tester) async { + await tester.pumpWidget( + _wrap( + const ComposerBudgetNotice( + maxBytes: 0, + transport: MeshCoreTransportType.bluetooth, + isConnected: true, + ), + ), + ); + + expect(find.byIcon(Icons.error_outline), findsOneWidget); + expect(find.byIcon(Icons.info_outline), findsNothing); + // Names the cause in plain words rather than exposing byte arithmetic. + expect(find.textContaining('Bluetooth'), findsOneWidget); + }); + + testWidgets('a small but nonzero budget is stated, not alarmed about', ( + tester, + ) async { + // 4 bytes is the measured DM budget at the unknown-MTU floor. The link + // works, it is just tiny, so this must not render as an error. + await tester.pumpWidget( + _wrap( + const ComposerBudgetNotice( + maxBytes: 4, + transport: MeshCoreTransportType.bluetooth, + isConnected: true, + ), + ), + ); + + expect(find.byIcon(Icons.info_outline), findsOneWidget); + expect(find.byIcon(Icons.error_outline), findsNothing); + // The actual number is surfaced so the user knows what they have. + expect(find.textContaining('4'), findsOneWidget); + }); + + testWidgets('a non-bluetooth transport does not blame Bluetooth', ( + tester, + ) async { + await tester.pumpWidget( + _wrap( + const ComposerBudgetNotice( + maxBytes: 0, + transport: MeshCoreTransportType.usb, + isConnected: true, + ), + ), + ); + + expect(find.byIcon(Icons.error_outline), findsOneWidget); + expect(find.textContaining('Bluetooth'), findsNothing); + }); + }); +} diff --git a/test/widgets/contact_card_chip_test.dart b/test/widgets/contact_card_chip_test.dart new file mode 100644 index 00000000..4693fbef --- /dev/null +++ b/test/widgets/contact_card_chip_test.dart @@ -0,0 +1,148 @@ +// Receiving a contact card (#610). +// +// Before this, an incoming rendered as raw text while the stock +// app showed a native Add Contact button for the very same payload. Sharing +// worked outbound only. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/widgets/translated_message_content.dart'; + +const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; +const _card = '<$_key:1:Ka8sbi>'; + +class _Conn extends MeshCoreConnector { + _Conn({this.known = const {}}); + + /// Public key hexes already in contacts. Mirrors the connector's own + /// `_knownContactKeys` set, which is what the chip now consults. + final Set known; + + @override + bool isKnownContact(String publicKeyHex) => known.contains(publicKeyHex); +} + +Future _pump(WidgetTester tester, String text, _Conn conn) => + tester.pumpWidget( + ChangeNotifierProvider.value( + value: conn, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: TranslatedMessageContent( + displayText: text, + style: const TextStyle(fontSize: 14), + ), + ), + ), + ), + ); + +void main() { + testWidgets('a received card renders as an actionable chip, not raw text', ( + tester, + ) async { + await _pump(tester, 'here is mine $_card', _Conn()); + + // The raw payload must not be shown. + expect(find.textContaining(_key), findsNothing); + // An actionable affordance is offered instead. + expect(find.byIcon(Icons.person_add_alt_1), findsOneWidget); + expect(find.byType(InkWell), findsOneWidget); + // The caption survives alongside it. + expect(find.textContaining('here is mine'), findsOneWidget); + }); + + testWidgets('a card for a known contact does not offer to re-add', ( + tester, + ) async { + // Mirrors stock, which warned rather than silently re-adding. + await _pump(tester, _card, _Conn(known: {_key})); + + expect(find.byIcon(Icons.how_to_reg), findsOneWidget); + expect(find.byIcon(Icons.person_add_alt_1), findsNothing); + // Not tappable, so it cannot be double-added. + expect(find.byType(InkWell), findsNothing); + }); + + testWidgets('a malformed card falls back to plain text rather than lying', ( + tester, + ) async { + // Right shape, impossible type. Rendering an Add chip here would promise + // something the parser will refuse. + const bad = '<$_key:9:Bob>'; + await _pump(tester, bad, _Conn()); + + expect(find.byIcon(Icons.person_add_alt_1), findsNothing); + expect(find.textContaining(bad), findsOneWidget); + }); + + testWidgets('a mention and a card in one message both render', ( + tester, + ) async { + // The two patterns are collected and sorted by position, so this is the + // case that would break a naive single-regex implementation. + await _pump(tester, '@[Bob] add this $_card', _Conn()); + + expect(find.textContaining('@Bob'), findsOneWidget); + expect(find.byIcon(Icons.person_add_alt_1), findsOneWidget); + expect(find.textContaining(_key), findsNothing); + }); + + testWidgets('a plain message is untouched and keeps link support', ( + tester, + ) async { + await _pump(tester, 'just a normal message', _Conn()); + + expect(find.byIcon(Icons.person_add_alt_1), findsNothing); + expect(find.textContaining('just a normal message'), findsOneWidget); + }); + + testWidgets('two cards in one message render as two separate chips', ( + tester, + ) async { + // Regression for the Gemini review: parsing from the first `<` to the last + // `>` would have read this as one span running from the first key to the + // second name, and produced garbage. + const other = + 'ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100'; + await _pump(tester, '$_card and <$other:2:Bob>', _Conn()); + + expect(find.byIcon(Icons.person_add_alt_1), findsNWidgets(2)); + expect(find.textContaining('Ka8sbi'), findsOneWidget); + expect(find.textContaining('Bob'), findsOneWidget); + expect(find.textContaining(_key), findsNothing); + }); + + testWidgets('a nested bracket mess yields one card, and it is the outer key', ( + tester, + ) async { + // Adversarial input from a public channel. `[^>]*` cannot cross a `>`, so + // the match ends at the inner closing bracket and the nested text becomes + // part of the OUTER card's name. Exactly one add is offered, for the outer + // key, and the tap opens the dialog where the key is visible before + // anything is written to the radio. No second key is silently smuggled in. + const other = + 'ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100'; + await _pump(tester, '<$_key:1:Name <$other:2:Inner>>', _Conn()); + + expect(find.byIcon(Icons.person_add_alt_1), findsOneWidget); + // The parser took the outer card, so the nested text is shown as the name + // rather than being treated as a second identity. + expect(find.textContaining('Name <'), findsOneWidget); + }); + + testWidgets('names with spaces and emoji survive into the chip label', ( + tester, + ) async { + await _pump(tester, '<$_key:2:Roger KY4RS 🧙>', _Conn()); + + expect(find.textContaining('Roger KY4RS 🧙'), findsOneWidget); + expect(find.byIcon(Icons.person_add_alt_1), findsOneWidget); + }); +} diff --git a/test/widgets/contact_sync_shortfall_banner_test.dart b/test/widgets/contact_sync_shortfall_banner_test.dart new file mode 100644 index 00000000..bade02a7 --- /dev/null +++ b/test/widgets/contact_sync_shortfall_banner_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/widgets/contact_sync_shortfall_banner.dart'; + +/// #674: a short contact sync must be loud and stay visible, and the choice +/// after a failed retry must default to keeping the saved contacts. +void main() { + late List calls; + + Widget build({ + ContactSyncShortfall? shortfall, + bool decisionPending = false, + int undelivered = 244, + }) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: ContactSyncShortfallBanner( + shortfall: shortfall, + decisionPending: decisionPending, + undeliveredCount: undelivered, + onDismiss: () => calls.add('dismiss'), + onKeep: () => calls.add('keep'), + onUseRadio: () => calls.add('useRadio'), + child: const Text('APP'), + ), + ), + ); + + const short = ContactSyncShortfall( + declared: 350, + received: 106, + keptLocally: 244, + ); + + setUp(() => calls = []); + + testWidgets('no shortfall: only the app renders', (tester) async { + await tester.pumpWidget(build()); + + expect(find.text('APP'), findsOneWidget); + expect(find.text('Contact sync incomplete'), findsNothing); + }); + + testWidgets('shortfall: banner with the counts, above the app', ( + tester, + ) async { + await tester.pumpWidget(build(shortfall: short)); + + expect(find.text('Contact sync incomplete'), findsOneWidget); + expect( + find.textContaining( + 'reported 350 contacts; after checking again the app has 106', + ), + findsOneWidget, + ); + expect(find.text('APP'), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + }); + + // #764: contacts the radio answered "not found" for are named, and only + // when there are any. + group('confirmed gone', () { + const withGone = ContactSyncShortfall( + declared: 350, + received: 340, + keptLocally: 10, + confirmedGone: 4, + ); + + testWidgets('banner names them when there are some', (tester) async { + await tester.pumpWidget(build(shortfall: withGone)); + + expect( + find.textContaining('4 saved contacts are no longer on the radio.'), + findsOneWidget, + ); + }); + + testWidgets('one reads in the singular', (tester) async { + await tester.pumpWidget( + build( + shortfall: const ContactSyncShortfall( + declared: 350, + received: 349, + keptLocally: 1, + confirmedGone: 1, + ), + ), + ); + + expect( + find.textContaining('1 saved contact is no longer on the radio.'), + findsOneWidget, + ); + }); + + testWidgets('banner says nothing about it when there are none', ( + tester, + ) async { + await tester.pumpWidget(build(shortfall: short)); + + expect(find.textContaining('no longer on the radio'), findsNothing); + }); + + testWidgets('the decision dialog names them too', (tester) async { + await tester.pumpWidget( + build(shortfall: withGone, decisionPending: true, undelivered: 10), + ); + + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.textContaining( + '4 saved contacts are no longer on the radio.', + ), + ), + findsOneWidget, + ); + }); + }); + + testWidgets('no declared total uses its own wording', (tester) async { + await tester.pumpWidget( + build( + shortfall: const ContactSyncShortfall( + declared: null, + received: 50, + keptLocally: 3, + ), + ), + ); + + expect(find.textContaining('did not report how many'), findsOneWidget); + }); + + testWidgets('the close button dismisses', (tester) async { + await tester.pumpWidget(build(shortfall: short)); + await tester.tap(find.byIcon(Icons.close)); + + expect(calls, ['dismiss']); + }); + + // #713: the app mounts the banner in MaterialApp.builder, above the + // Navigator, where there is no Overlay. The tests above mount it under + // `home:`, which has one, so they could not see this. + group('mounted where the app mounts it (MaterialApp.builder)', () { + Widget inBuilder({bool decisionPending = false}) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => ContactSyncShortfallBanner( + shortfall: short, + decisionPending: decisionPending, + undeliveredCount: 244, + onDismiss: () => calls.add('dismiss'), + onKeep: () => calls.add('keep'), + onUseRadio: () => calls.add('useRadio'), + child: child ?? const SizedBox.shrink(), + ), + home: const Scaffold(body: Text('APP')), + ); + + testWidgets('hovering the close button does not break the app', ( + tester, + ) async { + await tester.pumpWidget(inBuilder()); + final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(location: Offset.zero); + addTearDown(gesture.removePointer); + await gesture.moveTo(tester.getCenter(find.byIcon(Icons.close))); + await tester.pumpAndSettle(const Duration(seconds: 2)); + + expect(tester.takeException(), isNull); + expect(find.text('Contact sync incomplete'), findsOneWidget); + expect(find.text('APP'), findsOneWidget); + }); + + testWidgets('the decision dialog works there too', (tester) async { + await tester.pumpWidget(inBuilder(decisionPending: true)); + await tester.pump(); + await tester.tap(find.text('Keep my contacts')); + + expect(tester.takeException(), isNull); + expect(calls, ['keep']); + }); + }); + + group('decision pending', () { + testWidgets('asks, says how many would be removed, defaults to Keep', ( + tester, + ) async { + await tester.pumpWidget(build(shortfall: short, decisionPending: true)); + await tester.pump(); + + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.textContaining('removes 244 contacts'), findsOneWidget); + final keep = tester.widget(find.byType(FilledButton)); + expect(keep.autofocus, isTrue); + expect(find.text('Keep my contacts'), findsOneWidget); + }); + + testWidgets('Keep my contacts', (tester) async { + await tester.pumpWidget(build(shortfall: short, decisionPending: true)); + await tester.tap(find.text('Keep my contacts')); + + expect(calls, ['keep']); + }); + + testWidgets('Use the radio\'s list', (tester) async { + await tester.pumpWidget(build(shortfall: short, decisionPending: true)); + await tester.tap(find.text('Use the radio\'s list')); + + expect(calls, ['useRadio']); + }); + + testWidgets('Enter on the dialog picks the default, Keep', (tester) async { + await tester.pumpWidget(build(shortfall: short, decisionPending: true)); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + + expect(calls, ['keep']); + }); + }); +} diff --git a/test/widgets/contact_verification_badge_test.dart b/test/widgets/contact_verification_badge_test.dart new file mode 100644 index 00000000..3eea4ace --- /dev/null +++ b/test/widgets/contact_verification_badge_test.dart @@ -0,0 +1,171 @@ +// Verification-state tests (#630). +// +// The three states are not cosmetic. advertVerified means the node itself +// asserted its identity in a signed advert. keyConfirmed means a message went +// through, which only works with the matching private key. keyOnly means +// someone typed a key and nothing has confirmed it on air. + +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/widgets/contact_verification_badge.dart'; + +const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; + +Contact _contact({required DateTime lastSeen}) => Contact( + publicKey: hex2Uint8List(_key), + name: 'Bob', + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: lastSeen, +); + +Contact _keyOnly() => + _contact(lastSeen: DateTime.fromMillisecondsSinceEpoch(0)); +Contact _adverted() => _contact(lastSeen: DateTime(2026, 9, 6, 12)); + +Message _msg(MessageStatus status) => Message( + senderKey: hex2Uint8List(_key), + text: 'hi', + isOutgoing: true, + timestamp: DateTime(2026, 9, 6), + status: status, +); + +class _Conn extends MeshCoreConnector { + _Conn(this.messages); + final List messages; + + @override + List getMessages(Contact contact) => messages; +} + +void main() { + group('Contact.isAdvertVerified (#630)', () { + test('a key-only contact carries the epoch and is not advert-verified', () { + expect(_keyOnly().isAdvertVerified, isFalse); + }); + + test('any real advert timestamp counts as verified', () { + expect(_adverted().isAdvertVerified, isTrue); + }); + + test('the parser output is unverified by construction', () { + // Ties the model getter to what fromShareUri actually produces, so the + // two cannot drift. + final parsed = Contact.fromShareUri( + 'meshcore://contact/add?name=Bob&public_key=$_key&type=1', + )!; + expect(parsed.isAdvertVerified, isFalse); + }); + }); + + group('resolveContactVerification (#630)', () { + test('an adverted contact is advertVerified even with no messages', () { + expect( + resolveContactVerification(_adverted(), _Conn(const [])), + ContactVerification.advertVerified, + ); + }); + + test('an advert wins over message history', () { + // The advert is strictly stronger: it is signed and it stores the raw + // packet that makes the contact re-shareable. + expect( + resolveContactVerification( + _adverted(), + _Conn([_msg(MessageStatus.delivered)]), + ), + ContactVerification.advertVerified, + ); + }); + + test('a key-only contact with no traffic is keyOnly', () { + expect( + resolveContactVerification(_keyOnly(), _Conn(const [])), + ContactVerification.keyOnly, + ); + }); + + test('a delivered message upgrades a key-only contact to keyConfirmed', () { + expect( + resolveContactVerification( + _keyOnly(), + _Conn([_msg(MessageStatus.sent), _msg(MessageStatus.delivered)]), + ), + ContactVerification.keyConfirmed, + ); + }); + + test('unacked traffic does NOT confirm the key', () { + // sent means it left the radio. failed and pending prove nothing at all. + // Only delivered means the far end produced the right ACK, which needs + // the plaintext, which needs the matching private key. + for (final s in [ + MessageStatus.pending, + MessageStatus.sent, + MessageStatus.failed, + ]) { + expect( + resolveContactVerification(_keyOnly(), _Conn([_msg(s)])), + ContactVerification.keyOnly, + reason: '$s must not count as confirmation', + ); + } + }); + }); + + group('ContactVerificationBadge rendering (#630)', () { + Future pump(WidgetTester tester, Contact c, _Conn conn) => + tester.pumpWidget( + ChangeNotifierProvider.value( + value: conn, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: ContactVerificationBadge(contact: c)), + ), + ), + ); + + testWidgets('advert-verified shows the green check', (tester) async { + await pump(tester, _adverted(), _Conn(const [])); + final icon = tester.widget(find.byType(Icon)); + expect(icon.icon, Icons.verified); + expect(icon.color, Colors.green); + }); + + testWidgets('key-confirmed shows a neutral check, not green', ( + tester, + ) async { + await pump(tester, _keyOnly(), _Conn([_msg(MessageStatus.delivered)])); + final icon = tester.widget(find.byType(Icon)); + expect(icon.icon, Icons.check_circle_outline); + expect(icon.color, isNot(Colors.green)); + }); + + testWidgets('key-only shows a muted key and nothing alarming', ( + tester, + ) async { + await pump(tester, _keyOnly(), _Conn(const [])); + final icon = tester.widget(find.byType(Icon)); + expect(icon.icon, Icons.key_outlined); + // Owner steer: no amber, no hazard glyph. Nothing is wrong with this + // contact, it is just less confirmed. + expect(icon.icon, isNot(Icons.warning)); + expect(icon.icon, isNot(Icons.warning_amber)); + expect(icon.icon, isNot(Icons.error_outline)); + expect(icon.color, isNot(Colors.amber)); + expect(icon.color, isNot(Colors.red)); + }); + }); +} diff --git a/test/widgets/my_contact_qr_dialog_test.dart b/test/widgets/my_contact_qr_dialog_test.dart new file mode 100644 index 00000000..7631a807 --- /dev/null +++ b/test/widgets/my_contact_qr_dialog_test.dart @@ -0,0 +1,114 @@ +// Widget tests for sharing this device's own identity as a QR (#629). +// +// The QR is only the meshcore://contact/add link rendered visually. qr_flutter +// keeps its payload private (`final String? _data`), so these assert on the +// link the dialog renders beside the code, which is the same string, and on +// that link parsing back into the right key, name and type. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:qr_flutter/qr_flutter.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/widgets/my_contact_qr_dialog.dart'; + +const _key = 'aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899'; + +class _FakeConn extends MeshCoreConnector { + _FakeConn({required this.keyHex, this.nodeName}); + + final String keyHex; + final String? nodeName; + + @override + String get selfPublicKeyHex => keyHex; + + @override + String? get selfName => nodeName; +} + +Future _open(WidgetTester tester, MeshCoreConnector conn) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: conn, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () => showMyContactQrDialog(context), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('renders a QR plus the link it encodes', (tester) async { + await _open(tester, _FakeConn(keyHex: _key, nodeName: 'Strycher-RK4')); + + final expected = Contact.buildShareUri( + publicKeyHex: _key, + name: 'Strycher-RK4', + type: advTypeChat, + ); + + expect(find.byType(QrImageView), findsOneWidget); + // The link is shown so it can be copied or pasted into a chat, which is + // the path that works when the other person is not in the room. + expect(find.text(expected), findsOneWidget); + }); + + testWidgets('the rendered link parses back to this device', (tester) async { + await _open(tester, _FakeConn(keyHex: _key, nodeName: 'Strycher-RK4')); + + final expected = Contact.buildShareUri( + publicKeyHex: _key, + name: 'Strycher-RK4', + type: advTypeChat, + ); + final parsed = Contact.fromShareUri(expected); + + expect(parsed, isNotNull); + expect(parsed!.publicKeyHex, _key); + expect(parsed.name, 'Strycher-RK4'); + // This device is a companion, not a repeater. + expect(parsed.type, advTypeChat); + }); + + testWidgets('a node with no name still produces an addable link', ( + tester, + ) async { + await _open(tester, _FakeConn(keyHex: _key)); + + final expected = Contact.buildShareUri( + publicKeyHex: _key, + name: '', + type: advTypeChat, + ); + expect(find.text(expected), findsOneWidget); + // The key is the identity, so a nameless link is still usable. + expect(Contact.fromShareUri(expected)?.publicKeyHex, _key); + }); + + testWidgets('with no connection nothing is rendered, since we lack our key', ( + tester, + ) async { + // An empty key would encode a QR that cannot be added, which is worse + // than refusing to show one. + await _open(tester, _FakeConn(keyHex: '')); + + expect(find.byType(QrImageView), findsNothing); + expect(find.byType(AlertDialog), findsNothing); + }); +} diff --git a/test/widgets/radio_preset_picker_test.dart b/test/widgets/radio_preset_picker_test.dart new file mode 100644 index 00000000..a6d3caab --- /dev/null +++ b/test/widgets/radio_preset_picker_test.dart @@ -0,0 +1,164 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/radio_preset.dart'; +import 'package:meshcore_open/models/radio_settings.dart'; +import 'package:meshcore_open/services/radio_preset_service.dart'; +import 'package:meshcore_open/widgets/radio_preset_picker.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +RadioPreset preset(String title, String region, RadioPresetSource source) => + RadioPreset( + id: '${source.name}:$title', + title: title, + region: region, + frequencyMHz: 910.525, + bandwidth: LoRaBandwidth.bw62_5, + spreadingFactor: LoRaSpreadingFactor.sf7, + codingRate: LoRaCodingRate.cr4_5, + source: source, + ); + +/// Menu rows only exist while the menu is open; the closed button shows +/// titles from selectedItemBuilder instead. +Finder menuItems({required bool enabled}) => find.byWidgetPredicate( + (w) => w is DropdownMenuItem && w.enabled == enabled, +); + +void main() { + late RadioPresetService service; + final presets = [ + preset('Australia', 'Australia', RadioPresetSource.meshcore), + preset('USA', 'USA', RadioPresetSource.meshcore), + preset('USA - Philly Mesh', 'USA', RadioPresetSource.offband), + ]; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + service = RadioPresetService( + prefs: await SharedPreferences.getInstance(), + loadAsset: (_) async => throw StateError('no assets in this test'), + fetch: (_) async => throw StateError('offline'), + ); + }); + + Future> pump( + WidgetTester tester, { + String? selectedId, + }) async { + final picked = []; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: ListenableBuilder( + listenable: service, + builder: (context, _) => RadioPresetPicker( + service: service, + presets: presets, + selectedId: selectedId, + onSelected: picked.add, + ), + ), + ), + ), + ), + ); + return picked; + } + + Future openMenu(WidgetTester tester) async { + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + } + + testWidgets('groups presets under region headers with source labels (#729)', ( + tester, + ) async { + await pump(tester); + await openMenu(tester); + + // One non-selectable header per region, one selectable row per preset. + expect(menuItems(enabled: false), findsNWidgets(2)); + expect(menuItems(enabled: true), findsNWidgets(3)); + expect(find.text('MeshCore'), findsNWidgets(2)); + expect(find.text('Offband'), findsOneWidget); + }); + + testWidgets('selecting an entry reports it; a region header does nothing', ( + tester, + ) async { + final picked = await pump(tester); + await openMenu(tester); + + await tester.tap(menuItems(enabled: false).last, warnIfMissed: false); + await tester.pumpAndSettle(); + expect(picked, isEmpty); + + // The menu may have closed on the header tap; reopen it if so. + if (menuItems(enabled: true).evaluate().isEmpty) { + await openMenu(tester); + } + await tester.tap(find.text('USA - Philly Mesh').last); + await tester.pumpAndSettle(); + expect(picked.single.id, 'offband:USA - Philly Mesh'); + }); + + testWidgets('starts on the selected preset', (tester) async { + await pump(tester, selectedId: 'offband:USA - Philly Mesh'); + final field = tester.widget>( + find.byType(DropdownButtonFormField), + ); + expect(field.initialValue, 'offband:USA - Philly Mesh'); + }); + + testWidgets('an unknown selection shows no preset rather than failing', ( + tester, + ) async { + await pump(tester, selectedId: 'offband:gone'); + final field = tester.widget>( + find.byType(DropdownButtonFormField), + ); + expect(field.initialValue, isNull); + }); + + testWidgets('a good refresh shows no error (#748)', (tester) async { + final files = { + for (final f in [kUpstreamPresetFile, kOverlayPresetFile]) + f: File('$kRadioPresetAssetDir$f').readAsStringSync(), + }; + service = RadioPresetService( + prefs: await SharedPreferences.getInstance(), + loadAsset: (_) async => throw StateError('no assets in this test'), + fetch: (url) async => files[url.split('/').last]!, + ); + await pump(tester); + await tester.tap(find.byIcon(Icons.refresh)); + await tester.pumpAndSettle(); + expect(service.refreshError, isNull); + expect(find.textContaining('Presets updated'), findsOneWidget); + expect( + find.text("Couldn't update presets. Showing the saved list."), + findsNothing, + ); + }); + + testWidgets('a failed refresh stays on screen as an error', (tester) async { + await pump(tester); + expect( + find.text('Presets included with this version of the app'), + findsOneWidget, + ); + await tester.tap(find.byIcon(Icons.refresh)); + await tester.pumpAndSettle(); + expect( + find.text("Couldn't update presets. Showing the saved list."), + findsOneWidget, + ); + }); +} diff --git a/tools/contact_recovery_bench.py b/tools/contact_recovery_bench.py new file mode 100644 index 00000000..22342c3d --- /dev/null +++ b/tools/contact_recovery_bench.py @@ -0,0 +1,165 @@ +"""Read-only bench check of a real radio for the forced contact resync (#703). + +Run with the app disconnected from the radio (the serial port is exclusive): + + python tools/contact_recovery_bench.py COM13 + python tools/contact_recovery_bench.py COM13 --expect-key d549bbfbd0 + +Sends only APP_START, CMD_GET_CONTACTS and CMD_GET_CONTACT_BY_KEY; it never +writes to the radio's contact table. It checks the two protocol facts the +recovery relies on, on the real firmware: + +1. A by-key request for a contact the radio holds returns that contact. +2. A by-key request for a key it does not hold returns ERR_CODE_NOT_FOUND (2). + +and reports how full syncs (up to --pulls, paced by --settle) add up against +the declared total. Exit code 0 when both protocol checks pass. +""" +import argparse +import os +import sys +import time + +import serial + +CMD_APP_START = 0x01 +CMD_GET_CONTACTS = 0x04 +CMD_GET_CONTACT_BY_KEY = 30 +RESP_ERR = 0x01 +RESP_CONTACTS_START = 0x02 +RESP_CONTACT = 0x03 +RESP_END_OF_CONTACTS = 0x04 +RESP_SELF_INFO = 0x05 +ERR_NOT_FOUND = 2 + + +def frame(payload: bytes) -> bytes: + return bytes([0x3C, len(payload) & 0xFF, len(payload) >> 8]) + payload + + +class Reader: + def __init__(self, ser): + self.ser = ser + self.buf = bytearray() + self.skipped = 0 + + def frames(self, timeout): + end = time.time() + timeout + while time.time() < end: + chunk = self.ser.read(self.ser.in_waiting or 1) + if chunk: + self.buf += chunk + while len(self.buf) >= 3: + if self.buf[0] != 0x3E: + self.buf.pop(0) + self.skipped += 1 + continue + n = self.buf[1] | (self.buf[2] << 8) + if n > 176: + self.buf.pop(0) + self.skipped += 1 + continue + if len(self.buf) < 3 + n: + break + payload = bytes(self.buf[3:3 + n]) + del self.buf[:3 + n] + yield payload + end = time.time() + timeout + + +def pull(ser, r): + ser.write(frame(bytes([CMD_GET_CONTACTS]))) + declared, keys = None, [] + for p in r.frames(5): + if p[0] == RESP_CONTACTS_START and len(p) >= 5: + declared = int.from_bytes(p[1:5], "little") + elif p[0] == RESP_CONTACT and len(p) >= 33: + keys.append(p[1:33].hex()) + elif p[0] == RESP_END_OF_CONTACTS: + break + return declared, keys + + +def by_key(ser, r, key_hex): + """Returns ('contact', key) / ('err', code) / ('none', None).""" + ser.write(frame(bytes([CMD_GET_CONTACT_BY_KEY]) + bytes.fromhex(key_hex))) + for p in r.frames(5): + if p[0] == RESP_CONTACT and len(p) >= 33: + return "contact", p[1:33].hex() + if p[0] == RESP_ERR: + return "err", p[1] if len(p) > 1 else None + return "none", None + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("port") + ap.add_argument("--expect-key", help="abort unless the radio key starts with this hex") + ap.add_argument("--pulls", type=int, default=3) + ap.add_argument("--settle", type=float, default=10.0, help="seconds between pulls") + args = ap.parse_args() + # Radio names can carry emoji the Windows console code page cannot print. + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + ser = serial.Serial(args.port, 115200, timeout=0.05) + try: + time.sleep(0.5) + ser.reset_input_buffer() + r = Reader(ser) + + ser.write(frame(bytes([CMD_APP_START, 0x06]) + b"\x00" * 6 + b"bench703\x00")) + key = name = None + for p in r.frames(3): + if p[0] == RESP_SELF_INFO and len(p) >= 36: + key = p[4:36].hex() + name = p[58:].split(b"\x00")[0].decode("utf-8", "replace") + break + if key is None: + print(f"ABORT: no SELF_INFO from {args.port}") + return 2 + if args.expect_key and not key.startswith(args.expect_key.lower()): + print(f"ABORT: {args.port} is {key[:10]}, not {args.expect_key}") + return 2 + print(f"{args.port}: {name} key={key[:10]}") + + union, declared = set(), None + for i in range(1, args.pulls + 1): + if i > 1: + time.sleep(args.settle) + declared, keys = pull(ser, r) + union.update(keys) + print( + f"pull {i}: declared={declared} received={len(keys)} " + f"union={len(union)} skipped_bytes={r.skipped}" + ) + if declared is not None and len(union) >= declared: + break + + ok = True + if union: + held = sorted(union)[0] + kind, value = by_key(ser, r, held) + good = kind == "contact" and value == held + ok &= good + print(f"by-key held contact {held[:10]}: {kind} {value!r:.24} -> {'PASS' if good else 'FAIL'}") + else: + print("by-key held contact: SKIP (radio delivered no contacts)") + ok = False + + absent = os.urandom(32).hex() + while absent in union: + absent = os.urandom(32).hex() + kind, value = by_key(ser, r, absent) + good = kind == "err" and value == ERR_NOT_FOUND + ok &= good + print(f"by-key absent key: {kind} {value!r} -> {'PASS' if good else 'FAIL'}") + + complete = declared is not None and len(union) >= declared + print(f"union {len(union)} of {declared}: {'complete' if complete else 'short'}") + return 0 if ok else 1 + finally: + ser.close() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/untranslated.json b/untranslated.json index 7784f580..33eda239 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,5 +1,10 @@ { "bg": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -12,6 +17,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -19,6 +41,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -26,15 +55,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -48,6 +114,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -63,10 +158,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "de": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -79,6 +252,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -86,6 +276,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -93,15 +290,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -115,6 +349,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -130,10 +393,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "es": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -146,6 +487,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -153,6 +511,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -160,15 +525,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -182,6 +584,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -197,10 +628,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "fr": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -213,6 +722,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -220,6 +746,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -227,15 +760,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -249,6 +819,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -264,10 +863,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "hu": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -280,6 +957,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -287,6 +981,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -294,15 +995,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -316,6 +1054,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -331,10 +1098,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "it": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -347,6 +1192,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -354,6 +1216,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -361,15 +1230,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -383,6 +1289,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -398,10 +1333,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "ja": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -414,6 +1427,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -421,6 +1451,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -428,15 +1465,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -450,6 +1524,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -465,10 +1568,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "ko": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -481,6 +1662,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -488,6 +1686,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -495,15 +1700,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -517,6 +1759,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -532,10 +1803,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "nl": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -548,6 +1897,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -555,6 +1921,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -562,15 +1935,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -584,6 +1994,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -599,10 +2038,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "pl": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -615,6 +2132,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -622,6 +2156,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -629,15 +2170,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -651,6 +2229,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -666,10 +2273,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "pt": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -682,6 +2367,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -689,6 +2391,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -696,15 +2405,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -718,6 +2464,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -733,10 +2508,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "ru": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -749,6 +2602,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -756,6 +2626,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -763,15 +2640,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -785,6 +2699,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -800,10 +2743,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "sk": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -816,6 +2837,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -823,6 +2861,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -830,15 +2875,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -852,6 +2934,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -867,10 +2978,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "sl": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -883,6 +3072,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -890,6 +3096,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -897,15 +3110,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -919,6 +3169,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -934,10 +3213,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "sv": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -950,6 +3307,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -957,6 +3331,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -964,15 +3345,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -986,6 +3404,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -1001,10 +3448,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "uk": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -1017,6 +3542,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -1024,6 +3566,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -1031,15 +3580,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -1053,6 +3639,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -1068,10 +3683,88 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ], "zh": [ + "scanner_connectFailedTransient", + "scanner_connectFailedTimeout", + "scanner_connectFailedGeneric", + "scanner_bleReleaseWarning", + "scanner_bleReleaseWarningMessage", "settings_messageSettings", "settings_messageSettingsSubtitle", "settings_gpsStatusTitle", @@ -1084,6 +3777,23 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_experimental", + "settings_experimentalSubtitle", + "settings_experimentalDescription", + "settings_coreScopeObserverCount", + "settings_coreScopeObserverCountSubtitle", + "settings_coreScopeObserverCountUnsupported", + "settings_experimentalDisable", + "settings_experimentalDisableSubtitle", + "settings_experimentalUnlocked", + "settings_experimentalAlreadyUnlocked", + "settings_experimentalCountdown", + "settings_aboutLicenses", + "settings_aboutWebsite", + "settings_aboutPlayStore", + "settings_aboutDonate", + "settings_aboutLinkFailed", + "settings_aboutPresetsAttribution", "settings_infoFirmware", "settings_infoModel", "settings_infoOffbandCaps", @@ -1091,6 +3801,13 @@ "settings_infoDataScope", "settings_infoDataScopeSubtitle", "settings_publicKeyCopied", + "settings_presetSourceMeshCore", + "settings_presetSourceOffband", + "settings_presetsRefresh", + "settings_presetsUpdating", + "settings_presetsUpdateFailed", + "settings_presetsUpdatedAt", + "settings_presetsBundled", "settings_femLna", "settings_femLnaSubtitle", "appSettings_clock", @@ -1098,15 +3815,52 @@ "appSettings_clock12h", "appSettings_clock24h", "contacts_searchSensors", + "contacts_manageSensor", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "composerBudgetBlockedTitle", + "composerBudgetLimitedTitle", + "composerBudgetBluetoothCause", + "composerBudgetGenericCause", + "chat_sendingAgain", + "message_sendAgain", "chat_replyWithRoute", + "debugLog_shareLog", + "debugLog_saveLog", + "debugLog_downloadLog", + "debugLog_shareSubject", + "debugLog_logSaved", + "debugLog_logUnavailable", "channel_heardTooltip", + "channel_coreScopeTooltip", + "channel_coreScopeRefresh", + "channel_coreScopeRefreshFailed", + "channel_coreScopeNotFound", + "channel_coreScopeCounts", + "channel_senderNameUnknown", + "channel_senderNameUnknownHint", + "channel_senderAlreadyContact", + "channel_senderMultipleMatches", + "channel_senderAddNotConnected", + "channel_senderAddFailed", + "channel_senderCandidate", "map_alwaysShowNames", "path_suggestedRoute", "path_searchRepeaters", + "repeater_tempRadio", + "repeater_tempRadioSubtitle", + "repeater_tempRadioMinutes", + "repeater_tempRadioPathHashNote", + "repeater_tempRadioMinutesInvalid", + "repeater_cliCommandTimeout", + "channelPath_routeDirect", + "channelPath_routeFlood", + "channelPath_snrLabel", + "channelPath_snrValue", + "channelPath_rssiLabel", + "channelPath_rssiValue", "channels_shareQr", "channels_shareQrTitle", "channels_shareQrInstructions", @@ -1120,6 +3874,35 @@ "channels_qrExists", "listFilter_sensors", "contacts_repeaterPathTraceVia", + "contacts_addByKey", + "contacts_addByKeyDescription", + "contacts_publicKeyLabel", + "contacts_publicKeyHelper", + "contacts_publicKeyInvalid", + "contacts_nameLabel", + "contacts_typeLabel", + "contacts_addByKeyUnverifiedNote", + "contacts_addByKeyAdded", + "contacts_addByKeyFailed", + "contacts_myContactQr", + "contacts_myContactQrInstructions", + "contacts_contactLinkCopied", + "contacts_qrNeedsConnection", + "contacts_scanContactQr", + "contacts_scanContactQrInstructions", + "contacts_invalidContactQr", + "contacts_verifiedByAdvert", + "contacts_verifiedByMessage", + "contacts_verifiedKeyOnly", + "contacts_lastSeenNever", + "contacts_cardAddContact", + "contacts_cardAlreadyAdded", + "contacts_cardAlreadyAddedTooltip", + "chat_attachTooltip", + "chat_attachGif", + "chat_attachMyContact", + "chat_attachMyContactSubtitle", + "chat_contactCardNeedsConnection", "snrIndicator_noNeighbors", "block_block", "block_unblock", @@ -1135,6 +3918,79 @@ "block_namesHint", "block_offloadActive", "block_offloadStoreFull", - "block_composerNotice" + "block_composerNotice", + "storageUnavailableTitle", + "storageUnavailableBody", + "batteryOptimizationTitle", + "batteryOptimizationBody", + "batteryOptimizationOpenSettings", + "batteryOptimizationDismiss", + "batteryOptimizationOpenFailed", + "stockConfig_selectAll", + "stockConfig_deselectAll", + "stockConfig_sectionName", + "stockConfig_sectionIdentity", + "stockConfig_sectionRadio", + "stockConfig_sectionPosition", + "stockConfig_sectionOther", + "stockConfig_sectionAutoAdd", + "stockConfig_sectionChannels", + "stockConfig_sectionContacts", + "stockConfig_identityWarning", + "stockConfig_publicKeyLabel", + "stockConfig_privateKeyHidden", + "exportConfig_title", + "exportConfig_instruction", + "exportConfig_allChannels", + "exportConfig_allContacts", + "exportConfig_nothingSelected", + "exportConfig_lossyNotice", + "exportConfig_omittedTitle", + "exportConfig_omittedUnsupported", + "exportConfig_omittedNoReply", + "exportConfig_omittedRejected", + "exportConfig_omittedUnavailable", + "exportConfig_exportAnyway", + "exportConfig_cancel", + "exportConfig_shareSubject", + "exportConfig_failed", + "exportConfig_notConnected", + "importConfig_title", + "importConfig_instruction", + "importConfig_chooseFile", + "importConfig_identityWarning", + "importConfig_channelsNote", + "importConfig_contactsNote", + "importConfig_nothingSelected", + "importConfig_notConnected", + "importConfig_parseFailed", + "importConfig_confirmIdentityTitle", + "importConfig_confirmIdentityBody", + "importConfig_confirmIdentityAccept", + "importConfig_cancel", + "importConfig_resultTitle", + "importConfig_resultCounts", + "importConfig_resultSkippedHeading", + "importConfig_resultFailedHeading", + "importConfig_reasonAlreadyPresent", + "importConfig_reasonNoFreeSlot", + "importConfig_reasonAbsentFromFile", + "importConfig_reasonNoReply", + "importConfig_reasonUnsupported", + "importConfig_reasonRejected", + "importConfig_reasonNotWritable", + "importConfig_entryLine", + "importConfig_close", + "settings_exportConfig", + "settings_importConfig", + "settings_configBackupSubtitle", + "contactSyncShortfallTitle", + "contactSyncShortfallBody", + "contactSyncShortfallBodyNoTotal", + "contactSyncDecisionTitle", + "contactSyncDecisionBody", + "contactSyncKeep", + "contactSyncUseRadio", + "contactSyncConfirmedGone" ] } diff --git a/web/favicon.ico b/web/favicon.ico new file mode 100644 index 00000000..d20a93ee Binary files /dev/null and b/web/favicon.ico differ diff --git a/web/favicon.png b/web/favicon.png index 8aaa46ac..0a4db8b5 100644 Binary files a/web/favicon.png and b/web/favicon.png differ diff --git a/web/favicon.svg b/web/favicon.svg new file mode 100644 index 00000000..e8434743 --- /dev/null +++ b/web/favicon.svg @@ -0,0 +1 @@ + diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png index b749bfef..ec91b757 100644 Binary files a/web/icons/Icon-192.png and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png index 88cfd48d..4910c946 100644 Binary files a/web/icons/Icon-512.png and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png index eb9b4d76..fa276017 100644 Binary files a/web/icons/Icon-maskable-192.png and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png index d69c5669..8c977ca1 100644 Binary files a/web/icons/Icon-maskable-512.png and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html index 3087ec27..e4eca5c0 100644 --- a/web/index.html +++ b/web/index.html @@ -18,18 +18,37 @@ - + + - + + + - meshcore_open + + + + + + + + + + + + + + + + + Offband Meshcore diff --git a/web/manifest.json b/web/manifest.json index 9b0c25f2..dd66563d 100644 --- a/web/manifest.json +++ b/web/manifest.json @@ -1,11 +1,11 @@ { - "name": "meshcore_open", - "short_name": "meshcore_open", + "name": "Offband Meshcore", + "short_name": "Offband", "start_url": ".", "display": "standalone", - "background_color": "#0175C2", - "theme_color": "#0175C2", - "description": "A new Flutter project.", + "background_color": "#0F1412", + "theme_color": "#0F1412", + "description": "Open-source MeshCore client for LoRa mesh radios. Direct and channel chat, live node map, and repeater administration over Bluetooth, USB, or TCP.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ diff --git a/web/og-banner.png b/web/og-banner.png new file mode 100644 index 00000000..700da128 Binary files /dev/null and b/web/og-banner.png differ diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index cd4fc19b..58ed7ef3 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,15 +6,24 @@ #include "generated_plugin_registrant.h" +#include #include +#include #include #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); FlutterBluePlusPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterBluePlusPlugin")); + ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi")); SharePlusWindowsPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); + WindowManagerPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("WindowManagerPlugin")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index 533a1712..e615315f 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,9 +3,12 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows flutter_blue_plus_winrt + screen_retriever_windows share_plus url_launcher_windows + window_manager ) list(APPEND FLUTTER_FFI_PLUGIN_LIST